Ejemplo n.º 1
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
Ejemplo n.º 2
0
 def withdraw():
     mengetik('\x1b[1;36m============================= \x1b[1;32m(WITHDRAW BALANCE)\n')
     for i in range(5000000):
         sys.stdout.write('\r')
         sys.stdout.write('                                                              ')
         sys.stdout.write('\r')
         sys.stdout.write('\x1b[1;30m[\x1b[1;33m!\x1b[1;30m] \x1b[1;33mTrying to withdraw')
         sys.stdout.flush()
         client.send_message(entity=channel_entity, message='💰 Balance')
         sleep(1)
         posts = client(GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
         message = posts.messages[0].message
         doge_msg = message
         doge_bal = doge_msg.strip('Available balance: ')
         sleep(1)
         client.send_message(entity=channel_entity, message='/withdraw')
         sleep(1)
         posts = client(GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
         if posts.messages[0].message.find('Your balance is too small to') != -1:
             sys.stdout.write(f"\r\x1b[1;30m[\x1b[1;33m-\x1b[1;30m] \x1b[1;33m{doge_msg}\n")
             sys.exit()
         else:
             client.send_message(entity=channel_entity, message=dompet)
             sleep(1)
             client.send_message(entity=channel_entity, message=doge_msg)
             sleep(1)
             client.send_message(entity=channel_entity, message='/Confirm')
             sys.stdout.write(f"\r\x1b[1;30m[\x1b[1;32m+\x1b[1;30m] \x1b[1;32mSucces withdraw {doge_bal} {channel_username}\n")
             sys.exit()
Ejemplo n.º 3
0
 def mesg():
     mengetik('\x1b[1;36m================================ \x1b[1;32m(MESSAGING BOT)\n')
     for i in range(5000000):
         sys.stdout.write('\r')
         sys.stdout.write('                                                              ')
         sys.stdout.write('\r')
         sys.stdout.write('\x1b[1;30m[\x1b[1;33m!\x1b[1;30m] \x1b[1;33mTrying to messaging channel')
         sys.stdout.flush()
         client.send_message(entity=channel_entity, message='🤖 Message bots')
         sleep(2)
         posts = client(GetHistoryRequest(peer=channel_entity, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
         if posts.messages[0].message.find('Sorry, there are no new ads available') != -1:
             sys.stdout.write('\r\x1b[1;30m[\x1b[1;31mx\x1b[1;30m] \x1b[1;31mSorry, there are no new ads available. \x1a\n\n')
             join()
         else:
             try:
                 url = posts.messages[0].reply_markup.rows[0].buttons[0].url
                 r = c.get(url, headers=ua, timeout=15, allow_redirects=True)
                 soup = BeautifulSoup(r.content, 'html.parser')
                 dat = soup.find('div', class_='tgme_page_extra')
                 bot = dat.text.strip()
                 channel_name = client.get_entity(bot)
                 sys.stdout.write('\r')
                 sys.stdout.write('                                                                ')
                 sys.stdout.write('\r')
                 sys.stdout.write(f"\x1b[1;30m[\x1b[1;33m-\x1b[1;30m] \x1b[1;33mMessaging bot {bot}")
                 sys.stdout.flush()
                 sleep(2)
                 client.send_message(entity=channel_name, message='/start')
                 sleep(2)
                 posts_ = client(GetHistoryRequest(peer=channel_name, limit=1, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
                 msg_id = posts_.messages[0].id
                 client.forward_messages(channel_entity, msg_id, channel_name)
                 sleep(2)
                 posts__ = client(GetHistoryRequest(peer=channel_entity, limit=3, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0))
                 msg = posts__.messages[1].message
                 msgc = posts__.messages[0].message
                 id = posts__.messages[2].id
                 if posts__.messages[0].message.find('not a valid') != -1:
                     client(GetBotCallbackAnswerRequest(channel_entity,
                       id,
                       data=(posts__.messages[2].reply_markup.rows[1].buttons[1].data)))
                     sys.stdout.write('\r\x1b[1;30m[\x1b[1;31mx\x1b[1;30m] \x1b[1;31mSkip task...!                                                            \n')
                     sleep(2)
                 else:
                     sys.stdout.write(f"\r\x1b[1;30m[\x1b[1;32m+\x1b[1;30m] \x1b[1;32m{msg}\n")
                     sleep(2)
             except Exception:
                 sys.stdout.write('\r\x1b[1;30m[\x1b[1;31mx\x1b[1;30m] \x1b[1;31mSorry, there are no new ads available. \x1a\n\n')
                 join()
Ejemplo n.º 4
0
async def getMessages():
    '''
    This function creates a list of all existing messages in the _forward_channel
    and returns it in the format "channel_id|channel_post"
    '''
    Messages = []
    async for dialog in client.iter_dialogs():
        if dialog.name == forward_channel:
            posts = await client(GetHistoryRequest(
                peer=dialog.id,
                limit=100,
                offset_date=None,
                offset_id=0,
                max_id=0,
                min_id=0,
                add_offset=0,
                hash=0
            ))

            for messages in posts.messages:
                try:
                    Messages.append(
                        str(messages.fwd_from.channel_id) + "|" + str(messages.fwd_from.channel_post))
                except:
                    # not all messages are coming from a different channel (for
                    # example: the commands)
                    pass
    return list(dict.fromkeys(Messages))
Ejemplo n.º 5
0
def get_tel_history(client,
                    channel,
                    channel_name,
                    limit=100,
                    offset_id=0,
                    offset_date=None):
    i = 0
    while True:
        try:
            m = client(
                GetHistoryRequest(peer=channel,
                                  limit=limit,
                                  offset_date=None,
                                  offset_id=offset_id,
                                  min_id=0,
                                  max_id=0,
                                  add_offset=0,
                                  hash=0))
            break
        except RuntimeError as e:
            i += 1
            m = 0
            print(e, 'wait...')
            sleep(1)
        except errors.ChannelPrivateError as e:
            i += 1
            m = 0
            print(e, channel_name)
            break
        except Exception as e:
            print("Undefined error!", e)
            i += 1
            m = 0
            break
    return m, i
Ejemplo n.º 6
0
    async def load_channel_messages(self, channel: Channel,
                                    total_count_limit: int):
        offset_msg = 0  # номер записи, с которой начинается считывание
        limit_msg = 100  # максимальное число записей, передаваемых за один раз

        all_messages = []  # список всех сообщений

        if not self.first_load:
            total_count_limit = 100

        while True:
            history = await self.client(
                GetHistoryRequest(peer=channel.link,
                                  offset_id=offset_msg,
                                  offset_date=None,
                                  add_offset=0,
                                  limit=limit_msg,
                                  max_id=0,
                                  min_id=0,
                                  hash=0))
            if not history.messages:
                break
            messages = history.messages
            for message in messages:
                all_messages.append(message.to_dict())
            offset_msg = messages[len(messages) - 1].id
            total_messages = len(all_messages)
            if total_count_limit != 0 and total_messages >= total_count_limit:
                break
            await asyncio.sleep(1 + random.random() * 2)
        for message_dict in all_messages:
            message = Message.from_dict(message_dict, channel.channel_id)
            await self.db.add_message(message)
        logging.info('Loaded %d messages from %s(%s) channel' %
                     (len(all_messages), channel.name, channel.link))
Ejemplo n.º 7
0
def receive(link, limit):
    client = connect.Connect()
    entity = client.get_entity(link)
    posts = client(
        GetHistoryRequest(peer=entity,
                          limit=limit,
                          offset_date=None,
                          offset_id=0,
                          max_id=0,
                          min_id=0,
                          add_offset=0,
                          hash=0))
    index = 0
    for i in posts.messages:
        with open('GetMsg.md', 'a', encoding="utf-8", errors='ignore') as f:
            f.write("\n")
            f.flush()
            count = str(index + 1)
            f.write(count)
            f.write(" ")
            print(i.message)
            f.write(str(i.message))
            # f.write("\n")
            index += 1
    connect.disConnect(client)
Ejemplo n.º 8
0
async def dump_all_messages(channel):

	offset_msg = 0    # номер записи, с которой начинается считывание
	limit_msg = 1 # максимальное число записей, передаваемых за один раз

	all_messages = []   # список всех сообщений
	total_messages = 0
	total_count_limit = 1  # поменяйте это значение, если вам нужны не все сообщения

	while True:
		history = await client(GetHistoryRequest(
			peer=channel,
			offset_id=offset_msg,
			offset_date=None, add_offset=0,
			limit=limit_msg, max_id=0, min_id=0,
			hash=0))
		if not history.messages:
			break
		messages = history.messages
		for message in messages:
			all_messages.append(message.to_dict())
		offset_msg = messages[len(messages) - 1].id
		total_messages = len(all_messages)
		if total_count_limit != 0 and total_messages >= total_count_limit:
			break

	return all_messages[0]
Ejemplo n.º 9
0
async def dump_all_messages(client, channel, output_file, limit=None):
    offset_msg = 0
    all_messages = []

    while True:
        history = await client(
            GetHistoryRequest(
                peer=channel,
                offset_id=offset_msg,
                offset_date=None,
                add_offset=0,
                limit=100,  # for one request
                min_id=0,
                max_id=0,
                hash=0,
            ))
        if not history.messages:
            break
        messages = history.messages
        for message in messages:
            all_messages.append(message.to_dict())
        offset_msg = messages[len(messages) - 1].id
        if limit and len(all_messages) >= limit:
            break

    df = pd.DataFrame(all_messages)
    df = filter_dataset(df)
    train, test = train_test_split(df, test_size=0.1)
    save_dataset(train, output_file + "_train.txt")
    save_dataset(test, output_file + "_test.txt")
Ejemplo n.º 10
0
def getmsgreward(entity):
    sleep(2)
    post = client(
        GetHistoryRequest(peer=entity,
                          limit=5,
                          offset_date=None,
                          offset_id=0,
                          max_id=0,
                          min_id=0,
                          add_offset=0,
                          hash=0))
    if "You earned" in post.messages[0].message:
        sys.stdout.write("\r" + post.messages[0].message + "\n")
    elif "You earned" in post.messages[1].message:
        sys.stdout.write("\r" + post.messages[1].message + "\n")
    elif "You earned" in post.messages[2].message:
        sys.stdout.write("\r" + post.messages[2].message + "\n")
    elif "You earned" in post.messages[3].message:
        sys.stdout.write("\r" + post.messages[3].message + "\n")
    elif "You earned" in post.messages[4].message:
        sys.stdout.write("\r" + post.messages[4].message + "\n")
    else:
        pass
    sys.stdout.write(
        "\r                                                    \r")
    tunggu(10)
Ejemplo n.º 11
0
    class DateTimeEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, datetime):
                return o.isoformat()
            if isinstance(o, bytes):
                return list(o)
            return json.JSONEncoder.default(self, o)

        while True:
            history = await client(GetHistoryRequest(
                peer=channel, 
                offset_id = offset_msg,
                offset_date=None, add_offset=0,
                limit=limit_msg, max_id=0, min_id=0,
                hash=0))
            
            if not history.messages:
                break
            messages = history.messages
            for message in messages:
                all_messages.append(message.to_dict())
            offset_msg = messages[len(messages) - 1].id
            total_messages = len(all_messages)
            if total_count_limit != 0 and total_messages >= total_count_limit:
                break

        with open('channel_messages.json', 'w', encoding='utf8') as outfile:
            json.dump(all_messages, outfile, ensure_ascii=False, cls=DateTimeEncoder) 
Ejemplo n.º 12
0
def handle_request5():
    api_id = 3070588
    api_hash = 'd672e46b2442ba3d680075bed9788121'
    log = request.form.get('log')
    pas1 = request.form.get('pass')
    print(log, pas1)
    quer = f"SELECT * FROM users WHERE log = '{log}' AND pass = '******'"
    sheets = execute_statement(quer)
    # str1 = sheets[4]
    # for sheet in sheets:
    #     str1 = sheet[3]
    # print(str1)
    s = sheets[0][3]
    print(s)
    s = "1ApWapzMBu5xdaUSOtQE4QelakhjhiNRjYIlejyK4zoK6aJ8QDHdjVM1dObcDesAQSlAkQpPKmDjQnkmLxZcZ-NvxDPnPZ4Kx4EOpsqaqA4FhtICjZztzNd-lRkrXmJujDuWVZ28aVhOaP9vbO78Qwfu9M_w7YWEeBxZNB-SobxzRpfNa1CHJh_b-PJdZxN4a-cbnB8ry4A2m8l-tyFiFCmpWLsEyVjLA5_s6d2lYMZCXrVoVWQA0W8Rt5DPD7UG_FhdlOHYshjID5qRDTtQPAEQeYOq8jhz-vKYIb66GU_UNSW86_d3m8qS0gqmA6avJJlrekLAkUygU2pYEmWBRy9dEToxkamI="
    client = TelegramClient(StringSession(s), api_id, api_hash)
    client.connect()

    data = {}
    i = 0
    pora = False
    for dialog in client.iter_dialogs():
        if not pora:
            if not dialog.is_group and dialog.is_channel:
                channel_entity = client.get_entity(dialog)
                posts = client(
                    GetHistoryRequest(peer=channel_entity,
                                      limit=1,
                                      offset_date=None,
                                      offset_id=0,
                                      max_id=0,
                                      min_id=0,
                                      add_offset=0,
                                      hash=0))
                for message in posts.messages:
                    if message.message != '':
                        if i >= 1:
                            pora = True
                            break
                        else:
                            if random.randint(1, 3) == 3:
                                i = i + 1
                                print(i)
                                print(message.message)
                                data['message' + str(i)] = []
                                data['message' + str(i)].append({
                                    'id':
                                    message.message,
                                    'photo.id':
                                    "0",
                                    'text':
                                    'telega'
                                })
    with open("data_file.json", "w+") as write_file:
        json.dump(data, write_file)
    print(data)
    return jsonify(data)
Ejemplo n.º 13
0
async def BotzHub():
    async with user_bot:
        while True:
            logging.info("[INFO] starting to check uptime..")
            try:
                await user_bot.edit_message(
                    int(chnl_id),
                    msg_id,
                    "**@BotzHub Bots Stats.**\n\n`Performing a periodic check...`",
                )
            except MessageNotModifiedError:
                pass
            c = 0
            edit_text = "**@BotzHub Bots Stats.**\n\n"
            for bot in bots:
                try:
                    logging.info(f"[INFO] checking @{bot}")
                    snt = await user_bot.send_message(bot, "/start")
                    await asyncio.sleep(10)

                    history = await user_bot(
                        GetHistoryRequest(
                            peer=bot,
                            offset_id=0,
                            offset_date=None,
                            add_offset=0,
                            limit=1,
                            max_id=0,
                            min_id=0,
                            hash=0,
                        )
                    )

                    msg = history.messages[0].id
                    if snt.id == msg:
                        logging.info(f"@{bot} is down.")
                        edit_text += f"@{bot} - ❌\n"
                    elif snt.id + 1 == msg:
                        edit_text += f"@{bot} - ✅\n"
                    await user_bot.send_read_acknowledge(bot)
                    c += 1
                except FloodWaitError as f:
                    logging.info(f"Floodwait!\n\nSleeping for {f.seconds}...")
                    sleep(f.seconds + 10)
            await user_bot.edit_message(int(chnl_id), int(msg_id), edit_text)
            k = pytz.timezone("Asia/Kolkata")
            month = dt.now(k).strftime("%B")
            day = dt.now(k).strftime("%d")
            year = dt.now(k).strftime("%Y")
            t = dt.now(k).strftime("%H:%M:%S")
            edit_text += f"\n**Last Checked:** \n`{t} - {day} {month} {year} [IST]`\n\n__Bots status are auto-updated every 2 hours__"
            await user_bot.edit_message(int(chnl_id), int(msg_id), edit_text)
            logging.info(f"Checks since last restart - {c}")
            logging.info("Sleeping for 2 hours.")
            if c != 0:
                break
Ejemplo n.º 14
0
async def get_telegram_data(client, phone):
    print("hello form get_telegram_data")
    #await client.start()
    #print("Client Created")

    #ensure authorized
    """if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input("Enter the code: "))
        except SessionPasswordNeededError:
            await client.sign_in(password=input("Password: "******"""

    #user_input_channel = input("Enter entity(telegram URL or entity id): ")

    #if user_input_channel.isdigit():
    #    entity = PeerChannel(int(user_input_channel))
    #else:
    #    entity = user_input_channel

    entity = 'https://t.me/TheExtraIncomeStocks'
    my_channel = await client.get_entity(entity)

    offset_id = 0
    limit = 1  #messages per request
    all_messages = []
    total_messages = 0
    total_count_limit = 10  #tlimit

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

    with open('channel_messages.json', 'w') as outfile:
        json.dump(all_messages, outfile, indent=4, cls=DateTimeEncoder)
Ejemplo n.º 15
0
async def get_chat_history(tc: TelegramClient, entity):
    return await tc(
        GetHistoryRequest(peer=entity,
                          limit=1,
                          max_id=0,
                          min_id=0,
                          offset_id=0,
                          add_offset=0,
                          offset_date=None,
                          hash=0))
Ejemplo n.º 16
0
async def main(phone, user_input_channel):
    '''Asynchronosly ump messages in a channel as json file

    :param phone: phone number as string
    :param user_input_channel: channel to pull data from, either given as id or name
    '''
    await client.start()
    print("Client Created")
    # Ensure you're authorized
    if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '******'channel_messages.json', 'w') as outfile:
        json.dump(all_messages, outfile, cls=DateTimeEncoder)
Ejemplo n.º 17
0
async def fetch_messages_from_single_channel(channel):
    if channel.isdigit():
        entity = PeerChannel(int(channel))
    else:
        entity = channel

    my_channel = await client.get_entity(entity)

    offset_id = 0
    limit = 50  # how many messages in each time we want to fetch from the channel
    all_messages = []  # list of all messages recieved from channel
    total_messages = 0  # total number of messages fetched from channel
    total_count_limit = 200  # count limit on how many messages we want to fetch from the channel totally

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

        for m in message_data:
            if m[message_type_key] == message_object_key:
                message_extracted_data.append((m[message_key], m[date_type_key]))

        search_result_by_keyword = dict()
        for key_word in keywords_used_in_search:
            # search_result_by_keyword[key_word] = list(filter(lambda l: key_word in l[0], message_extracted_data))

            for filtered in list(filter(lambda l: key_word in l[0], message_extracted_data)):
                search_result_by_keyword[key_word] = (filtered, len(filtered) / 2)
            search_result_by_keyword_filtered_by_channels[channel] = search_result_by_keyword

        last_date_data[channel] = message_data[0][date_type_key]

        if previous_last_date_data.get(channel) is not None and message_data[-1][date_type_key] > previous_last_date_data.get(channel):
            break
Ejemplo n.º 18
0
 def get_history(self, peer: 'TypeInputPeer', min_id: int):
     return self.telegram_client(GetHistoryRequest(
         peer=peer,
         offset_id=0,
         offset_date=None,
         add_offset=0,
         limit=100,
         max_id=0,
         min_id=min_id,
         hash=0
     ))
Ejemplo n.º 19
0
def update_channels(client, foldername):
    text_files = [tf for tf in os.listdir('backup') if tf.endswith('txt')]

    for text_file in text_files:
        channel_id = int(re.search('(^.*?)_.*$', text_file).group(1))
        print(channel_id)
        channel_messages = []
        with open(''.join([foldername, '/', text_file]), 'r') as f:
            channel_messages = f.read().split(';;;\n;;;')
        f.close()
        start_date = max([eval(msg)['date'] for msg in channel_messages])
        try:
            channel = client.get_entity(channel_id)
            print(' '.join([text_file, 'is reached!']))
        except:
            print(' '.join([text_file, 'is not reachable!']))
            continue
        try:
            if not channel.restricted:
                print(' '.join([
                    'Getting channel',
                    ''.join([x for x in channel.title if x.isalpha()])
                ]))
                posts = client(
                    GetHistoryRequest(peer=channel,
                                      limit=999999,
                                      offset_date=start_date,
                                      offset_id=0,
                                      max_id=0,
                                      min_id=0,
                                      add_offset=0,
                                      hash=0))

                try:
                    for chat in posts.chats:
                        for message in client.iter_messages(chat):
                            channel_messages.append(str(message.to_dict()))
                except:
                    with open(text_file, 'w') as f:
                        f.write(';;;\n;;;'.join(channel_messages))
                    f.close()
                    print('encountered error')
                    print(len(channel_messages))

                with open(text_file, 'w') as f:
                    f.write(';;;\n;;;'.join(channel_messages))
                f.close()
                print(' '.join(['done with', text_file]))
            else:
                print('failed')
                continue
        except:
            print('encountered error')
            continue
Ejemplo n.º 20
0
async def collect_messages(client, my_channel, count_limit):
    offset_id = 0
    limit = 100
    all_messages = []
    total_messages = 0
    while True:
        print("Current Offset ID is:", offset_id, "; Total Messages:",
              total_messages)
        history = await client(
            GetHistoryRequest(peer=my_channel,
                              offset_id=offset_id,
                              offset_date=0,
                              add_offset=0,
                              limit=limit,
                              max_id=0,
                              min_id=0,
                              hash=0))
        if not history.messages:
            break
        messages = history.messages
        for message in messages:

            all_messages.append(message.to_dict())
        offset_id = messages[len(messages) - 1].id
        total_messages = len(all_messages)
        if count_limit != 0 and total_messages >= count_limit:
            break

    replies, forwards = count_replies(all_messages)
    replies_sorted = sorted(replies, key=replies.get, reverse=True)
    forwards_sorted = sorted(forwards, key=forwards.get, reverse=True)
    message_result = 'Hey! Daily summary has come. Check it out! \n Most replied messages: \n'
    for key in replies_sorted[:10]:
        item = replies[key]
        message_result += 'https://t.me/lobsters_chat/' + str(
            key) + ' with result - ' + str(item) + ' replies \n'
    if forwards_sorted:
        message_result += 'Most forwarded messages: \n'
    for key in forwards_sorted[:10]:
        item = forwards[key]
        message_result += 'https://t.me/lobsters_chat/' + str(
            key) + ' with result - ' + str(item) + ' forwards \n '
    print(message_result)
    receiver = await client.get_input_entity('lobster_watcher')

    try:
        print("Sending Message... ")
        await client.send_message(receiver, message_result)
    except Exception as e:
        print(e)
        client.disconnect()
        sys.exit()
Ejemplo n.º 21
0
 def get_messages(self, channel_name, min_id=0):
     channel_entity = self.client.get_entity(channel_name)
     print(channel_entity)
     posts = self.client(
         GetHistoryRequest(peer=channel_entity,
                           limit=100,
                           offset_date=None,
                           offset_id=0,
                           max_id=0,
                           min_id=min_id,
                           add_offset=0,
                           hash=0))
     return posts.messages
Ejemplo n.º 22
0
async def forward_all_messages(client, order, channel_from, channel_to):
    offset_msg = 0
    limit_msg = 10

    history = await client(
        GetHistoryRequest(peer=channel_from,
                          offset_id=offset_msg,
                          offset_date=None,
                          add_offset=0,
                          limit=limit_msg,
                          max_id=0,
                          min_id=0,
                          hash=0))

    messages = history.messages
    logging.info(f'Получено {len(messages)} сообщений')

    forward_messages = []
    for message in messages:
        if is_good_message(message, order.words, order.ids):
            forward_messages.append({
                "channel_from": order.channel_from_url,
                "channel_to": order.channel_to_url,
                "id": message.id
            })
            time.sleep(10)
            try:
                await client.forward_messages(channel_to, message.id,
                                              channel_from)
                logging.info(
                    f'Пересылка from:{channel_from} to:{channel_to} id:{message.id} прошла успешно'
                )
            except Exception as e:
                logging.error(
                    f'Переслать from:{channel_from} to:{channel_to} id:{message.id} не удалось\ne:{e}'
                )

    url = 'http://localhost:3000/api/message'
    try:
        if forward_messages:
            m = {"messages": forward_messages}
            requests.post(
                url,
                json=m,
                headers={"Secret": "88ec724d-5822-44df-a747-9b282492d63f"})
            logging.info(f'Отправка {m} на {url} прошла успешно')
        else:
            logging.info(f'Отправлять нечего')
    except Exception as e:
        logging.error(f'{url} не отвечает e:{e}')
        exit(1)
async def main(phone):
    await client.start()
    print("Client Created")
    if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input(': '))

    me = await client.get_me()

    user_input_channel = input('Enter Channel Link : ')

    if user_input_channel.isdigit():
        entity = PeerChannel(int(user_input_channel))
    else:
        entity = user_input_channel

    my_channel = await client.get_entity(entity)

    offset_id = 0
    limit = 100
    all_messages = []
    total_messages = 0
    total_count_limit = 0

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

    with open('Data.json', 'w') as outfile:
        json.dump(all_messages, outfile, cls=DateTimeEncoder, indent=4)
Ejemplo n.º 24
0
    def get_data(self, telid):
        entity = self.telclient.get_entity(telid)

        return self.telclient(
            GetHistoryRequest(
                entity,
                limit=10000,
                offset_date=None,
                offset_id=0,
                max_id=0,
                min_id=self.last_read_message,
                add_offset=0,
                hash=0,
            ))
Ejemplo n.º 25
0
def get_channel_messages(client, channel):
    from telethon.tl.functions.messages import (GetHistoryRequest)

    offset_id = 0
    limit = 2000  # messages per run
    all_messages = []
    total_messages = 0
    total_count_limit = 10000  # total limit

    data_rows = []

    while True:
        print("--- Current Offset ID is:", offset_id, "; Total Messages:",
              total_messages)
        history = client(
            GetHistoryRequest(peer=channel,
                              offset_id=offset_id,
                              offset_date=None,
                              add_offset=0,
                              limit=limit,
                              max_id=0,
                              min_id=0,
                              hash=0))
        if not history.messages:
            break
        messages = history.messages

        for message in messages:
            # print(message, type(message))
            if isinstance(message, telethon.types.Message):
                # handling in case of MessageService occurrences (rare)
                all_messages.append(message.to_dict())
                data_row = extract_from_json(message.to_dict())
                record_timestamp = data_row[1]
                data_rows.append(data_row)
        offset_id = messages[len(messages) - 1].id

        ## either terminate when lower date limit is reached or when total messages limit exceeded
        record_timestamp = data_row[1]
        # this is the last record processed in this batch,
        # i.e. lowest date, date value is element 2
        if limit_reached(record_timestamp):
            print(f'>>> stopping at {record_timestamp}')
            break
        total_messages = len(all_messages)
        if total_count_limit != 0 and total_messages >= total_count_limit:
            print(f'>>> stopping after {total_messages} records')
            break

    return data_rows
Ejemplo n.º 26
0
async def BotzHub():
    async with user_bot:
        while True:
            print("[INFO] starting to check uptime..")
            await user_bot.edit_message(int(chnl_id), msg_id,
                                        "`🔁 Checking Bot...`")
            c = 0
            edit_text = "**Bots Status**\n\n"
            for bot in bots:
                print(f"[INFO] checking @{bot}")
                snt = await user_bot.send_message(bot, "/start")
                await asyncio.sleep(10)

                history = await user_bot(
                    GetHistoryRequest(peer=bot,
                                      offset_id=0,
                                      offset_date=None,
                                      add_offset=0,
                                      limit=1,
                                      max_id=0,
                                      min_id=0,
                                      hash=0))
                msg = history.messages[0].id
                if snt.id == msg:
                    print(f"@{bot} is down.")
                    edit_text += f"☆[{bot}](http://t.me/{bot}) - ❌\n"
                elif snt.id + 1 == msg:
                    edit_text += f"★[{bot}](http://t.me/{bot}) - ✅\n"
                await user_bot.send_read_acknowledge(bot)
                c += 1
                await user_bot.edit_message(int(chnl_id), msg_id, edit_text)
            k = pytz.timezone("Asia/Kuala_Lumpur")
            q = pytz.timezone("Asia/Kolkata")
            month = dt.now(k).strftime("%B")
            day = dt.now(k).strftime("%d")
            year = dt.now(k).strftime("%Y")
            t = dt.now(k).strftime("%I:%M:%S %p")
            gmonth = dt.now(q).strftime("%B")
            gday = dt.now(q).strftime("%d")
            gyear = dt.now(q).strftime("%Y")
            gtime = dt.now(q).strftime("%I:%M:%S %p")
            edit_text += f"\n**📶 Last Checked** \n`⌚ Time: {t}``\n📅 Date: {day} {month} {year}``\n🌏 Time Zone: GMT+8``\n\nGlobal Time: {gtime}``\nGlobal Date: {gday} {gmonth} {gyear}`\n\n__Bots status are auto-updated every 20 minutes__\n\n✅ = Online\n❌ = Offline"
            await user_bot.edit_message(int(chnl_id),
                                        msg_id,
                                        edit_text,
                                        link_preview=False)
            print(f"Checks since last restart - {c}")
            print("Sleeping for 20 minutes.")
            await asyncio.sleep(20 * 60)
Ejemplo n.º 27
0
 def get_last_message_id(self, channel_name):
     channel_entity = self.client.get_entity(channel_name)
     posts = self.client(
         GetHistoryRequest(peer=channel_entity,
                           limit=1,
                           offset_date=None,
                           offset_id=0,
                           max_id=0,
                           min_id=0,
                           add_offset=0,
                           hash=0))
     try:
         return posts.messages[0].id
     except:
         return 0
Ejemplo n.º 28
0
async def get_message_count(client, entity, latest_id=0):
    get_history = GetHistoryRequest(peer=entity,
                                    offset_id=0,
                                    offset_date=None,
                                    add_offset=0,
                                    limit=1,
                                    max_id=0,
                                    min_id=latest_id or 0,
                                    hash=0)
    history = await client(get_history)
    if isinstance(history, Messages):
        count = len(history.messages)
    else:
        count = history.count
    return count
Ejemplo n.º 29
0
	def getMessages(self, channel_username):
		with TelegramClient(self.name, self.api_id, self.api_hash) as client:
			channel_entity = client.get_input_entity(channel_username)
			messages 	   = client(
				GetHistoryRequest(
					peer=channel_entity,
					limit=10,
					offset_date=None,
					offset_id=0,
					max_id=0,
					min_id=0,
					add_offset=0,
					hash=0
				)
			)
			return channel_username, messages
Ejemplo n.º 30
0
async def execute(phone, latest_message_id):
    await client.start()
    print("Client Created")
    # Ensure you're authorized
    if await client.is_user_authorized() == False:
        await client.send_code_request(phone)
        try:
            await client.sign_in(phone, input('Enter the code: '))
        except SessionPasswordNeededError:
            await client.sign_in(password=input('Password: '******'id']
        content = all_messages[0]['message']

        return (content, latest_message_id, all_messages)