Example #1
0
 def run(self):
     # Listen for updates
     while True:
         update = self.updates.poll() # This will block until an update is available
         triggers = []
         if isinstance(update, Updates):
             for x in update.updates:
                 if not isinstance(x,UpdateNewChannelMessage): continue
                 if isinstance(x.message,MessageService): continue
                 # We're only interested in messages to supergroups
                 words = word_tokenize(x.message.message.lower())
                 # Avoid matching 'emacs' in 'spacemacs' and similar
                 if 'emacs' in words and x.message.to_id.channel_id not in EMACS_BLACKLIST:
                     triggers.append(('emacs',x.message))
                 if 'chrome' in words:
                     triggers.append(('chrome',x.message))
                 if 'x files theme' == x.message.message.lower() and x.message.out:
                     # Automatically reply to yourself saying 'x files theme' with the audio
                     msg = x.message
                     chan = InputPeerChannel(msg.to_id.channel_id,CHANNELS[msg.to_id.channel_id])
                     self.send_voice_note(chan,'xfiles.m4a',reply_to=msg.id)
                     sleep(1)
                 if '.shrug' in x.message.message.lower() and x.message.out:
                     # Automatically replace '.shrug' in any message you
                     # send to a supergroup with the shrug emoticon
                     msg = x.message
                     chan = InputPeerChannel(msg.to_id.channel_id,CHANNELS[msg.to_id.channel_id])
                     self(EditMessageRequest(chan,msg.id,
                         message=msg.message.replace('.shrug','¯\_(ツ)_/¯')))
                     sleep(1)
Example #2
0
async def grabUsername(e):
    global inGrab
    await e.edit(
        "__Il processo di grab è stato avviato! Per stopparlo usa .stopgrab__")
    inGrab = True
    createdPrivateChannel = await bot(
        CreateChannelRequest("BlackList", "BlackList", megagroup=False))
    newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__["id"]
    newChannelAccessHash = createdPrivateChannel.__dict__["chats"][0].__dict__[
        "access_hash"]
    desiredPublicUsername = e.text.split(" ", 1)[1].replace("@", "")
    while inGrab:
        try:
            checkUsernameResult = await bot(
                CheckUsernameRequest(
                    InputPeerChannel(channel_id=newChannelID,
                                     access_hash=newChannelAccessHash),
                    desiredPublicUsername))
            if checkUsernameResult:
                publicChannel = await bot(
                    UpdateUsernameRequest(
                        InputPeerChannel(channel_id=newChannelID,
                                         access_hash=newChannelAccessHash),
                        desiredPublicUsername))
                inGrab = False
                await e.edit("__Grab Riuscito!__")
            else:
                await asyncio.sleep(1)
        except:
            await asyncio.sleep(1)
    async def create_new_channel(
        self,
        channel_name,
        channel_desc,
        public=False,
        publicName=None,
    ):
        createdPrivateChannel = await self.client(
            CreateChannelRequest(channel_name, channel_desc, megagroup=False))
        # if you want to make it public use the rest
        if public:
            newChannelID = createdPrivateChannel.__dict__["chats"][0].__dict__[
                "id"]
            newChannelAccessHash = createdPrivateChannel.__dict__["chats"][
                0].__dict__["access_hash"]
            desiredPublicUsername = publicName
            checkUsernameResult = await self.client(
                CheckUsernameRequest(
                    InputPeerChannel(channel_id=newChannelID,
                                     access_hash=newChannelAccessHash),
                    desiredPublicUsername))
            if (checkUsernameResult == True):
                try:
                    await self.client(
                        UpdateUsernameRequest(
                            InputPeerChannel(channel_id=newChannelID,
                                             access_hash=newChannelAccessHash),
                            desiredPublicUsername))
                    return 0, "Public channel created successfully!"
                except errors.rpcerrorlist.UsernameOccupiedError:
                    return 1, "Username is already taken by someone else!"
            return 99, "Could not make the channel public..."

        return 0, "Private channel created successfully!"
Example #4
0
    def run(self):
        # Listen for updates
        while True:
            update = self.updates.poll(
            )  # This will block until an update is available
            triggers = []
            if isinstance(update, Updates):
                for x in update.updates:
                    if not isinstance(x, UpdateNewChannelMessage): continue
                    if isinstance(x.message, MessageService): continue
                    # We're only interested in messages to supergroups
                    words = word_tokenize(x.message.message.lower())
                    # Avoid matching 'emacs' in 'spacemacs' and similar
                    if 'emacs' in words and x.message.to_id.channel_id not in EMACS_BLACKLIST:
                        triggers.append(('emacs', x.message))
                    if 'chrome' in words:
                        triggers.append(('chrome', x.message))
                    if 'x files theme' == x.message.message.lower(
                    ) and x.message.out:
                        # Automatically reply to yourself saying 'x files theme' with the audio
                        msg = x.message
                        chan = InputPeerChannel(msg.to_id.channel_id,
                                                CHANNELS[msg.to_id.channel_id])
                        self.send_voice_note(chan,
                                             'xfiles.m4a',
                                             reply_to=msg.id)
                        sleep(1)
                    if '.shrug' in x.message.message.lower() and x.message.out:
                        # Automatically replace '.shrug' in any message you
                        # send to a supergroup with the shrug emoticon
                        msg = x.message
                        chan = InputPeerChannel(msg.to_id.channel_id,
                                                CHANNELS[msg.to_id.channel_id])
                        self(
                            EditMessageRequest(chan,
                                               msg.id,
                                               message=msg.message.replace(
                                                   '.shrug', '¯\_(ツ)_/¯')))
                        sleep(1)

                for trigger in triggers:
                    msg = trigger[1]
                    chan = InputPeerChannel(msg.to_id.channel_id,
                                            CHANNELS[msg.to_id.channel_id])
                    log_chat = InputPeerUser(user_id=123456789,
                                             access_hash=987654321234567890)
                    self.send_message(
                        log_chat, "{} said {} in {}. Sending react {}".format(
                            msg.from_id, msg.message,
                            CHANNELNAMES[msg.to_id.channel_id],
                            REACTS[trigger[0]][:20]))
                    react = '>{}\n{}'.format(trigger[0], REACTS[trigger[0]])
                    self.invoke(
                        SendMessageRequest(chan, react,
                                           reply_to_msg_id=msg.id))
                    sleep(1)
Example #5
0
File: tele.py Project: Dino16m/tele
def addUsersToChannel(client, users, channel):
    channelEntity = InputPeerChannel(channel.id, channel.access_hash)
    count = 0
    error = False
    success = []
    random.shuffle(users)
    us = [
        client.get_input_entity(user.username) for user in users[:50]
        if user.username is not None and rest(1) and userWasActive(user.status)
    ]
    #us = [InputPeerUser(user_id=user.id, access_hash=user.access_hash) for user in users if user.username is not None]
    usersToAdd = chunkify(us, 20)
    random.shuffle(usersToAdd)
    for usersToAdd1 in usersToAdd:
        try:
            update = client(InviteToChannelRequest(channelEntity, usersToAdd1))
            sleep(1)
        except Exception as e:
            print(e.args)
            error = True
        finally:
            if not error:
                printAddStatus(len(update.users))
                success.extend(getSuccessFromUpdate(update.users))
            error = False

        if count >= 500:
            break
        print(str(count))
        count = count + 1
    sleep(10)
    return success
Example #6
0
def main(args) -> None:
    if args.api_id > 0 and args.api_hash != '' and args.phone > 0:
        client = TelegramClient('chatwipe', args.api_id, args.api_hash)
        client.start(str('+') + str(args.phone))

        peer = choose_peer(client, args.peer)
        messages_found = get_messages(
            client, peer.id, peer.access_hash, args.until,
            client.get_me().username or client.get_me().first_name)

        if args.mode == 'delete' and len(messages_found) > 0:
            print("[WARN] Going to delete among {} messages".format(
                len(messages_found)))

        for chunk in message_chunks(messages_found, 100):
            if args.mode == 'delete':
                affected_messages = client.delete_messages(
                    InputPeerChannel(peer.id, peer.access_hash), chunk)
                print("[INFO] Deleted {} messages".format(
                    affected_messages[0].pts_count))
            elif args.mode == 'list':
                for post in chunk:
                    print("[INFO] ({}) [ID:{}]: {}".format(
                        str(post.date.strftime("%b %d %Y %H:%M:%S UTC")),
                        str(post.id), str(post.message)))

    else:
        print('[ERROR] Please provide the necessary values for the params')
Example #7
0
def add_member(chat, nickname):
    #Add users to channel, group, or megagroup
    global added_users
    global failed_users
    try:
        target_group_entity = client.get_entity(chat.id)
    except:
        sleep(10)
        target_group_entity = chat.title
    try:
        sleep(10)
        client(AddChatUserRequest(target_group_entity, nickname, 10))
    except Exception as e:
        try:
            sleep(10)
            client(InviteToChannelRequest(target_group_entity, [nickname]))
            added_users += 1
        except Exception as e:
            try:
                try:
                    sleep(10)
                    target_group_entity = chat.migrated_to
                except:
                    try:
                        sleep(10)
                        target_group_entity = InputPeerChannel(chat.id, chat.access_hash)
                    except:
                        pass
                sleep(10)
                client(InviteToChannelRequest(target_group_entity, [nickname]))
                added_users += 1
            except Exception as e:
                print(" \n-----\nusername: {}\n{}\n-----\n ".format(nickname, e))
                failed_users += 1
Example #8
0
def main(args) -> None:
    if args.api_id > 0 and args.api_hash != '' and args.phone > 0:
        client = TelegramClient('chatwipe', args.api_id, args.api_hash)
        client.start(str('+') + str(args.phone))

        peers = choose_peer(client, args.peer)
        for peer in peers:
            print(f'[INFO] Peer: {peer.title}')
            messages_found = get_messages(client, peer.id, peer.access_hash,
                                          args.until)

            if args.mode == 'delete' and len(messages_found) > 0:
                print(
                    f'[WARN] Going to delete among {len(messages_found)} messages'
                )

            for chunk in message_chunks(messages_found, 100):
                if args.mode == 'delete':
                    affected_messages = client.delete_messages(
                        InputPeerChannel(peer.id, peer.access_hash), chunk)
                    print(
                        f'[INFO] Deleted {affected_messages[0].pts_count} messages'
                    )
                elif args.mode == 'list':
                    for post in chunk:
                        print(
                            f'[INFO] ({str(post.date.strftime("%b %d %Y %H:%M:%S UTC"))}) [ID:{str(post.id)}]: {post.message}'
                        )

    else:
        print('[ERROR] Please provide the necessary values for the params')
Example #9
0
    def get_chat_messages(self, channel_name, all=False):
        """
        Функция для получения всех сообщений из чата.
        :param channel_name: имя чата (например durov)
        :param all: количество сообщений. Если False - получает последние 5к сообщений
        :return: объекты сообщений
        """
        chat_object = self.get_chat_info(channel_name)
        input_channel = InputChannel(chat_object['chat_id'], chat_object['access_hash'])
        channel = self.client.invoke(GetFullChannelRequest(input_channel)).__dict__
        chat_peer = InputPeerChannel(channel['full_chat'].id, chat_object['access_hash'])

        all_messages = []
        offset = 0
        new_messages = self.client.invoke(GetHistoryRequest(chat_peer, 0, None, offset, LIMIT, 0, 0, )).messages

        if all:
            while len(new_messages) is not 0 and offset < MESSAGES_LIMIT:
                offset += 100

                for new_message in new_messages:
                    all_messages.append(new_message.__dict__)

                new_messages = self.client.invoke(GetHistoryRequest(chat_peer, 0, None, offset, LIMIT, 0, 0)).messages
                time.sleep(1)

        else:

            for new_message in new_messages:
                all_messages.append(new_message.__dict__)

        return all_messages
Example #10
0
async def handle_message(evt: events.NewMessage.Event) -> None:
    if '*' in allowed_user and not evt.is_private:
        return
    if not (str(evt.from_id) in allowed_user and str(evt.chat_id) in allowed_user) and '*' not in allowed_user:
        log.info(f'user {evt.from_id} or {evt.chat_id} not allowed to use this bot')
        if evt.is_private:
            await evt.delete()
        return
    if str(evt.message.message).startswith('/del') and evt.reply_to_msg_id is not None:
        if bool(int(evt.is_channel)) and bool(int(evt.is_group)):
            peer = InputPeerChat(chat_id=int(evt.chat_id))
        else:
            if bool(int(evt.is_group)):
                peer = InputPeerChat(chat_id=int(evt.chat_id))
            elif bool(int(evt.is_channel)):
                peer = InputPeerChannel(channel_id=int(evt.chat_id), access_hash=0)
            else:
                peer = InputPeerUser(user_id=int(evt.chat_id), access_hash=0)
        c = cast(Message, await client.get_messages(entity=peer, ids=evt.reply_to_msg_id))
        me = await client.get_me()
        reply_msg = cast(Message, await c.get_reply_message())
        log.debug(f'msg_from={c.from_id},evt_from={evt.from_id},c is reply={c.is_reply}'
                  f',reply_msg_from={reply_msg.from_id if reply_msg is not None else 0}')
        if c.from_id == evt.from_id or (c.from_id == me.id and c.is_reply):
            if (reply_msg is not None and reply_msg.from_id == evt.from_id) or reply_msg is None:
                await client.delete_messages(evt.input_chat, [evt.reply_to_msg_id])
        await evt.delete()
    else:
        if not evt.file:
            log.info('not evt.file')
            await evt.delete()
            return
        try:
            ret = get_media_meta(evt.media)
            if ret[0] and ret[1] and ret[2] <= max_file_size:
                middle_x = StringCoder.encode(
                    f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                # url = public_url / str(pack_id(evt)) / get_file_name(evt)
                url = link_prefix / middle_x / get_file_name(evt)
                await evt.reply(f'[{url}]({url})')
                log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}')
            else:
                if admin_id == evt.from_id and ret[0]:
                    log.debug('admin usage')
                    middle_x = StringCoder.encode(
                        f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                    log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}")
                    # url = public_url / str(pack_id(evt)) / get_file_name(evt)
                    url = link_prefix / middle_x / get_file_name(evt)
                    await evt.reply(f'[{url}]({url})')
                    log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}')
                else:
                    log.info('non-admin can not serve other than image')
                    await evt.delete()
        except Exception as exp:
            await evt.reply(str(exp))
            pass
Example #11
0
 def get_input_peer(entity):
     """Gets the input peer for the given "entity" (user, chat or channel).
        Returns None if it was not found"""
     if isinstance(entity, User):
         return InputPeerUser(entity.id, entity.access_hash)
     if isinstance(entity, Chat):
         return InputPeerChat(entity.id)
     if isinstance(entity, Channel):
         return InputPeerChannel(entity.id, entity.access_hash)
Example #12
0
async def client_message(client_ms, input_peer_channels):
    for input_peer_channel in input_peer_channels:
        channel = InputPeerChannel(input_peer_channel['id'], input_peer_channel['access_hash'])
        messages = await client_ms.get_messages(channel, limit=None)
        messagesClear = []
        for x in messages:
            if (x.peer_id.channel_id in consts['check_phone_id']) and x.message == None:
                messagesClear.append(x)

        await client_ms.delete_messages(channel, messagesClear)
Example #13
0
def unpack_id(file_id: int) -> Tuple[TypeInputPeer, int]:
    is_group = file_id & group_bit
    is_channel = file_id & channel_bit
    chat_id = file_id >> chat_id_offset & pack_bit_mask
    msg_id = file_id >> msg_id_offset & pack_bit_mask
    if is_channel:
        peer = InputPeerChannel(channel_id=chat_id, access_hash=0)
    elif is_group:
        peer = InputPeerChat(chat_id=chat_id)
    else:
        peer = InputPeerUser(user_id=chat_id, access_hash=0)
    return peer, msg_id
Example #14
0
    def get_messages(self,
                     peer_id: int,
                     peer_hash: str,
                     up_to_date,
                     limit: int = 100,
                     offset_id: int = 0,
                     max_id: int = 0,
                     min_id: int = 0) -> object:
        """
        Collecting messages from defined chat peer(s) until provided date
        """

        logging.info(f'Getting messages from peer {peer_id} '
                     f'until the date {up_to_date}...')

        add_offset = 0
        messages = list()

        while True:
            time.sleep(0.1)

            search_result = self.telegram_client(
                SearchRequest(peer=InputPeerChannel(peer_id, peer_hash),
                              q='',
                              filter=InputMessagesFilterEmpty(),
                              min_date=None,
                              max_date=None,
                              offset_id=offset_id,
                              add_offset=add_offset,
                              limit=limit,
                              max_id=max_id,
                              min_id=min_id,
                              from_id=None,
                              hash=0))

            if search_result.messages:
                logging.info(
                    f'Received: {len(search_result.messages)} messages. Offset: {add_offset}.'
                )
                for post in search_result.messages:
                    if post.date.replace(tzinfo=None) > up_to_date:
                        messages.extend([post])
                        add_offset += 1
                    else:
                        return messages

            else:
                logging.info("It's stopped because met end of chat")
                return messages
Example #15
0
def get_messages(client,
                 peer_id: Union[Channel],
                 peer_hash: str,
                 delete_up_to_date,
                 limit: int = 100,
                 offset_id: int = 0,
                 max_id: int = 0,
                 min_id: int = 0) -> List[int]:

    print(
        f'[INFO] Getting messages from peer {peer_id} for user '
        f'{client.get_me().username or client.get_me().first_name} until the date {delete_up_to_date}...'
    )

    add_offset = 0
    messages: List[int] = []

    while True:
        time.sleep(0.1)

        search_result = client(
            SearchRequest(peer=InputPeerChannel(peer_id, peer_hash),
                          q='',
                          filter=InputMessagesFilterEmpty(),
                          min_date=None,
                          max_date=None,
                          offset_id=offset_id,
                          add_offset=add_offset,
                          limit=limit,
                          max_id=max_id,
                          min_id=min_id,
                          from_id=InputUserSelf(),
                          hash=0))

        if search_result.messages:
            print(
                f'[INFO] Received: {len(search_result.messages)} messages. Offset: {add_offset}.'
            )
            for post in search_result.messages:
                if post.date.replace(tzinfo=None) > delete_up_to_date:
                    messages.extend([post])
                    add_offset += 1
                else:
                    return messages

        else:
            print("[INFO] It's stopped because met end of chat.")
            return messages
Example #16
0
    async def add(self, target_group, members, from_group):
        self._run = True
        target_group_entity = InputPeerChannel(target_group.id,
                                               target_group.access_hash)
        # print(from_group)
        # print(type(from_group))
        # await self.client(ImportChatInviteRequest(from_group.access_hash))
        # print("Joined Channel")
        # await self.list_groups()
        x = 0
        phone_data = json.load(open(build_phone_path(self.phone)))
        while (self._run and x < len(members)):
            try:
                delay = TGClient.DELAY
                user = members[x]
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
                message = "Adding {name} to Group".format(name=user["name"])
                await self.client(
                    InviteToChannelRequest(target_group_entity, [user_to_add]))
            except PeerFloodError:
                delay = delay * 5
                message = "Getting Flood Error from telegram. Waiting {delay} seconds".format(
                    delay=delay)
            except UserPrivacyRestrictedError:
                message = "The user's privacy settings do not allow you to do this. Skipping."
                delay = 0.5
            except Exception as e:
                message = str(e)
                delay = 0.5

            print("USER: "******"name"])
            print("USER ID: ", user["id"])
            update_config = dict(message=message,
                                 count=x + 1,
                                 timestamp=datetime.now().timestamp() + delay)
            phone_data.update(update_config)
            save_phone(phone_data, self.phone)
            x += 1
            await asyncio.sleep(delay)
        if self._run:
            phone_data.update({"message": "All users in list processed"})
            save_phone(phone_data, self.phone)
def get_file_stream(message_ids):
    peer = InputPeerChannel(CHANNEL_REPLY_TELETHON_ID,
                            CHANNEL_REPLY_TELETHON_HASH)
    messages = []
    for message_id in message_ids:
        messages.append(
            client.get_message_history(peer, offset_id=message_id + 1,
                                       limit=1)[1][0])

    for message in messages:
        stream = BytesIO()
        thread = threading.Thread(target=client.download_media,
                                  args=(message, ),
                                  kwargs={'file': stream})
        thread.daemon = True
        thread.start()
        pos = 0
        while (thread.is_alive()):
            stream.seek(pos)
            r = stream.read()
            pos += len(r)
            yield r
Example #18
0
def makeScapeGoat(peters):
    with TelegramClient('dynasties', api_id, api_hash) as client:
        channels = getChannels(client)
        printChannels(channels)
        channel = channels['killindemsha']
        channelEntity = InputPeerChannel(channel.id, channel.access_hash)
        goats = getentity(client)
        try:
            client(InviteToChannelRequest(channelEntity, goats))
        except Exception as e:
            print(e.args)
        client.send_message('me', 'try')
        print('update is')
        print('I am ' + client.get_me().stringify())
    random.shuffle(peters)
    print(
        add(peters,
            'killindemsha',
            online=False,
            getFrom=[],
            filepath='users.txt',
            limit=1000))
Example #19
0
def scrapeGroups():
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:
                groups.append(chat)
        except:
            continue

    print('Choose a group to scrape members from:')
    i = 0
    for g in groups:
        print(str(i) + '- ' + g.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    print('Fetching Members...')
    all_participants = []
    all_participants = client.get_participants(target_group, aggressive=True)
    usernames = []
    for participant in all_participants:
        if participant.username is not None:
            usernames.append(participant.username)
        else:
            usernames.append('User type is none')
    client.send_message(
        'me',
        f"List of all users From {target_group.title}.\n Total user count {len(usernames)}"
    )
    client.send_message('me', "\n".join(usernames))
    # Adding to group
    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    for user in usernames:
        try:
            print("Adding {}".format(user))
            if user == "User type is none":
                continue
            user_to_add = client.get_input_entity(user)
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting 60 Seconds...")
            time.sleep(60)
        except PeerFloodError:
            print(
                "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
        except:
            traceback.print_exc()
            print("Unexpected Error")
            continue
 async def getmem():
     clear()
     print(colorText(wt))
     print('')
     print('')
     
     print(ye+'[+] Choose your channel to Add members.')
     a=0
     for i in channel:
         print(gr+'['+str(a)+']', i.title)
         a += 1
     opt1 = int(input(ye+'Enter a number: '))
     my_participants = await client.get_participants(channel[opt1])
     target_group_entity = InputPeerChannel(channel[opt1].id, channel[opt1].access_hash)
     my_participants_id = []
     for my_participant in my_participants:
         my_participants_id.append(my_participant.id)
     with open('channeladder_members.txt', 'r') as r:
         users = json.load(r)
     count = 1
     i = 0
     for user in users:
         if count%50 == 0:
             clear()
             print(colorText(wt))
             print('')
             print('')
             print(ye+"please wait for 1 minute...")
             time.sleep(60)
         elif count >= 300:
             await client.disconnect()
             break
         elif i >= 8:
             await client.disconnect()
             break
         count+=1
         time.sleep(1)
         if user['uid'] in my_participants_id:
             print(gr+'User present. Skipping.')
             continue
         else:
             try:
                 user_to_add = InputPeerUser(user['uid'], user['access_hash'])
                 add = await client(InviteToChannelRequest(target_group_entity,[user_to_add]))
                 print(gr+'Added ', str(user['uid']))
                 
             except PeerFloodError:
                 print(re+"Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
                 i += 1
             except UserPrivacyRestrictedError:
                 print(re+"The user's privacy settings do not allow you to do this. Skipping.")
                 i = 0
             except UserBotError:
                 print(re+"Can't add Bot. Skipping.")
                 i = 0
             except InputUserDeactivatedError:
                 print(re+"The specified user was deleted. Skipping.")
                 i = 0
             except UserChannelsTooMuchError:
                 print(re+"User in too much channel. Skipping.")
             except UserNotMutualContactError:
                 print(re+'Mutual No. Skipped.')
                 i = 0
             except Exception as e:
                 print(re+"Error:", e)
                 print("Trying to continue...")
                 i += 1
                 continue
Example #21
0
  async def EVENTER(event):
   event.original_update=event.original_update
   if type(event.original_update)is not UpdateShortMessage:
    if hasattr(event.original_update.message,'reply_markup')and type(event.original_update.message.reply_markup)is ReplyInlineMarkup:
     RQForm=MUFilter(event.original_update.message.reply_markup)
     if RQForm is not None:
      if MUFilterT(event.original_update.message.reply_markup) is None:
       if RFORMER2(RQForm).find('/vc/')>0:
        await event.message.click(2)
       else:
        print (num+"..rewarding\r")
        #ScreenMessage(Fore.GREEN+'      Requesting reward')
        UravxBuCwNMpYWTzKhcy=20
        CompteurSUC=0
        while True:
         (RQCode,RQText)=RFORMER(RQForm)
         MFINDER=BeautifulSoup(RQText,'html.parser')
         cc=MFINDER.find('div',{'class':'g-recaptcha'})
         tt=MFINDER.find('div',{'id':'headbar'})
         if RQCode==302:
          print(num+"..ok\r")
          #sys.stdout.write(Fore.MAGENTA+'[%s] STATUS: %s (%d)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'FALSE' if cc is not None else 'TRUE',CompteurSUC))
          break
         elif RQCode==200 and cc is None and tt is not None:
          TTCode=tt.get('data-code')
          TTime=tt.get('data-timer')
          TToken=tt.get('data-token')
          await event.message.click(2)
         #requests.post('http://bch.dogeclick.com/reward',data={'code':TTCode,'token':TToken},headers=BROWSER,allow_redirects=False)
          break
         elif RQCode==200 and cc is not None:
          await event.message.click(2)
          time.sleep(10)
          print(num+"..ok\r")
          #sys.stdout.write(Fore.MAGENTA+'[%s] STATUS: %s (%d)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'FALSE' if cc is not None else 'TRUE',CompteurSUC))
         CompteurSUC+=1
         time.sleep(3)
      elif MUFilterT(event.original_update.message.reply_markup) is True:
       print(num)
       if RFORMER2(RQForm).find('/jc/') >0:
        await event.message.click(3)
       else:
        username = RFORMER2(RQForm).replace('https://telegram.me/', '')
        try:
         papa = await event.client(ResolveUsernameRequest(username))
        except FloodWaitError as e :
         await PROFILER.send_message('BitcoinClick_bot','/visit')
         return
         time.sleep(3)
         #VWate(e.seconds,num)
        except UsernameNotOccupiedError:
         await event.message.click(3)
        except UsernameInvalidError:
         await event.message.click(3)
        #papa = await event.client(ResolveUsernameRequest(username))
        #ScreenMessage(Fore.BLUE+username)
        #sys.stdout.write(Fore.GREEN+'[%s]: %s (%s)\r'%(datetime.datetime.now().strftime("%H:%M:%S"),'Wait joining Channel', username))

        try:
         await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash)))
        except FloodWaitError as e:
         await PROFILER.send_message('BitcoinClick_bot','/visit')
         #VWate(e.seconds,num)
         #await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash)))
        except ChannelsTooMuchError as c:
         await main()
         try:
          await event.client(JoinChannelRequest(InputPeerChannel(papa.chats[0].id, papa.chats[0].access_hash)))
         except ChannelsTooMuchError:
          await PROFILER.send_message('BitcoinClick_bot','/visit')
        except ChannelPrivateError:
         await event.message.click(1)
        await event.message.click(1)
        time.sleep(2)
      elif MUFilterT(event.original_update.message.reply_markup) is False:
       try:
        print(num+"..ok\r")
        #print(RFORMER2(RQForm))
        await boter(RFORMER2(RQForm))
       except UsernameNotOccupiedError:
        await event.message.click(2)
       except ChatWriteForbiddenError:
        await event.message.click(2)
       except StartParamInvalidError:
        await event.message.click(2)
       except ValueError:
        await event.message.click(2)  
       time.sleep(2)
Example #22
0
def ekleyici():
    with open(f'{SESSION}bilgiler.json', 'r', encoding='utf-8') as f:
        config = json.loads(f.read())

    clientler = []
    for hesap in config:
        api_id = hesap['api_id']
        api_hash = hesap['api_hash']
        telefon = hesap['telefon']
        client = TelegramClient(f'{SESSION}{telefon}', api_id, api_hash)
        client.connect()

        if client.is_user_authorized():
            clientler.append({'telefon': telefon, 'client': client})
        else:
            print(f'{telefon} giriş yapamadı...')

    sohbetler = []
    son_tarih = None
    parca_boyutu = 200
    gruplar = []

    sonuc = clientler[-1]['client'](GetDialogsRequest(
        offset_date=son_tarih,
        offset_id=0,
        offset_peer=InputPeerEmpty(),
        limit=parca_boyutu,
        hash=0))
    sohbetler.extend(sonuc.chats)

    for sohbet in sohbetler:
        try:
            if sohbet.megagroup == True:
                gruplar.append(sohbet)
        except AttributeError:
            continue

    print('\n\tHangi Gruba SUSER Eklemek İstiyorsunuz?\n')
    say = 0
    grup_idleri = []
    for grup in gruplar:
        print(f'{say} - {grup.title}')
        grup_idleri.append(grup.id)
        say += 1

    grup_index = input("\nLütfen Numara Seçin!: ")
    eklenecek_grup = grup_idleri[int(grup_index)]

    filtrelenmis_client = []
    for sec_client in clientler:
        telefon = sec_client['telefon']
        grup_yolu = f'{GRUP}{telefon}.json'

        if os.path.isfile(grup_yolu):
            with open(grup_yolu, 'r', encoding='utf-8') as f:
                gruplar = json.loads(f.read())

            # Eğer UserBot Gruba Dahilse
            hedeflenen_grup = id_ile_grup_ver(gruplar, eklenecek_grup)
            if hedeflenen_grup:
                grup_hash = int(hedeflenen_grup['hash'])
                grubun_kendisi = InputPeerChannel(eklenecek_grup, grup_hash)

                grup_suser_yolu = f'{GRUP}{eklenecek_grup} - {telefon}.json'
                if os.path.isfile(grup_suser_yolu):
                    sec_client['eklenecek_grup'] = grubun_kendisi

                    with open(grup_suser_yolu, encoding='utf-8') as f:
                        sec_client['users'] = json.loads(f.read())

                    filtrelenmis_client.append(sec_client)
                else:
                    print(f'{telefon} kaynak grupta değil..')
                    return
            else:
                print(f'{telefon} hedef grupta değil..')
                return
        else:
            print(f'{telefon} Lütfen Session Oluşturun..')
            return

    # print(filtrelenmis_client)

    # diz_turu   = int(input("\n\n1 - KullanıcıAdıyla\n2 - ID ile\nSeçim Yapın: "))

    suser_nickleri = []
    with open('KekikSuser.json', "r+", encoding='utf-8') as json_dosyasi:
        json_suserler = json.loads(json_dosyasi.read())
        try:
            for nick in json_suserler:
                suser_nickleri.append(nick['nick'])
        except TypeError:
            suser_nickleri.extend(json_suserler)

    var_olan_kisiler = []
    v_suserler = clientler[0]['client'].get_participants(eklenecek_grup,
                                                         aggressive=True)
    for suser in v_suserler:
        if (suser.username) and (not suser.bot) and (not suser.scam) and (
                not suser.deleted):
            var_olan_kisiler.append(f'@{suser.username}')

    client_sayisi = lambda: len(filtrelenmis_client)
    print(f'\n\t[!] - {client_sayisi()} Adet - Client\'in var..')
    # kullanici_sayisi = len(filtrelenmis_client[0]['users'])

    client_index = 0
    eklenen_suser_sayisi = 0
    for suser in suser_nickleri:
        rastgele = random.randrange(len(suser_nickleri))
        bilgi = suser_nickleri[rastgele]
        if client_sayisi() == 0:
            print(
                f'\n\n\tClient Kalmadı!!\n\n\t| Toplam Eklenen : {eklenen_suser_sayisi} Kişi Oldu.."'
            )
            with open('KekikSuser.json', "w+", encoding='utf-8') as cli_bitti:
                cli_bitti.write(
                    json.dumps(suser_nickleri,
                               ensure_ascii=False,
                               sort_keys=False,
                               indent=2))
            return

        if client_index == client_sayisi():
            client_index = 0

        if (not bilgi) or (bilgi in var_olan_kisiler):
            suser_nickleri.remove(bilgi)
            continue

        uyku = lambda: time.sleep(random.randrange(
            1, 3))  # Burası eklemeler arası bekleme süresi saniye cinsinden
        gecerli_client = filtrelenmis_client[client_index]
        try:
            eklenecek_suser = gecerli_client['client'].get_input_entity(bilgi)

            print(
                f"\n\n[~] {gecerli_client['telefon']} | {bilgi}\'i Eklemeyi Deniyorum.."
            )
            gecerli_client['client'](InviteToChannelRequest(
                gecerli_client['eklenecek_grup'], [eklenecek_suser]))
            eklenen_suser_sayisi += 1
            print(
                f"[+] {bilgi}\'i Ekledim\t| Toplam Eklenen : {eklenen_suser_sayisi} Kişi Oldu.."
            )

            client_index += 1
            uyku()
            continue
        except PeerFloodError as flood:
            print(
                f'[!] Takıldı | Flood Yemişsin Kanka.. » ({flood}) | {gecerli_client["telefon"]} Düşürdüm..'
            )
            filtrelenmis_client.remove(gecerli_client)
            gecerli_client['client'].disconnect()
            client_index = 0
            print(f'\n\t[!] - {client_sayisi()} Adet - Client\'in Kaldı..!!')
            uyku()
            continue
        except UserPrivacyRestrictedError:
            print('[!] Takıldı | Malesef Gizlilik Ayarları Kanka..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UserNotMutualContactError:
            print('[!] Kullanıcı Karşılıksız İletişim Hatası..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UserChannelsTooMuchError:
            print('[!] Takıldı | Kullanıcı Çok Fazla Yere Üye..')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except ChannelInvalidError:
            print('[!] Takıldı | ChannelInvalidError')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except UsernameNotOccupiedError:
            print('[!] Takıldı | UsernameNotOccupiedError')
            suser_nickleri.remove(bilgi)
            client_index += 1
            uyku()
            continue
        except FloodWaitError as fw:
            print(f"\t[!] Takıldı | ({fw}) | {bilgi}")
            fw_suresi = int(str(fw).split()[3])
            if fw_suresi > 1000:
                filtrelenmis_client.remove(gecerli_client)
                gecerli_client['client'].disconnect()
                client_index = 0
                print(
                    f'\n\t[!] - {client_sayisi()} Adet - Client\'in Kaldı..!!')
            continue
        except Exception as hata:
            print(f"\t[!] Takıldı | ({type(hata).__name__}) | {hata}")
            continue
Example #23
0
filter_clients = []

for my_client in clients:
    phone = my_client['phone']
    path_group = root_path + '/data/group/' + phone + '.json'
    if os.path.isfile(path_group):

        with open(path_group, 'r', encoding='utf-8') as f:
            groups = json.loads(f.read())

        current_target_group = get_group_by_id(groups, group_target_id)

        if current_target_group:
            group_access_hash = int(current_target_group['access_hash'])
            target_group_entity = InputPeerChannel(group_target_id,
                                                   group_access_hash)

            path_group_user = root_path + '/data/user/' + phone + "_" + str(
                group_source_id) + '.json'
            if os.path.isfile(path_group_user):
                # add target_group_entity key value
                my_client['target_group_entity'] = target_group_entity

                with open(path_group_user, encoding='utf-8') as f:
                    my_client['users'] = json.loads(f.read())

                filter_clients.append(my_client)
            else:
                print('This account with phone ' + str(phone) +
                      ' is not in source group')
        else:
Example #24
0
	def run(self):
		def load_conf():
			print("Cargando conf cliente")
			conf_dict = self.config.conf_dict
			self.bot_token = conf_dict['bot_token']
			self.api_id = conf_dict['api_id']
			self.api_hash = conf_dict['api_hash']
			self.phone = conf_dict['phone']
			self.channels = conf_dict['channels']
			self.keywords = conf_dict['keywords']
			return True


		# Solicita al cliente que recargue la conf
		def reload_conf_req():
			load_conf()
			try:
				req = Packet(cons.RELOAD_CONF, None)
				self.queue_to_bot.put(req)

				# Espera bloqueante del cliente
				try:
					reply = self.queue_to_bot.get(True, 5)

					if reply.reply_code is False:
						print("Cli: reload_conf_req")

				except Empty:
					print("Cli: reload_conf_req")

			except Exception as e:
				print("Excepcion:", e)

		def queue_check():
			while True:
				try:
					req = self.queue_to_cli.get(block=True)
					print("Cli receive: ", req)

					if req.request_code == cons.ADD_CHANNEL:
						add_channel(req)
					elif req.request_code == cons.RELOAD_CONF:
						load_conf()


				except Empty:
					pass

		def bot_send_msg(text):
			packet = Packet(cons.SEND_MSG, text)
			self.queue_to_bot.put(packet)
			time.sleep(1)  # Evitar floodwait exception

		def channel_exists(id_channel):
			try:
				# channel = self.client(ResolveUsernameRequest(username=id_channel))
				tl_channel = self.client.get_entity(id_channel)
				return tl_channel
			except UsernameNotOccupiedError as e:
				print("check_channel: '" + id_channel + "' no existe")
				return None
			except Exception as e:
				print("Error channel_exists: ", e)
				return None

		def add_channel(req):
			# ID, alias o url

			tl_channel = channel_exists(req.request_data)

			if tl_channel is None:
				req.reply_code = False
				req.reply_data = "El canal no existe"
			elif type(tl_channel) == telethon.tl.types.User:
				req.reply_code = False
				req.reply_data = "El ID se corresponde al de un usuario. " \
				                 "Los chats de usuario no estan soportados"
			else:

				# Ya existe en la conf?
				exists = False
				for ch in self.channels:
					if ch.id == tl_channel.id:
						exists = True

				if exists:
					req.reply_code = False
					req.reply_data = "El canal ya estaba guardado"
				else:
					try:
						channel_info = self.client(GetChannelsRequest([tl_channel]))
						if channel_info.chats[0].left is True:
							join_result = self.client(JoinChannelRequest(tl_channel))
							req.reply_code = True
							req.reply_data = "Te has unido al canal: " + tl_channel.title
							self.queue_to_bot.put(req)

					except Exception as e:
						req.reply_code = False
						req.reply_data = "Error al unirse al canal " + tl_channel.title
						self.queue_to_bot.put(req)
						print(req.reply_data)
						print(e)
						return False

					channel_custom = ChannelCustom(tl_channel.id, tl_channel.access_hash, tl_channel.username,
					                               tl_channel.title)

					self.channels.append(channel_custom)
					success = self.config.save_var("Config", "channels", self.channels)

					if success is True:
						req.reply_code = True
						req.reply_data = "Se ha añadido el canal: " + tl_channel.title
						reload_conf_req()
					else:
						req.reply_code = False
						req.reply_data = "Error al guardar el fichero de conf"

			self.queue_to_bot.put(req)


		def filter_tl_update(update):
			#print("Cli tl update:", update)
			# UpdateNewChannelMessage(message=Message (out=False, mentioned=False, media_unread=False, silent=False, post=True, id=1052, from_id=None, to_id=PeerChannel(channel_id=1263221050), fwd_from=None, via_bot_id=None, reply_to_msg_id=None, date=datetime.utcfromtimestamp(1523628439), message='Fri Apr 13 18:07:17 2018 YES!', media=None, reply_markup=None, entities=[], views=1, edit_date=None, post_author=None, grouped_id=None), pts=1053, pts_count=1)

			if type(update) is not UpdateNewChannelMessage:
				return

			from_channel_id = update.message.to_id.channel_id
			message = update.message.message

			channel_match = False
			for ch in self.channels:
				if ch.id == from_channel_id:
					channel_match = True
					ch.last_msg = update.message.id
					self.config.save_var("Config", "channels", self.channels)
					break

			if channel_match:
				check_msg_match(message)

		def check_msg_match(msg):
			for keyword in self.keywords:

				pattern = re.compile(keyword, re.IGNORECASE)
				msg_match = pattern.search(msg)

				if msg_match:
					# Telegram BOT API message
					bot_send_msg(msg)
					print("Cli: message match -> send to bot ("+msg[0:10]+")")
					break



		#################################################
		#                 EJECUCION CLIENTE             #
		#################################################
		print("\n\n", __file__, ": ", time.strftime("%Y-%m-%d %H:%M"), "\n")
		print("Ejecutando Client")
		load_conf()


		# Conectamos la API cliente
		self.client = TelegramClient('client', self.api_id, self.api_hash, update_workers=1)
		self.client.connect()

		# Comprobamos si tenemos autorizacion o solicitamos el codigo a tl y al user
		try:
			if not self.client.is_user_authorized():
				self.client.send_code_request(self.phone)

				request = Packet(cons.ASK_TL_AUTH_CODE, None)
				self.queue_to_bot.put(request)

				try:
					req = self.queue_to_cli.get(block=True, timeout=cons.AUTH_CODE_TIMEOUT)
					if req.request_code is cons.ASK_TL_AUTH_CODE_REPLY:
						self.client.sign_in(phone=self.phone, code=req.request_data)

				except Empty:
					error = "Client: Codigo autorizacion telegram no recibido, terminando cliente"
					print("WARNING: " + error)
					bot_send_msg(error)
					sys.exit()

		except ApiIdInvalidError as err:
			print("WARNING Client: API_ID/API_HASH invalidas")
			print(err)
			bot_send_msg("Error de configuracion del cliente: API_ID/API_HASH invalidas."
			                                "\nRevisa la configuracion y vuelve a lanzar el cliente /client_launch")
			sys.exit()

		except PhoneNumberInvalidError as err:
			print("WARNING Client: Numero de telefono (Phone) invalido")
			print(err)
			bot_send_msg("Error de configuracion del cliente: Numero de telefono (Phone) invalido."
			                                "\nRevisa la configuracion y vuelve a lanzar el cliente /client_launch")
			sys.exit()

		except Exception as err:
			error = "Cliente: "+str(err)
			print("WARNING ", error, type(err))
			bot_send_msg(error)
			sys.exit()


		# Hacer consulta a tl para verificar inicio correcto
		try:
			if type(self.client.get_me()) is not User:
				raise Exception

			bot_send_msg("Cliente iniciado con éxito")

		except Exception as err:
			error = "Cliente: error al iniciar cliente.\n"+str(err)
			print("WARNING error al iniciar cliente.\n", error, type(err))
			bot_send_msg(error)
			sys.exit()


		# Comprobar que el cliente esta unido a los canales guardados
		for channel in self.channels:
			try:
				ch = InputPeerChannel(channel.id, channel.access_hash)
				self.client(JoinChannelRequest(ch))
			except Exception as e:
				print("Warning JoinChannelRequest:", e)
				bot_send_msg("Error al unirse al canal "+channel.title)


		# Revisar mensajes omitidos si la app ha estado apagada
		for ch in self.channels:

			print("Solicitando mensajes antiguos del canal", ch.title)
			print("Msg min_id: ", ch.last_msg)

			date_now = datetime.datetime.now()
			date_old = date_now - datetime.timedelta(hours=cons.OFFLINE_MAX_HOUR_RETRIEVE)
			try:
				query = self.client(GetHistoryRequest(
					peer=InputPeerChannel(ch.id, ch.access_hash),
					limit=cons.OFFLINE_MAX_MSG_RETRIEVE_PER_CHANNEL,  # Max number of msg get from channel
					offset_date=date_old,  # Only msgs in last 24h
					add_offset=0,
					offset_id=0,
					max_id=0,
					min_id=ch.last_msg,  # Only request msg no procesados
					hash=0
				))

				# Una vez tenemos los mensajes nuevos, analizarlos
				messages = query.messages
				for msg in messages:
					if type(msg) is Message:
						# print(msg)
						check_msg_match(msg.message)
					else:
						print("Warning Cli: unkown msg type", type(msg), msg)

				# Guardar el id del ultimo mensaje procesado
				if messages:
					ch.last_msg = messages[0].id
					self.config.save_var("Config", "channels", self.channels)
			except Exception as err:
				error = "Cliente: " + str(err)
				print("WARNING ", error, type(err))
				bot_send_msg(error)



		thread_queue = Thread(target=queue_check)
		thread_queue.daemon = True
		thread_queue.start()






		# Bucle polling updates telegram & threads queue
		while True:
			try:
				tl_update = self.client.updates.poll()
				filter_tl_update(tl_update)

			except KeyboardInterrupt:
				break
			except Exception as e:
				print("Error: ", e)

		self.client.disconnect()
def ekle():
	nya = c.RawConfigParser() #Grup keylerini oku
	nya.read('degerler.veri')
	cfg = nya['veri'] ['config_no']
	satno = nya['veri'] ['satir_no']
	kissay = nya['veri'] ['kisi_sayisi']
	group_username = nya['veri'] ['kanal_grup_adi']
	ags = nya['veri'] ['aktif_gun_sayisi']
	bsk = nya['veri'] ['beklenicek_sure_kucuk']
	bsb = nya['veri'] ['beklenicek_sure_buyuk']
	intsatno = int(satno)
	intkissay = int(kissay)
	intags = int(ags)
	intbsk = int(bsk)
	intbsb = int(bsb)
	cpass = c.RawConfigParser()
	cpass.read(cfg)
	try:
		api_id = cpass['cred']['id']
		api_hash = cpass['cred']['hash']
		phone = cpass['cred']['phone']
		client = TelegramClient(phone, api_id, api_hash)
	except KeyError:
		sys.exit(1)
	client.connect()
	if not client.is_user_authorized():
		client.send_code_request(phone)
		os.system('cls')
		client.sign_in(phone, input('[+] Enter the code telegram send : '))
	client(JoinChannelRequest(channel=group_username))
	os.system('cls')
	users = []
	with open("grup_uyeleri.csv","r", encoding='UTF-8') as fd:
		rows = csv.reader(fd,delimiter=",",lineterminator="\n")
		for row in islice(csv.reader(fd),intsatno,None):
			user = {}
			user['username'] = row[0]
			user['id'] = int(row[1])
			user['access_hash'] = int(row[2])
			user['name'] = row[3]
			users.append(user)
	chats = []
	last_date = None
	chunk_size = 200
	groups=[]
	result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
	chats.extend(result.chats)
	for chat in chats:
		try:
			check=client.get_entity(group_username)
			if check.id==chat.id:
				groups.append(chat)
		except:
			continue
	i=0
	for group in groups:
		print('['+str(i)+']' '-' +group.title)
		i+=1
	g_index=0
	target_group=groups[int(g_index)]
	target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash)
	mode=1
	max_user_to_add=0
	for user in users:
			try:
				max_user_to_add+=1
				if max_user_to_add==intkissay:
					client(LeaveChannelRequest(channel=group_username))
					os._exit(1)
				print (phone+" Kullanici ekleniyor {}".format(user['id']))
				if mode == 1:
					if user['username'] == "":
						continue
					user_to_add = client.get_input_entity(user['username'])
				elif mode == 2:
					user_to_add = InputPeerUser(user['id'], user['access_hash'])
				else:
					sys.exit("[!] Gecersiz secenek secildi. Tekrar dene.")
				try:
					client(InviteToChannelRequest(target_group_entity,[user_to_add]))
					print("[+] Rastgele "+intbsk+" ila "+intbsb+" sn bekleniyor.")
					time.sleep(random.randrange(intbsk,intbsb))
				except:
					traceback.print_exc()
					print("[+] HATA Rastgele 11 ila 23 sn bekleniyor.")
					time.sleep(random.randrange(11,23))
					continue
			except PeerFloodError:
				print("[!] Telegrama fazla istek attigimiz icin hatayla karsilastik. Bot Durduruldu.")
				while(True):
					time.sleep(random.randrange(11,23))
			except UserPrivacyRestrictedError:
				print("[!] Kullanicinin gizlilik ayarlari yuzunden eklenemedi. Atlaniyor.")
				time.sleep(random.randrange(11,23))
				max_user_to_add-=1
			except UserNotMutualContactError:
				print("[!] User not mutual contact hatasi alindi. Devam ediliyor.")
				time.sleep(random.randrange(12,22))
				max_user_to_add-=1
			except UserKickedError:
				print("[!] Bu kullanici bu grupdan daha once atilmis. Atlaniyor.")
				time.sleep(random.randrange(9,21))
				max_user_to_add-=1
			except:
				traceback.print_exc()
				print("[!] Beklenmeyen Hata")
				time.sleep(random.randrange(14,25))
				max_user_to_add-=1
				continue
Example #26
0
result = client(
    GetDialogsRequest(offset_date=None,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=200,
                      hash=0))

client.send_message('me', 'Hello, myself!')

for chat in result.chats:
    if target_id == int(chat.id):
        print('found target_id')
        if type(chat) == Chat:
            target_entity = InputPeerChat(chat.id)
        if type(chat) == Channel:
            target_entity = InputPeerChannel(chat.id, chat.access_hash)

for chat in result.chats:
    if type(chat) == Chat:
        chat_groups.append(chat)
    elif type(chat) == Channel:
        channel_groups.append(chat)

print('\nChats')
for chat in chat_groups:
    print(chat)

print("\nChannel")
for channel in channel_groups:
    print(channel)
Example #27
0
def add_users_to_group():
    input_file = sys.argv[1]
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['username'] = row[0]
            try:
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
            except IndexError:
                print('users without id or access_hash')
            users.append(user)

    random.shuffle(users)
    chats = []
    last_date = None
    chunk_size = 10
    groups = []

    result = client(
        GetDialogsRequest(offset_date=last_date,
                          offset_id=0,
                          offset_peer=InputPeerEmpty(),
                          limit=chunk_size,
                          hash=0))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat.megagroup == True:  #Condition To Only List Megagroups
                groups.append(chat)
        except:
            continue

    print('Choose a group to add members:')
    i = 0
    for group in groups:
        print(str(i) + '- ' + group.title)
        i += 1

    g_index = input("Enter a Number: ")
    target_group = groups[int(g_index)]
    print('\n\nChosen Group:\t' + groups[int(g_index)].title)

    target_group_entity = InputPeerChannel(target_group.id,
                                           target_group.access_hash)

    mode = int(input("Enter 1 to add by username or 2 to add by ID: "))

    error_count = 0

    for user in users:
        try:
            print("Adding {}".format(user['username']))
            if mode == 1:
                if user['username'] == "":
                    continue
                user_to_add = client.get_input_entity(user['username'])
            elif mode == 2:
                user_to_add = InputPeerUser(user['id'], user['access_hash'])
            else:
                sys.exit("Invalid Mode Selected. Please Try Again.")
            client(InviteToChannelRequest(target_group_entity, [user_to_add]))
            print("Waiting 3 Seconds...")
            time.sleep(3)
        except PeerFloodError:
            print(
                "Getting Flood Error from Telegram. You should stop script now.Please try again after some time."
            )
        except UserPrivacyRestrictedError:
            print(
                "The user's privacy settings do not allow you to do this. Skipping."
            )
        except:
            traceback.print_exc()
            print("Unexpected Error")
            error_count += 1
            if error_count > 10:
                sys.exit('too many errors')
            continue
Example #28
0
#Fetching participants from server
all_participants = []
print('Fetching Members...')

try:
    all_participants = client.get_participants(target_group_scrapper, aggressive=True)
except: 
    print("Unable to fetch participants of", target_group_scrapper)
    exit()

if len(all_participants) == 0:
    print("No user found in", target_group_scrapper + '.', "Please check the group.")
    exit()

try:
    target_group_entity_adder = InputPeerChannel(target_group_adder.id, target_group_adder.access_hash)
    isChannel = True
except:
    target_group_entity_adder = InputPeerChat(target_group_adder.id)
    isChannel = False

n = 0
user_added_count = 0



for i in range(start_index,len(all_participants)):
    user = all_participants[i]
    n += 1
    if n % 50 == 0:
        time.sleep(900)
Example #29
0
    try:
        if chat.megagroup == True:
            groups.append(chat)
    except:
        continue

print(gr+'Choose a group to add members:'+cy)
i = 0
for group in groups:
    print(str(i) + '- ' + group.title)
    i += 1

g_index = input(gr+"Enter a Number: "+re)
target_group = groups[int(g_index)]

target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash)

mode = int(input(gr+"Enter 1 to add by username or 2 to add by ID: "+cy))

n = 0

for user in users:
    n += 1
    if n % 80 == 0:
        sleep(60)
    try:
        print("Adding {}".format(user['id']))
        if mode == 1:
            if user['username'] == "":
                continue
            user_to_add = client.get_input_entity(user['username'])
Example #30
0
def addermulti():
    g_scrape_id = ''
    g_id = ''

    def add_credentials():
        if os.path.isfile(os.path.join(os.getcwd(),
                                       'multiconfig.json')) == True:
            with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                      'r') as config_file:
                data = json.load(config_file)

                print(f'Credentials found, for {len(data)} Telegram accounts')
                for cred in data:
                    print(
                        f'Checking if two factor authentication is already done with {cred["phone"]}'
                    )
                    client = TelegramClient(cred['phone'], cred['api_id'],
                                            cred['api_hash'])

                    async def main():
                        # Now you can use all client methods listed below, like for example...
                        await client.send_message('me', 'Hello !!!!!')

                    with client:
                        client.loop.run_until_complete(main())
                    client.connect()
                    if not client.is_user_authorized():
                        print(
                            f'Sending request code to {cred["phone"]}, please authenticate'
                        )
                        client.send_code_request(phone)
                        client.sign_in(cred["phone"], input('40779'))
                    else:
                        print(
                            f'Good! Client {cred["phone"]} is authenticated, I can use it.'
                        )
                    client.disconnect()

            print(f'Credentials found, for {len(data)} Telegram accounts')
            while True:
                question = input(
                    'Do you want to use these credentials?[y/n] ').lower()
                if question == 'y':
                    break
                elif question == 'n':
                    print('Good, lets define new credentials...')
                    ammount_of_credentials = int(
                        input('How many accounts do you want to add?'))
                    credentials = []
                    for i in range(ammount_of_credentials):
                        phone = input('Type the phone number: ')
                        api_id = input(f'Type {phone} api id: ')
                        api_hash = input(f'Type {phone} api hash: ')

                        config = {}
                        config['api_id'] = api_id
                        config['api_hash'] = api_hash
                        config['phone'] = phone
                        credentials.append(config.copy())

                        with open(
                                os.path.join(os.getcwd(), 'multiconfig.json'),
                                'w') as config_file:
                            json.dump(credentials, config_file, indent=2)

                        client = TelegramClient(phone, api_id, api_hash)

                        async def main():
                            # Now you can use all client methods listed below, like for example...
                            await client.send_message('me', 'Hello !!!!!')

                        with client:
                            client.loop.run_until_complete(main())
                        client.connect()
                        if not client.is_user_authorized():
                            print(
                                f'Sending request code to {phone}, please authenticate'
                            )
                            client.send_code_request(phone)
                            client.sign_in(phone, input('40779'))
                        else:
                            print(
                                f'Good! Client {phone} is authenticated, I can use it.'
                            )
                        client.disconnect()
                    break
        else:
            print('No credentials found. Lets define new ones')
            ammount_of_credentials = int(
                input('How many accounts do you want to add?'))
            credentials = []
            for i in range(ammount_of_credentials):
                phone = input('Type the phone number: ')
                api_id = input(f'Type {phone} api id: ')
                api_hash = input(f'Type {phone} api hash: ')

                config = {}
                config['api_id'] = api_id
                config['api_hash'] = api_hash
                config['phone'] = phone
                credentials.append(config.copy())

                with open(os.path.join(os.getcwd(), 'multiconfig.json'),
                          'w') as config_file:
                    json.dump(credentials, config_file, indent=2)

                client = TelegramClient(phone, api_id, api_hash)

                async def main():
                    # Now you can use all client methods listed below, like for example...
                    await client.send_message('me', 'Hello !!!!!')

                with client:
                    client.loop.run_until_complete(main())
                client.connect()
                if not client.is_user_authorized():
                    print(
                        f'Sending request code to {phone}, please authenticate'
                    )
                    client.send_code_request(phone)
                    client.sign_in(phone, input('40779'))
                else:
                    print(
                        f'Good! Client {phone} is authenticated, I can use it.'
                    )
                client.disconnect()

    add_credentials()

    with open(os.path.join(os.getcwd(), 'multiconfig.json'),
              'r') as config_file:
        credentials = json.load(config_file)

    for config in credentials:
        api_id = config['api_id']
        api_hash = config['api_hash']
        phone = config['phone']

        AMMOUNT_OF_FLOOD_ERROS = 0
        AMMOUNT_OF_USERS_ADDED = 0
        print(f'Now trying use account {phone}')

        try:
            client = TelegramClient(phone, api_id, api_hash)

            async def main():
                # Now you can use all client methods listed below, like for example...
                await client.send_message('me', 'Hello !!!!!')

            SLEEP_TIME_1 = 100
            SLEEP_TIME_2 = 100
            with client:
                client.loop.run_until_complete(main())
            client.connect()
            if not client.is_user_authorized():
                client.send_code_request(phone)
                client.sign_in(phone, input('40779'))

            chats = []
            last_date = None
            chunk_size = 200
            groups = []

            result = client(
                GetDialogsRequest(offset_date=last_date,
                                  offset_id=0,
                                  offset_peer=InputPeerEmpty(),
                                  limit=chunk_size,
                                  hash=0))
            chats.extend(result.chats)

            for chat in chats:
                try:
                    if chat.megagroup == True:
                        groups.append(chat)
                except:
                    continue

            try:
                print('Which Group Do You Want To Scrape Members From: ')
                i = 0

                for g in groups:
                    g.title = g.title.encode('utf-8')
                    g.title = g.title.decode('ascii', 'ignore')
                    print(f'[Group]: {str(g.title)} [Id]: {str(g.id)}')
                    i += 1

                if g_scrape_id == '':
                    g_scrape_id = input(
                        "Please! Enter the group to scrape id: ").strip()

                for group in groups:
                    if str(group.id) == g_scrape_id:
                        target_group_scrape = group

                print('Fetching Members...')
                all_participants_to_scrape = []
                all_participants_to_scrape = client.get_participants(
                    target_group_scrape, aggressive=True)

                print('Saving In file...')

                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          'w+') as f:
                    users = []
                    jsonuser = {}
                    for user in all_participants_to_scrape:
                        jsonuser.clear()
                        if user.username:
                            username = user.username
                        else:
                            username = ""
                        if user.first_name:
                            first_name = user.first_name
                        else:
                            first_name = ""
                        if user.last_name:
                            last_name = user.last_name
                        else:
                            last_name = ""
                        name = (first_name + ' ' + last_name).strip()
                        jsonuser['username'] = username
                        jsonuser['id'] = user.id
                        jsonuser['access_hash'] = user.access_hash
                        jsonuser['name'] = name
                        users.append(jsonuser.copy())
                    json.dump(users, f, indent=2)

                print('Members scraped successfully.......')

                users = []
                with open(os.path.join(os.getcwd(), 'Scraped.json'),
                          "r",
                          encoding='utf-8',
                          errors='ignore') as f:
                    list = json.load(f, strict=False)
                    for dict in list:
                        user = {}
                        user['username'] = dict['username']
                        user['id'] = dict['id']
                        user['access_hash'] = dict['access_hash']
                        user['name'] = dict['name']
                        users.append(user)

            except Exception as e:
                print(e)

            print('Choose a group to add members:')
            i = 0
            for group in groups:
                group.title = group.title.encode('utf-8')
                group.title = group.title.decode('ascii', 'ignore')
                print(f'[Group]: {str(group.title)} [Id]: {str(group.id)}')
                i += 1

            if g_id == '':
                g_id = input("Enter the group Id: ")

            for group in groups:
                if g_id == str(group.id):
                    target_group = group

            #Start of scrappe members from that group to avoid repetition

            try:
                all_participants = []
                all_participants = client.get_participants(target_group,
                                                           aggressive=True)

                scrapedusers = []
                jsonuser = {}
                for user in all_participants:
                    jsonuser.clear()
                    if user.username:
                        username = user.username
                    else:
                        username = ""
                    if user.first_name:
                        first_name = user.first_name
                    else:
                        first_name = ""
                    if user.last_name:
                        last_name = user.last_name
                    else:
                        last_name = ""
                    name = (first_name + ' ' + last_name).strip()
                    jsonuser['username'] = username
                    jsonuser['id'] = user.id
                    jsonuser['access_hash'] = user.access_hash
                    jsonuser['name'] = name
                    scrapedusers.append(jsonuser.copy())

                print('Members scraped successfully.......')
            except:
                print(
                    'Error scrapping members of this group. Danger of false positives.'
                )

            #End of scrappe members of that group to avoid repetition

            target_group_entity = InputPeerChannel(target_group.id,
                                                   target_group.access_hash)

            # mode = int(input("Enter 1 to add by username or 2 to add by ID: "))
            mode = 2

            n = 0

            try:
                with open(os.path.join(os.getcwd(), 'tried.json'),
                          'r') as file:
                    tried = json.load(file)
            except:
                tried = []

            for user in users:
                if AMMOUNT_OF_FLOOD_ERROS > 10:
                    print(
                        'UPS, GOT 10 FLOOD ERRORS, SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if AMMOUNT_OF_USERS_ADDED >= 45:
                    print(
                        'GREAT! ADDED 45 USERS WITH THIS NUMBER TODAY. SWITCHING TO THE NEXT ACCOUNT'
                    )
                    break
                if user not in scrapedusers:
                    if user not in tried:
                        tried.append(user.copy())
                        with open(os.path.join(os.getcwd(), 'tried.json'),
                                  'w+') as file:
                            json.dump(tried, file, indent=2)
                        try:
                            n += 1
                            if n % 80 == 0:
                                sleep(60)
                            try:
                                print("Trying to add user {}".format(
                                    user['id']))
                                if mode == 1:
                                    if user['username'] == "":
                                        continue
                                    user_to_add = client.get_input_entity(
                                        user['username'])
                                elif mode == 2:
                                    user_to_add = InputPeerUser(
                                        user['id'], user['access_hash'])
                                else:
                                    sys.exit(
                                        "Invalid Mode Selected. Please Try Again."
                                    )
                                client(
                                    InviteToChannelRequest(
                                        target_group_entity, [user_to_add]))
                                print("Waiting for 60-180 Seconds...")
                                time.sleep(random.randrange(60, 90))
                            except PeerFloodError:
                                AMMOUNT_OF_FLOOD_ERROS += 1
                                print(
                                    "Getting Flood Error from telegram. Script is stopping now. Please try again after some time."
                                )
                                print(
                                    "Waiting {} seconds".format(SLEEP_TIME_2))
                                time.sleep(SLEEP_TIME_2)
                                continue  #continues adicionado por mim
                            except UserPrivacyRestrictedError:
                                print(
                                    "The user's privacy settings do not allow you to do this. Skipping."
                                )
                                print("Waiting for 5 Seconds...")
                                time.sleep(random.randint(
                                    0, 5))  #Alterei, antes era randrange(5,0)
                                continue  # adicionado por mim
                            except UserNotMutualContactError:
                                continue
                            except UserChannelsTooMuchError:
                                print(
                                    'This user is already in too many channels/supergroups.'
                                )
                                continue
                            except Exception as e:
                                # traceback.print_exc()
                                print(f"Unexpected Error: {e}")
                                continue
                            AMMOUNT_OF_USERS_ADDED += 1

                            try:
                                with open(
                                        os.path.join(os.getcwd(),
                                                     'added.json'),
                                        'r') as file:
                                    added = json.load(file)
                                    added.append(user.copy())
                            except:
                                added = []

                            with open(os.path.join(os.getcwd(), 'added.json'),
                                      'w+') as file:
                                json.dump(added, file, indent=2)
                                try:
                                    print(
                                        f'User {user["name"]} with id: {user["id"]} has been sucessfully added to your group.'
                                    )
                                except UnicodeEncodeError:
                                    print(
                                        f'User with id: {user["id"]} has been sucessfully added your group.'
                                    )

                        except Exception as e:
                            print(f'An unnespected error ocureed: {e}')

                    else:
                        print(
                            f'This user has been checked by me before. Skipping. If you want o erase data, delete "tried.json".'
                        )
                else:
                    print('This user already is in this group. Skipping.')
        except Exception as e:
            e = str(e)
            print(e)
            try:
                client.disconnect()
            except:
                print('Unable to disconnect client')
                time.sleep(30000)
            if 'database' in e:
                print(
                    'The last time program was executed it was not closed properly. Please delete the .session files and restart the program.'
                )
                time.sleep(30000)
                try:
                    client.disconnect()
                except:
                    print('Unable to disconnect client')

        try:
            client.disconnect()
        except:
            print('Unable to disconnect client')