Example #1
0
class Client():
    def __init__(self, phone, api_id, api_hash):
        self.phone = phone
        self.api_id = api_id
        self.available = True
        self.client = TelegramClient(phone, api_id, api_hash)
        self.client.connect()
        if not self.client.is_user_authorized():
            self.client.send_code_request(phone)
            self.client.sign_in(phone, input('Enter the code: '))
        self.client.disconnect()

    def send_message(self, participant, message):
        try:
            self.client.connect()
            self.client.send_message(participant.id, message)
            self.client.disconnect()
        except FloodWaitError:
            self.available = False
        except PeerFloodError:
            self.available = False
        except:
            self.client.disconnect()

    def send_messages(self, participant, messages, tempo):
        self.client.connect()
        for message in messages:
            self.client.invoke(
                SendMessageRequest(self.client.get_input_entity(participant),
                                   message))
            #self.client.send_message(participant.id, message)
            time.sleep(tempo)
        self.client.disconnect()

    def connect(self):
        self.client.connect()

    def disconnect(self):
        self.client.disconnect()

    def is_available(self):
        return self.available

    def get_entity(self, entity):
        return self.client.get_entity(entity)

    def invoke(self, request):
        return self.client.invoke(request)
Example #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
Example #3
0
def all_list(request):
    data = {}
    data_list = []
    api_id = 169722
    api_hash = 'b4d4b4374d60a3ba9d7ee84ce010e2b2'
    phone = '+918962141530'
    client = TelegramClient('+918962141530', api_id, api_hash)
    client.session.try_load_or_create_new(session_user_id='+918962141530')
    if client.connect():

        contacts = client.invoke(GetContactsRequest(0))
        users = contacts.users
        for user in users:

            data_list.append({
                'id': user.id,
                'first_name': user.first_name,
                # 'status':user.status,
                'phone': user.phone,
            })

        data = list(data_list)
        import pdb
        pdb.set_trace()
        return HttpResponse(json.dumps(data), content_type="application/json")

    data = {'message': 'otp genrated', 'status': 404}
    return HttpResponse(json.dumps(data), content_type="application/json")
Example #4
0
 def get_updates(self, client: TelegramClient):
     updates = client.invoke(
         GetChannelDifferenceRequest(get_input_peer(self.channel),
                                     ChannelMessagesFilterEmpty(), self.pts,
                                     -1))
     if type(updates) is ChannelDifference:
         self.pts = updates.pts
         return updates
     elif type(updates) is ChannelDifferenceTooLong:
         self.pts = updates.pts
         return updates
     else:
         return None
#!/usr/bin/env python3

from telethon import TelegramClient
from telethon import utils
from telethon.utils import get_display_name
from telethon.tl.functions.messages import DeleteMessagesRequest

api_id = int(os.environ.get('TELEGRAM_API_ID'))
api_hash = os.environ.get('TELEGRAM_API_HASH')

client = TelegramClient(os.environ.get('TELEGRAM_API_NAME'), api_id, api_hash)
client.start()

for val in client.get_dialogs(limit=None):
    for message in client.iter_messages(val.id, limit=None):
        result = client.invoke(DeleteMessagesRequest([message.id], True))
Example #6
0
    def run(self, conf, args, plugins):
        session_file = os.path.join(os.path.expanduser("~"),
                                    ".config/harpoon/telegram")
        client = TelegramClient(session_file, int(conf['Telegram']['id']),
                                conf['Telegram']['hash'])
        # FIXME : do not connect if it's help
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(conf['Telegram']['phone'])
            code_ok = False
            while not code_ok:
                code = input("Enter Telegram code:")
                try:
                    code_ok = client.sign_in(conf['Telegram']['phone'], code)
                except SessionPasswordNeededError:
                    # FIXME: getpass is not imported, that would not work
                    password = getpass(
                        'Two step verification enabled. Please enter your password: '******'subcommand'):
            if args.subcommand == 'id':
                try:
                    res = client.get_entity(args.ID)
                    print(
                        json.dumps(res.to_dict(),
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                except ValueError:
                    print('Identifier not found')
            elif args.subcommand == "messages":
                entity = client.get_entity(args.ID)
                messages = client.get_messages(entity, args.limit)
                users = {}
                if args.dump:
                    if not os.path.exists(args.dump):
                        os.makedirs(args.dump)
                if args.format == "text":
                    if len(messages) == 0:
                        print("No messages in this channel")
                    else:
                        print("%i messages downloaded:" % len(messages))
                        for msg in messages:
                            if isinstance(msg,
                                          telethon.tl.types.MessageService):
                                if isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatEditPhoto):
                                    print("[%s] Channel Photo Changed" %
                                          msg.date.isoformat())
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChannelCreate):
                                    print("[%s] Channel Created" %
                                          msg.date.isoformat())
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatAddUser):
                                    print(
                                        "[%s] Add Users To the Chat - %s" %
                                        (msg.date.isoformat(), ", ".join(
                                            [str(a)
                                             for a in msg.action.users])))
                                elif isinstance(
                                        msg.action, telethon.tl.types.
                                        MessageActionChatDeleteUser):
                                    print(
                                        "[%s] Remove User from the chat - %i" %
                                        (msg.date.isoformat(),
                                         msg.action.user_id))
                                else:
                                    print("[%s] Message Service: %s" %
                                          (msg.date.isoformat(),
                                           msg.action.message))
                            else:
                                if msg.media is None:
                                    if entity.megagroup:
                                        if msg.from_id not in users:
                                            users[msg.
                                                  from_id] = client.get_entity(
                                                      msg.from_id)
                                        print(
                                            "[%s][%i - @%s] %s" %
                                            (msg.date.isoformat(), msg.from_id,
                                             users[msg.from_id].username,
                                             msg.message))
                                    else:
                                        print("[%s] %s (%i views)" %
                                              (msg.date.isoformat(),
                                               msg.message, msg.views))
                                else:
                                    if msg.views:
                                        print(
                                            "[%s] Media (%i views)" %
                                            (msg.date.isoformat(), msg.views))
                                    else:
                                        print("[%s] Media" %
                                              (msg.date.isoformat()))
                                    if args.dump:
                                        if not os.path.exists(
                                                os.path.join(
                                                    args.dump,
                                                    str(msg.id) + '.jpg')):
                                            client.download_media(
                                                msg.media,
                                                os.path.join(
                                                    args.dump, str(msg.id)))
                                            time.sleep(7)
                elif args.format == "json":
                    msg = [m.to_dict() for m in messages]
                    print(
                        json.dumps(msg,
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                    if args.dump:
                        for msg in messages:
                            if msg.media is None:
                                if not os.path.exists(
                                        os.path.join(args.dump,
                                                     str(msg.id) + '.jpg')):
                                    client.download_media(
                                        msg.media,
                                        os.path.join(args.dump, str(msg.id)))
                                    time.sleep(7)
                elif args.format == "csv":
                    if entity.megagroup:
                        # Chat
                        w = csv.writer(sys.stdout, delimiter=';')
                        w.writerow([
                            "Date", "id", "Username", "userid", "Type",
                            "Message"
                        ])
                        for m in messages:
                            if m.from_id not in users:
                                users[m.from_id] = client.get_entity(m.from_id)
                            if isinstance(m, telethon.tl.types.MessageService):
                                w.writerow([
                                    m.date.isoformat(), m.id,
                                    users[m.from_id].username, m.from_id,
                                    m.__class__.__name__,
                                    m.action.__class__.__name__
                                ])
                            else:
                                w.writerow([
                                    m.date.isoformat(), m.id,
                                    users[m.from_id].username, m.from_id,
                                    m.__class__.__name__, m.message
                                ])
                    else:
                        w = csv.writer(sys.stdout, delimiter=';')
                        w.writerow([
                            "Date", "id", "Type", "Information", "Media",
                            "Views"
                        ])
                        for m in messages:
                            if isinstance(m, telethon.tl.types.MessageService):
                                if isinstance(
                                        m.action, telethon.tl.types.
                                        MessageActionChatEditPhoto):
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        "Channel Photo Changed", "No", ""
                                    ])
                                elif isinstance(
                                        m.action, telethon.tl.types.
                                        MessageActionChannelCreate):
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        "Channel Created", "No", ""
                                    ])
                                else:
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__,
                                        m.action.__class__.__name__, "No", ""
                                    ])
                            else:
                                if m.media is None:
                                    # message
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__, m.message, "No",
                                        m.views
                                    ])
                                else:
                                    w.writerow([
                                        m.date.isoformat(), m.id,
                                        m.__class__.__name__, m.message, "Yes",
                                        m.views
                                    ])
                                    if args.dump:
                                        if not os.path.exists(
                                                os.path.join(
                                                    args.dump,
                                                    str(m.id) + '.jpg')):
                                            client.download_media(
                                                m.media,
                                                os.path.join(
                                                    args.dump, str(m.id)))
                                            # Sleep to avoid being banned
                                            time.sleep(7)
                else:
                    print("Not implemented yet, sorry!")
            elif args.subcommand == "users":
                # List users from a group
                try:
                    entity = client.get_entity(args.ID)
                    offset = 0
                    limit = args.limit
                    all_participants = []

                    while True:
                        participants = client.invoke(
                            GetParticipantsRequest(
                                entity,
                                ChannelParticipantsSearch(''),
                                offset,
                                limit,
                                hash=0))
                        if not participants.users:
                            break
                        all_participants.extend(participants.users)
                        offset += len(participants.users)
                        time.sleep(
                            1
                        )  # This line seems to be optional, no guarantees!
                except ChatAdminRequiredError:
                    print(
                        "You don't have required access rights to get this list"
                    )
                else:
                    if args.format == "text":
                        for p in all_participants:
                            print("[+] User: %s (%s %s)" %
                                  (p.username, p.first_name, p.last_name))
                    elif args.format == "json":
                        users = [u.to_dict() for u in all_participants]
                        print(
                            json.dumps(users,
                                       sort_keys=True,
                                       indent=4,
                                       default=json_serial))
                    else:
                        print("Not implemented yet, sorry!")

            else:
                self.parser.print_help()
        else:
            self.parser.print_help()
Example #7
0
                    elif '#업데이트확인' in msg.message:
                        try:
                            url = urlopen(
                                'http://comic.naver.com/webtoon/list.nhn?titleId=119874&weekday='
                            )
                            html = url.read().decode('utf-8')
                            url.close()
                            spt = html.split(
                                '<a href="/webtoon/detail.nhn?titleId=119874&no='
                            )
                            toon_id = spt[1].split('&')[0]
                            update_date = spt[2].split(
                                '<td class="num">')[1].split('</')[0]
                            sleep(0.5)
                            client.invoke(
                                EditMessageRequest(
                                    get_input_peer(dest_channel.channel),
                                    msg.id,
                                    message=
                                    '< 업데이트 정보 >\n%s\nhttp://comic.naver.com/webtoon/detail.nhn?titleId=119874&no=%s&weekday=tue'
                                    % (update_date, toon_id)))
                        except:
                            client.invoke(
                                EditMessageRequest(
                                    get_input_peer(dest_channel.channel),
                                    msg.id,
                                    message=
                                    '< 업데이트 정보 >\n일시적인 오류로 업데이트를 확인할 수 없습니다.'))

client.disconnect()
Example #8
0
class ApiHandler:
    """
    Класс для работы с Telegram Api
    """

    def __init__(self, app_id, app_hash):
        self.app_id = app_id
        self.app_hash = app_hash

        self.client = TelegramClient('user-session', app_id, app_hash)
        self.client.connect()

        if not self.client.is_user_authorized():
            try:
                self.client.send_code_request(PHONE)
                print('Sending a code...')
                self.client.sign_in(PHONE, code=input('Enter code: '))
            except FloodWaitError as FloodError:
                print('Flood wait: {}.'.format(FloodError))
                sys.exit()
            except SessionPasswordNeededError:
                self.client.sign_in(password=getpass('Enter password: '******'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

    def get_chat_info(self, username):
        """
        Функция для получения информации о чате
        :param username: имя пользователя
        :return: словарь c chat_id и access_hash
        """
        try:
            chat = self.client(ResolveUsernameRequest(username))
        except UsernameNotOccupiedError:
            print('Chat/channel not found!')
            sys.exit()
        result = {
            'chat_id': chat.peer.channel_id,
            'access_hash': chat.chats[0].access_hash
        }
        return result

    def get_users(self, user_ids):
        """
        Функция для получения информации о пользователях
        :param user_ids: список id пользователей
        :return:
        """
        users = []

        for user_id in user_ids:
            try:
                users.append(self.client.get_entity(user_id).__dict__)
            except Exception:
                pass

        return users
Example #9
0
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.types import ChannelParticipantsSearch
from time import sleep
from telethon.tl.types import InputChannel

from telethon.tl.functions.channels import GetMessagesRequest

from telethon.tl.functions.channels import GetFullChannelRequest

offset = 0
limit = 100
all_participants = []
channel = InputChannel(mp3downloads1.id, mp3downloads1.access_hash)

full_chat = client.invoke(GetFullChannelRequest(channel))
print(full_chat)
print(full_chat.stringify())
sys.exit(1)

while True:
    participants = client.invoke(
        GetParticipantsRequest(channel, ChannelParticipantsSearch(''), offset,
                               limit))
    print(participants.stringify())
    sys.exit(1)
    if not participants.users:
        break
    all_participants.extend(participants.users)
    offset += len(participants.users)
    print(participants.users[0].stringify())
Example #10
0
    def run(self, conf, args, plugins):
        session_file = os.path.join(os.path.expanduser("~"),
                                    ".config/harpoon/telegram")
        client = TelegramClient(session_file, int(conf['Telegram']['id']),
                                conf['Telegram']['hash'])
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(conf['Telegram']['phone'])
            code_ok = False
            while not code_ok:
                code = input("Enter Telegram code:")
                try:
                    code_ok = client.sign_in(conf['Telegram']['phone'], code)
                except SessionPasswordNeededError:
                    # FIXME: getpass is not imported, that would not work
                    password = getpass(
                        'Two step verification enabled. Please enter your password: '******'subcommand'):
            if args.subcommand == 'id':
                try:
                    res = client.get_entity(args.ID)
                    print(
                        json.dumps(res.to_dict(),
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                except ValueError:
                    print('Identifier not found')
            elif args.subcommand == "messages":
                entity = client.get_entity(args.ID)
                messages = client.get_message_history(entity, args.limit)
                if args.format == "text":
                    print("%i messages downloaded:" % messages[0])
                    for msg in messages[1]:
                        if isinstance(msg, telethon.tl.types.MessageService):
                            print("[%s] Message Service: %s" %
                                  (msg.date.isoformat(), msg.action.message))
                        else:
                            if msg.media is None:
                                print("[%s] %s (%i views)" %
                                      (msg.date.isoformat(), msg.message,
                                       msg.views))
                            else:
                                print("[%s] Media (%i views)" %
                                      (msg.date.isoformat(), msg.views))
                elif args.format == "json":
                    msg = [m.to_dict() for m in messages[1]]
                    print(
                        json.dumps(msg,
                                   sort_keys=True,
                                   indent=4,
                                   default=json_serial))
                else:
                    print("Not implemented yet, sorry!")
            elif args.subcommand == "users":
                # List users from a group
                try:
                    entity = client.get_entity(args.ID)
                    offset = 0
                    limit = args.limit
                    all_participants = []

                    while True:
                        participants = client.invoke(
                            GetParticipantsRequest(
                                entity,
                                ChannelParticipantsSearch(''),
                                offset,
                                limit,
                                hash=0))
                        if not participants.users:
                            break
                        all_participants.extend(participants.users)
                        offset += len(participants.users)
                        sleep(
                            1
                        )  # This line seems to be optional, no guarantees!
                except ChatAdminRequiredError:
                    print(
                        "You don't have required access rights to get this list"
                    )
                else:
                    if args.format == "text":
                        for p in all_participants:
                            print("[+] User: %s (%s %s)" %
                                  (p.username, p.first_name, p.last_name))
                    elif args.format == "json":
                        users = [u.to_dict() for u in all_participants]
                        print(
                            json.dumps(users,
                                       sort_keys=True,
                                       indent=4,
                                       default=json_serial))
                    else:
                        print("Not implemented yet, sorry!")

            else:
                self.parser.print_help()
        else:
            self.parser.print_help()
Example #11
0
        #time.sleep(1)  # pause for 1 second to rate-limit automatic replies
        #await event.respond('@dante_dog_bot', '/start params_string')
@client.on(events.UserUpdate)
async def handler(event): 

#@client.on(events.NewMessage(incoming=True))
#async def handle_new_message(event):
    #@bot.on(events.NewMessage)
    #$async def echo(event):
    """Echo the user message."""
    #print(f"get it {event.text}")
    await client.send_message('@dante_dog_bot', '/start params_string')
    #await client.send_message("@zeidardz",message="Hello python")
from telethon.tl.functions.messages import StartBotRequest

request = StartBotRequest("bot_username_bot", "bot_username_bot", "params_string")
result = await client(request)

print(time.asctime(), '-', 'Auto-replying...')
#client.connect() # logining and connecting to Telegram servers
 result = client.invoke(ImportContactsRequest([contact], replace=True))
contacts = client.invoke(GetContactsRequest(""))
for u in result.users:
    client.send_message(u, 'Hi')
client.run_until_disconnected()
print(time.asctime(), '-', 'Stopped!')



loop = asyncio.get_event_loop()
 
Example #12
0
class SetUploader:
    _telegram_api_id, _telegram_api_hash = 173590, "9b05a9d53a77019aa1d615f27776e60f"
    # it only talks to @Stickers, so just hardcode it
    # invoke(ResolveUsernameRequest(username='******')) returns
    #   contacts.resolvedPeer = \
    #       (..., users=[(..., id=429000, access_hash=9143715803499997149, username=Stickers, ...)])
    _stickersbot = InputPeerUser(user_id=429000,
                                 access_hash=9143715803499997149)

    def __init__(self, set_paths):
        """
        Log in to Telegram and prepare for upload.
        
        :param set_paths: See the docstring of `cli.upload()`
        """
        # TODO: strip Telethon to avoid too much implicit import
        self._TC = TelegramClient(
            session=CustomisedSession.try_load_or_create_new(),
            api_id=self._telegram_api_id,
            api_hash=self._telegram_api_hash)
        logging.getLogger('TelethonLogger').setLevel(
            logging.ERROR)  # suppress logging from telethon

        # Stolen from telethon.InteractiveTelegramClient :P
        self._TC.connect()
        if not self._TC.is_user_authorized():
            print(PROMPT_ON_FIRST_LAUNCH)
            user_phone = input(PROMPT_PHONE_NUMBER)
            self._TC.send_code_request(user_phone)
            code_ok = False
            while not code_ok:
                code = input(PROMPT_LOGIN_CODE)
                try:
                    code_ok = self._TC.sign_in(user_phone, code)

                # Two-step verification may be enabled
                except RPCError as e:
                    from getpass import getpass
                    if e.password_required:
                        pw = getpass(PROMPT_2FA_PASSWORD)
                        code_ok = self._TC.sign_in(password=pw)
                    else:
                        raise e

        self._stickersets = list()
        for setpath in set_paths:
            print(NOTICE_PREPARING % setpath)
            path = Path(setpath)
            set_def_tuple = ()
            if path.is_dir():
                for d in path.glob('*.ssd'):
                    set_def_tuple = defparse.parse(d)  # only process one
                    break
            elif path.suffix == '.ssd':
                set_def_tuple = defparse.parse(path)
            if set_def_tuple:
                self._stickersets.append(set_def_tuple)

    def upload(self, subscribe=False):
        """
        Start uploads, and disconnect from Telegram after finish.
        
        :param subscribe: See `strings.CLI_SHELP_UPLOAD_SUBFLAG`
        :return: None
        """
        if self._stickersets:
            self._do_uploads(subscribe=subscribe)
        else:
            print(ERROR_NO_SET_UPLOAD)
        self._TC.disconnect()

    def _do_uploads(self, subscribe):
        """Talk to Stickers bot and create the sets."""
        self._sticker_bot_cmd(SendMessageRequest, message='/cancel')
        self._sticker_bot_cmd(SendMessageRequest, message='/start')

        for _set in self._stickersets:
            set_title, set_short_name, stickers = _set

            self._sticker_bot_cmd(SendMessageRequest, message='/newpack')
            self._sticker_bot_cmd(SendMessageRequest, message=set_title)
            for index, (sticker_image, emojis) in enumerate(stickers):
                uploaded_file = self._do_upload_file(sticker_image)
                uploaded_doc = InputMediaUploadedDocument(
                    file=uploaded_file,
                    mime_type='image/png',
                    attributes=[DocumentAttributeFilename(uploaded_file.name)],
                    caption='')
                self._sticker_bot_cmd(SendMediaRequest, media=uploaded_doc)
                self._sticker_bot_cmd(SendMessageRequest, message=emojis)
                print(
                    NOTICE_UPLOADED % {
                        'fn': uploaded_file.name,
                        'cur': index + 1,
                        'total': len(stickers)
                    })
            self._sticker_bot_cmd(SendMessageRequest, message='/publish')
            self._sticker_bot_cmd(SendMessageRequest, message=set_short_name)
            print(NOTICE_SET_AVAILABLE % {
                'title': set_title,
                'short_name': set_short_name
            })

            if subscribe:
                result = self._TC.invoke(
                    InstallStickerSetRequest(
                        InputStickerSetShortName(short_name=set_short_name),
                        archived=False))
                if type(result) == StickerSetInstallResultSuccess:
                    print(NOTICE_SET_SUBSCRIBED % set_title)

    @staticmethod
    def _get_random_id():
        return int.from_bytes(urandom(8), signed=True, byteorder='little')

    def _sticker_bot_cmd(self, request, **kwargs):
        """
        An 'interface' to send `MTProtoRequest`s.
        
        :param request: An MTProtoRequest
        :param kwargs: Parameters for the MTProtoRequest
        :return: None
        """
        random_id = self._get_random_id()
        self._TC.invoke(request=request(
            **kwargs, peer=self._stickersbot, random_id=random_id))
        sleep(1)  # wait for bot reply, but can ignore the content

    def _do_upload_file(self, filepath):
        """
        Upload a file to Telegram cloud.
        Stolen from telethon.TelegramClient.upload_file().
        Specialised for upload sticker images.
        
        :param filepath: A path-like object
        :return: An InputFile handle.
        """
        file = Path(filepath)
        file_id = self._get_random_id()
        file_name = file.name
        part_size_kb = 32 * 1024  # just hardcode it, every file is under 350KB anyways
        part_count = (file.stat().st_size + part_size_kb - 1) // part_size_kb
        file_hash = md5()
        with open(file, mode='rb') as f:
            for part_index in range(part_count):
                part = f.read(part_size_kb)
                self._TC.invoke(
                    request=SaveFilePartRequest(file_id, part_index, part))
                file_hash.update(part)
        return InputFile(id=file_id,
                         parts=part_count,
                         name=file_name,
                         md5_checksum=file_hash.hexdigest())
Example #13
0
chunk_size = 5
result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size))
dialogs.extend(result.dialogs)
users.extend(result.users)
chats.extend(result.chats)

print(dialogs)

# InputChannel(dialogs[0].id, dialogs[0].access_hash)

participants = client.invoke(
    GetParticipantsRequest(InputChannel(chats[0].id, chats[0].access_hash),
                           ChannelParticipantsSearch(''), 0, 300, 1))

# print(participants.users[0].stringify())

with open("names2.txt", "w") as output:
    for user in participants.users:
        output.write(user.first_name)
        output.write("\n")

with open("dialogs.txt", "w") as output:
    output.write(str(dialogs))

with open("users.txt", "w") as output:
    output.write(str(users))
Example #14
0
#for msg in reversed(messages):
#     print ("msg:   ", msg.id, msg)
#     client.invoke(ForwardMessagesRequest(from_peer=shelter2, id=[msg.id], to_peer=shelter2))

while True:
    update = client.updates.poll()
    print(update)
    if type(
            update
    ) == UpdateNewChannelMessage and update.message.to_id.channel_id == channel_manual.id:
        print('message id ' + str(update.message.id))
        print('channel id ' + str(update.message.to_id.channel_id))
        #print(update)
        #print(dir(update))
        client.invoke(
            ForwardMessagesRequest(from_peer=channel_from_input_peer,
                                   id=[update.message.id],
                                   to_peer=channel_to_input_peer))

#    print('UPDATE_MESSAGE')

#print(client.invoke(GetMessagesRequest(channel=my_channel_to, id=[update.message.id])))
#client.invoke(ForwardMessagesRequest(from_peer=my_channel_from, id=[update.message.id], to_peer=my_channel_to))
    else:
        continue

#def forward(update):
#if isinstance(update, UpdateShortMessage) and not update.out:
#total_count, messages, senders = client.get_message_history(channel_from_input_peer.chats[0], limit=1)
#    print('UPDATE_MESSAGE')
#    print(update.message)
#    print('FULL_MESSAGE')
Example #15
0
print("connected")

print("authorizing")

if not client.is_user_authorized():
    client.send_code_request(phone_number)
    client.sign_in(phone_number, input('Enter the code: '))

print("authorized")

print("getting dialogs")

dialogs, entities = client.get_dialogs(10)
entity = entities[0]

print("invoking GetHistoryRequest")

result = client.invoke(
    GetHistoryRequest(get_input_peer(entity),
                      limit=20,
                      offset_date=None,
                      offset_id=0,
                      max_id=0,
                      min_id=0,
                      add_offset=0))

messages = result.messages

print(str(messages[0]))
Example #16
0
numbers = open("numbers.txt", "r").read().split("\n")

for i in numbers:
    ####___More_data___####
    channel_name = "XXXXXXXXXXXXXX"
    guest_phone_number = i  #The number you want to add channel
    ####################################

    try:
        time_sleep = time.sleep(10)
        ####___Add_user_to_your_contact___####
        contact = InputPhoneContact(client_id=0,
                                    phone=guest_phone_number,
                                    first_name="AddedUser",
                                    last_name="")
        result = client.invoke(ImportContactsRequest([contact]))
        ###############################################################################################

        try:
            ####___Add_user_to_channel___####
            client(
                InviteToChannelRequest(channel=channel_name,
                                       users=[result.users[0]]))
            print(result.users[0].phone + " - added ")
            ############################################################################
        except errors.PeerFloodError:
            print("Too many requests, please change account or waiting")
        except errors.UserNotMutualContactError:
            print("This contact cannot be added")

    except (IndexError, TypeError):