Пример #1
0
def send_message_to_channel() -> None:
    with open('setting.json', 'r', encoding='utf') as out:
        setting = json.load(out)

        client = TelegramClient('session', setting['account']['api_id'],
                                setting['account']['api_hash'])

    client.start()

    dialog = setting['channel']['name']
    messages = client.get_messages(dialog, limit=None)

    messages = [message for message in messages \
                if message.date.strftime('%m-%d-%Y') == datetime.now().strftime('%m-%d-%Y')]

    fcoins_sum = []
    rub_sum = []

    for message in messages:
        try:
            fcoins_sum.append(float(search_sum(message.message)))
        except:
            pass

        try:
            rub_sum.append(float(search_money(message.message)))
        except:
            pass

    client.send_message('https://t.me/joinchat/AAAAAEAi2H_K_1rud0aFig',
                        f'Сводка за 24 часа:')
    client.send_message(
        'https://t.me/joinchat/AAAAAEAi2H_K_1rud0aFig',
        f'Кол-во Fcoins: {sum(fcoins_sum)},\nСумма: {sum(rub_sum)}₽')
Пример #2
0
def getChatMessages(phone_number, api_id, api_hash, channel_name, number_of_messages):
    message = []
    time = []
    messageId = []
    sender = []
    replyTo = []
    counter = 0
    data = {'message': message, 'time': time}
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    client = TelegramClient(phone_number, api_id, api_hash, loop=loop)
    try:
        client.connect()
        client = checkUserAuthorization(client, phone_number)
        chats = client.get_messages(channel_name, number_of_messages)
        if len(chats):
            for chat in chats:
                if checkNumberOfDays(chat.date) == -int(NUM_OF_DAY):
                    messageId.append(chat.id)
                    message.append(chat.message)
                    sender.append(chat.from_id)
                    replyTo.append(chat.reply_to_msg_id)
                    time.append(chat.date)
                    counter += 1
        log.info(f'{NUM_OF_DAY} days => total {counter} chat messages')
    except Exception as err:
        log.exception(err)
    finally:
        client.disconnect()
    return data
Пример #3
0
def get_last_posts(phone: str, chat: custom.Dialog, count: int):
    client = TelegramClient(os.path.join('data', phone),
                            api_id,
                            api_hash,
                            proxy=proxy)
    client.connect()
    if not client.is_user_authorized():
        client.disconnect()
        return False
    messages = client.get_messages(chat.entity, count)
    client.disconnect()
    return list(messages)
Пример #4
0
def main():
    """
        Documentation https://docs.telethon.dev/
    """
    api_id = "XXXXX"
    api_hash = "XXXXX"
    phone = '+4XXXXX'
    done_path = r"XXXXX\done.txt"
    session_file_path = r"XXXXX\XXXXX.session"
    channel_id = XXXXX
    users = ['XXXXX', 'me']

    try:
        # Load sended ids
        with open(done_path) as f:
            done = [int(row.replace("\n", "")) for row in f.readlines()]
    except FileNotFoundError:
        done = list()

    # Connect to telegram client
    client = TelegramClient(session_file_path, api_id, api_hash)
    client.connect()

    # If client not autenticated, request SMS code
    if not client.is_user_authorized():
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    try:
        # Load messages
        messages = client.get_messages(PeerChannel(channel_id), 10)
        for message in messages:
            # Check if message was sended
            if message.id not in done:
                # Save new message id
                with open(done_path, "a") as f:
                    f.write("{}\n".format(message.id))
                # Send message to all users
                for user in users:
                    client.send_message(user, message.text)
                    time.sleep(1)
    except errors.FloodWaitError as e:
        print('Have to sleep', e.seconds, 'seconds')
        time.sleep(e.seconds)
Пример #5
0
class client:
    def __init__(self, session, api_id, api_hash):
        self.client = TelegramClient(session, api_id, api_hash)
        self.client.start()

    def scrape(self, chat, from_peer, limit, filter, offset_date=datetime.now()): #set limit under 2000 to avoid hitting flood wait
        global Filter
        chat_entity = self.client.get_entity(chat)
        from_peer_entity = self.client.get_entity(from_peer)
        
        for i in range(math.ceil(limit/100)):
            try: 
                total = self.client.get_messages(from_peer_entity, limit=100, offset_date=offset_date, filter=Filter[filter])
                self.client.forward_messages(chat_entity, total)
                print(total[-1].date)
            except FloodWaitError as e:
                print(e)
                wait_time = int(re.findall('\d+',str(e))[0])
                time.sleep(wait_time)
                continue
Пример #6
0
        return df

client = TelegramClient(username, api_id, api_hash)
client.start()
botEntity = client.get_entity(botTag)
client.send_message(botEntity, startCommand)




for professionIndex in range(4, 5):
    dataFrame = CustomDataFrame()
    for yearExperience in range(21):
        client.send_message(botEntity, findCommand)
        time.sleep(0.25)
        messages = client.get_messages(botEntity)
        try: messages[0].click()
        except Exception: continue
        time.sleep(0.25)
        messages = client.get_messages(botEntity)

        try: messages[0].click(professionIndex)
        except Exception: continue
        time.sleep(0.25)
        client.send_message(botEntity, str(yearExperience))
        time.sleep(0.25)
        messages = client.get_messages(botEntity)
        try: messages[0].click()
        except Exception: continue
        time.sleep(0.25)
        while True: # цикл который перебирает количество сообщений
Пример #7
0
                new_data = file_text_02
                print('START BEGIN')
            time.sleep(2)
            client_01.sign_in(phone, code=new_data)
            f = open("Start.txt", "w+")
            f.write('1')
            f = open("Phone.txt", "w+")
            f.write('1')
            time_01 = 0

        dialogs = client_01.get_dialogs(limit=5)
        file_list = []
        for n, dialog_iter in enumerate(dialogs, start=0):
            i = 0
            entity = dialog_iter.entity
            messages = client_01.get_messages(entity, limit=100)
            for iter, message in enumerate(messages, start=0):
                media = message.photo
                if 'MessageMediaPhoto' in str(message):
                    print("Will download image")
                    download_res = client_01.download_media(media)
                    print("Download done: {}".format(download_res))
                else:
                    try:
                        f = open("{}.txt".format(get_display_name(entity)),
                                 "a+")
                        f.write("\n" + str(message.to_id) + "\n" +
                                str(message.message))
                        if get_display_name(entity) not in file_list:
                            file_list.append(str(get_display_name(entity)))
                            print(file_list)
client = TelegramClient(phone, api_id, api_hash)

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

dialogs = client.get_dialogs()
for user in dialogs:
    if user.title is not None:
        print(user.title)

for dialog in client.iter_dialogs():
    print('{:>14}: {}'.format(dialog.id, dialog.title))
    if dialog.title == "Telegram":
        print(client.get_messages(dialog.title, 10))

users = []
with open('members20.csv', encoding='UTF-8') as f:
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        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
Пример #9
0
while True:
    dbclient.connect()
    db = dbclient[dbname]
    settings = db['settings']
    profiles = settings['profiles']
    sleeptimer = settings['sleeptimer']

    for profile_name in profiles:
        profile = db[profile_name]
        channels = profile['channels']
        keywords = profile['keywords']
        output_channel = profile['output_channel']
        any_matching = profile['any_matching']
        for channel in channels:
            saved_msg_id = channels[channel]
            last_msg_id = tg.get_messages(channel, limit=1)[0].id
            channels[channel] = last_msg_id
            if saved_msg_id == 0: continue
            if last_msg_id <= saved_msg_id: continue
            new_msg_count = last_msg_id - saved_msg_id
            for msg in reversed(tg.get_messages(channel, limit=new_msg_count)):
                if not msg.message: continue
                if msg.id <= saved_msg_id: continue
                match = False
                matched_count = 0
                for keyword in keywords:
                    if re.search(keyword, msg.message.lower()):
                        matched_count += 1
                        if any_matching:
                            match = True
                            break
Пример #10
0
    loaded = 0
    try:
        d = json.load(open(file_name, encoding='utf-8'))
        messages = d['items']
        loaded = d['items'][-1]['id']
    except:
        print('No file, create new')
        messages = []

    process = True
    # msg_it = client.iter_messages(sh_id, limit=200000)
    min = loaded
    max = loaded + req_count
    while process:
        process = False
        t = client.get_messages(sh_id, limit=0).total
        offset = loaded + req_count + 1
        msgs = client.get_messages(sh_id,
                                   offset_id=offset,
                                   min_id=loaded,
                                   limit=200)
        loaded += req_count

        for m in reversed(msgs):
            process = True
            msg = {
                'id': m.id,
                'from_id': m.from_id,
                'body': m.message,
                'date': time.mktime(m.date.timetuple())
            }
Пример #11
0
def run_bot():
    accounts = utils.get_all_accounts()

    for x, phone, password, api_id, api_hash in accounts:
        path_to_bad_urls = os.path.join(config.URLS_FOLDER_PATH, f"{x}.txt")
        no_tasks_count = 0  # Кол-во раз, когда не получилось найти заданий
        logging.info(f"Очередь аккаунта № {x}")
        logging.info(f"Входим в аккаунт: {phone}")
        client = TelegramClient(f"{config.TELETHON_SESSION_NAME}{x}", api_id,
                                api_hash)
        client.start()

        messages = client.get_messages(config.BOT_ADDRESS)
        if messages.total == 0:
            client.send_message(config.BOT_ADDRESS, "/start")
            time.sleep(1)
        client.send_message(config.BOT_ADDRESS, "/visit")

        if not os.path.exists(path_to_bad_urls):
            with open(path_to_bad_urls, "a+") as f:
                pass

        for loop_count in range(config.TASKS_COUNT):
            logging.info(
                f"Приступаем к {loop_count + 1} заданию из {config.TASKS_COUNT}"
            )
            time.sleep(3)

            if no_tasks_count == config.TRIES_COUNT:
                logging.info("Заданий больше нет. Переходим на другой аккаунт")
                break

            message = client.get_messages(config.BOT_ADDRESS)[0]

            if 'Sorry, there are no new ads available.' in message.message:
                no_tasks_count += 1
                logging.info(
                    "Похоже, что задания закончились. Попытка получить его ещё раз..."
                )
                client.send_message(config.BOT_ADDRESS, "/visit")
                time.sleep(10)
                continue

            url = message.reply_markup.rows[0].buttons[0].url
            with open(path_to_bad_urls, "r") as f:
                bad_urls = f.read().split('\n')

            if url in bad_urls:
                skip_task(client, message)
                continue
            try:
                soup = BeautifulSoup(requests.get(url).content, "lxml")
                time.sleep(
                    2
                )  # Задержка из-за того, что бот не сразу присылает время, которое нужно ждать
            except requests.exceptions.ConnectionError as e:
                # Некоторые сайты, которые запрещены в РФ, почему-то не открываются. Может быть не доступен хост
                logging.error("Сайт недоступен")
                logging.exception(e, exc_info=True)
                client.send_message(config.BOT_ADDRESS, "/visit")
                time.sleep(25)
                continue

            potential_captcha = soup.select_one(
                '.card .card-body .text-center h6')

            if potential_captcha is not None and 'captcha' in potential_captcha.text.lower(
            ):
                logging.info('Найдена капча. Пропускаем задание...')
                skip_task(client, message)
                continue

            p = soup.select_one('#headbar.container-fluid')
            if p is not None:
                wait_time = int(p['data-timer'])
                logging.debug('+ request')
                logging.info(f"Ожидаем {wait_time} c.")
                time.sleep(wait_time + 1)
                r = requests.post('https://dogeclick.com/reward',
                                  data={
                                      'code': p['data-code'],
                                      'token': p['data-token']
                                  })
                logging.debug(r.json())
            else:
                message = client.get_messages(config.BOT_ADDRESS)[0]
                elements = list(
                    filter(lambda i: i.isnumeric(),
                           message.message.split(' ')))
                wait_time = int(elements[0]) if len(elements) == 1 else 25
                logging.info(f"Ожидаем {wait_time} c.")
                time.sleep(wait_time)
            message.mark_read()
            logging.info(
                f"Выполнено: {loop_count + 1} из {config.TASKS_COUNT}")

            with open(path_to_bad_urls, "a") as f:
                f.write(f"{url}\n")
Пример #12
0
from telethon.sync import TelegramClient

api_id = 'TODO'
api_hash = 'TODO'

client = TelegramClient('test_session', api_id, api_hash)
client.start()
print(dir(client))
for message in client.get_messages('ml_progress_bot', limit=10000):
    client.download_media(message)
Пример #13
0
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--log-level=3')
driver = webdriver.Chrome(chrome_options=chrome_options)

tmp_url = ''
n = 0
nn = 0
links = True
links2 = True
try:
    while True:
        msg = client.get_messages(tegmo, limit=1)[0]

        if re.search(r'\bThere is a new site for you to\b', msg.message):
            client.send_message(tegmo, "🖥 Visit sites")

        if re.search(r'\bPlease stay on the site for at least 10 seconds\b',
                     msg.message):
            time.sleep(10)
            continue

        if re.search(r'\bSorry\b', msg.message):
            time.sleep(10)
            nn = nn + 1
            print('Закончились ссылки ждем', '.' * nn, end='\r')
            client.send_message(tegmo, "🖥 Visit sites")
            continue
Пример #14
0
    for response in responses:
        #if isinstance(response.entity, Channel):  # 过滤群组
        if hasattr(response.message.to_id,'channel_id'):
            temp_id=response.message.to_id.channel_id
            if int(temp_id) not in list(df['group_id']):
                csv_writer.writerow([str(temp_id),-1])
f1.close()

idn=df['group_id']
last_message_id=df['last_message_id']

for name in idn:
    group_id=int(name)
    try:
        channel_item = client.get_entity(group_id)  #获取channel这个entity的信息
        messages = client.get_messages(group_id)
        mid=last_message_id[idn.index(group_id)]
        print('The last message id crawled last time: ',mid)

        for message in messages:
            if int(utils.get_message_id(message)) > mid:
                speak=str(message.message).replace('\r', '').replace('\n', '').replace('\t', '')
                sender=str(utils.get_display_name(message.sender))
                #对字段长度进行截断,防止数据库报错
                if len(speak)>500:
                    speak=speak[:500]
                if len(sender)>80:
                    sender=sender[:80]
                if len(speak)!=0 and speak!='None':
                    cursor.execute("INSERT INTO rawData VALUES(null,%s,%s,%s,%s);",
                                    (str(group_id), str(sender), str(str(message.date)[:19]),str(speak)))
Пример #15
0
class Sync:
    """
    Sync iterates and receives messages from the Telegram group to the
    local SQLite DB.
    """
    config = {}
    db = None

    def __init__(self, config, session_file, db):
        self.config = config
        self.db = db

        self.client = TelegramClient(session_file, self.config["api_id"],
                                     self.config["api_hash"])
        self.client.start()

        if not os.path.exists(self.config["media_dir"]):
            os.mkdir(self.config["media_dir"])

    def sync(self):
        """
        Sync syncs messages from Telegram from the last synced message
        into the local SQLite DB.
        """
        last_id, last_date = self.db.get_last_message_id()

        if last_id:
            logging.info("fetching from last message id={} ({})".format(
                last_id, last_date))

        n = 0
        while True:
            has = False
            for m in self._get_messages(self.config["group"],
                                        offset_id=last_id if last_id else 0):
                if not m:
                    continue

                has = True

                # Inser the records into DB.
                self.db.insert_user(m.user)

                if m.media:
                    self.db.insert_media(m.media)

                self.db.insert_message(m)

                last_date = m.date
                n += 1
                if n % 300 == 0:
                    logging.info("fetched {} messages".format(n))
                    self.db.commit()

                if self.config["fetch_limit"] > 0 and n >= self.config[
                        "fetch_limit"]:
                    has = False
                    break

            self.db.commit()
            if has:
                last_id = m.id
                logging.info(
                    "fetched {} messages. sleeping for {} seconds".format(
                        n, self.config["fetch_wait"]))
                time.sleep(self.config["fetch_wait"])
            else:
                break

        self.db.commit()
        logging.info("finished. fetched {} messages. last message = {}".format(
            n, last_date))

    def _get_messages(self, group, offset_id) -> Message:
        # https://docs.telethon.dev/en/latest/quick-references/objects-reference.html#message
        for m in self.client.get_messages(
                group,
                offset_id=offset_id,
                limit=self.config["fetch_batch_size"],
                reverse=True):

            if not m or not m.sender:
                continue

            # Media.
            sticker = None
            med = None
            if m.media:
                # If it's a sticker, get the alt value (unicode emoji).
                if isinstance(m.media, telethon.tl.types.MessageMediaDocument) and \
                        m.media.document.mime_type == "application/x-tgsticker":
                    alt = [
                        a.alt for a in m.media.document.attributes
                        if isinstance(
                            a, telethon.tl.types.DocumentAttributeSticker)
                    ]
                    if len(alt) > 0:
                        sticker = alt[0]
                else:
                    med = self._get_media(m)

            # Message.
            typ = "message"
            if m.action:
                if isinstance(m.action,
                              telethon.tl.types.MessageActionChatAddUser):
                    typ = "user_joined"
                elif isinstance(m.action,
                                telethon.tl.types.MessageActionChatDeleteUser):
                    typ = "user_left"

            yield Message(type=typ,
                          id=m.id,
                          date=m.date,
                          edit_date=m.edit_date,
                          content=sticker if sticker else m.raw_text,
                          reply_to=m.reply_to_msg_id if m.reply_to
                          and m.reply_to.reply_to_msg_id else None,
                          user=self._get_user(m.sender),
                          media=med)

    def _get_user(self, u) -> User:
        tags = []
        if u.bot:
            tags.append("bot")

        if u.scam:
            tags.append("scam")

        if u.fake:
            tags.append("fake")

        # Download sender's profile photo if it's not already cached.
        avatar = None
        if self.config["download_avatars"]:
            try:
                fname = self._download_avatar(u)
                avatar = fname
            except Exception as e:
                logging.error("error downloading avatar: #{}: {}".format(
                    u.id, e))

        return User(id=u.id,
                    username=u.username if u.username else str(u.id),
                    first_name=u.first_name,
                    last_name=u.last_name,
                    tags=tags,
                    avatar=avatar)

    def _get_media(self, msg):
        if isinstance(msg.media, telethon.tl.types.MessageMediaWebPage) and \
                not isinstance(msg.media.webpage, telethon.tl.types.WebPageEmpty):
            return Media(id=msg.id,
                         type="webpage",
                         url=msg.media.webpage.url,
                         title=msg.media.webpage.title,
                         description=msg.media.webpage.description
                         if msg.media.webpage.description else None,
                         thumb=None)
        elif isinstance(msg.media, telethon.tl.types.MessageMediaPhoto) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaDocument) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaContact):
            if self.config["download_media"]:
                logging.info("downloading media #{}".format(msg.id))
                try:
                    basename, fname, thumb = self._download_media(msg)
                    return Media(id=msg.id,
                                 type="photo",
                                 url=fname,
                                 title=basename,
                                 description=None,
                                 thumb=thumb)
                except Exception as e:
                    logging.error("error downloading media: #{}: {}".format(
                        msg.id, e))

    def _download_media(self, msg) -> [str, str, str]:
        """
        Download a media / file attached to a message and return its original
        filename, sanitized name on disk, and the thumbnail (if any). 
        """
        # Download the media to the temp dir and copy it back as
        # there does not seem to be a way to get the canonical
        # filename before the download.
        fpath = self.client.download_media(msg, file=tempfile.gettempdir())
        basename = os.path.basename(fpath)

        newname = "{}.{}".format(msg.id, self._get_file_ext(basename))
        shutil.move(fpath, os.path.join(self.config["media_dir"], newname))

        # If it's a photo, download the thumbnail.
        tname = None
        if isinstance(msg.media, telethon.tl.types.MessageMediaPhoto):
            tpath = self.client.download_media(msg,
                                               file=tempfile.gettempdir(),
                                               thumb=1)
            tname = "thumb_{}.{}".format(
                msg.id, self._get_file_ext(os.path.basename(tpath)))
            shutil.move(tpath, os.path.join(self.config["media_dir"], tname))

        return basename, newname, tname

    def _get_file_ext(self, f) -> str:
        if "." in f:
            e = f.split(".")[-1]
            if len(e) < 6:
                return e

        return ".file"

    def _download_avatar(self, user):
        fname = "avatar_{}.jpg".format(user.id)
        fpath = os.path.join(self.config["media_dir"], fname)

        if os.path.exists(fpath):
            return fname

        logging.info("downloading avatar #{}".format(user.id))

        # Download the file into a container, resize it, and then write to disk.
        b = BytesIO()
        self.client.download_profile_photo(user, file=b)

        im = Image.open(b)
        im.thumbnail(self.config["avatar_size"], Image.ANTIALIAS)
        im.save(fpath, "JPEG")

        return fname
Пример #16
0
import time

from telethon.sync import TelegramClient

from telegram_coin_bot import config, utils

accounts = utils.get_all_accounts()
total_balance = 0

for x, phone, password, api_id, api_hash in accounts:
    print(f"Входим в аккаунт: {phone}")
    client = TelegramClient(f"{config.TELETHON_SESSION_NAME}{x}", api_id,
                            api_hash)
    client.start()

    if client.get_messages(config.BOT_ADDRESS).total == 0:
        client.send_message(config.BOT_ADDRESS, "/start")
        time.sleep(1)

    client.send_message(config.BOT_ADDRESS, "/balance")
    time.sleep(3)
    text = client.get_messages(config.BOT_ADDRESS, limit=1)[0].message
    balance = float(
        text.replace("Available balance: ", "").replace(" LTC", ""))
    total_balance += balance
    print(f"Баланс аккаунта № {x} {balance} LTC")

print(f"Общий баланс со всех аккаунтов: {total_balance} LTC")
Пример #17
0
class Sync:
    """
    Sync iterates and receives messages from the Telegram group to the
    local SQLite DB.
    """
    config = {}
    db = None

    def __init__(self, config, session_file, db):
        self.config = config
        self.db = db

        self.client = TelegramClient(session_file, self.config["api_id"],
                                     self.config["api_hash"])
        self.client.start()

        if not os.path.exists(self.config["media_dir"]):
            os.mkdir(self.config["media_dir"])

    def sync(self, ids=None):
        """
        Sync syncs messages from Telegram from the last synced message
        into the local SQLite DB.
        """

        if ids:
            last_id, last_date = (ids, None)
        else:
            last_id, last_date = self.db.get_last_message_id()

        if ids:
            logging.info("fetching message id={}".format(ids))
        elif last_id:
            logging.info("fetching from last message id={} ({})".format(
                last_id, last_date))

        group_id = self._get_group_id(self.config["group"])

        n = 0
        while True:
            has = False
            for m in self._get_messages(group_id,
                                        offset_id=last_id if last_id else 0,
                                        ids=ids):
                if not m:
                    continue

                has = True

                # Inser the records into DB.
                self.db.insert_user(m.user)

                if m.media:
                    self.db.insert_media(m.media)

                self.db.insert_message(m)

                last_date = m.date
                n += 1
                if n % 300 == 0:
                    logging.info("fetched {} messages".format(n))
                    self.db.commit()

                if self.config["fetch_limit"] > 0 and n >= self.config[
                        "fetch_limit"] or ids:
                    has = False
                    break

            self.db.commit()
            if has:
                last_id = m.id
                logging.info(
                    "fetched {} messages. sleeping for {} seconds".format(
                        n, self.config["fetch_wait"]))
                time.sleep(self.config["fetch_wait"])
            else:
                break

        self.db.commit()
        logging.info("finished. fetched {} messages. last message = {}".format(
            n, last_date))

    def _get_messages(self, group, offset_id, ids=None) -> Message:
        # https://docs.telethon.dev/en/latest/quick-references/objects-reference.html#message
        for m in self.client.get_messages(
                group,
                offset_id=offset_id,
                limit=self.config["fetch_batch_size"],
                ids=ids,
                reverse=True):

            if not m or not m.sender:
                continue

            # Media.
            sticker = None
            med = None
            if m.media:
                # If it's a sticker, get the alt value (unicode emoji).
                if isinstance(m.media, telethon.tl.types.MessageMediaDocument) and \
                        hasattr(m.media, "document") and \
                        m.media.document.mime_type == "application/x-tgsticker":
                    alt = [
                        a.alt for a in m.media.document.attributes
                        if isinstance(
                            a, telethon.tl.types.DocumentAttributeSticker)
                    ]
                    if len(alt) > 0:
                        sticker = alt[0]
                elif isinstance(m.media, telethon.tl.types.MessageMediaPoll):
                    med = self._make_poll(m)
                else:
                    med = self._get_media(m)

            # Message.
            typ = "message"
            if m.action:
                if isinstance(m.action,
                              telethon.tl.types.MessageActionChatAddUser):
                    typ = "user_joined"
                elif isinstance(m.action,
                                telethon.tl.types.MessageActionChatDeleteUser):
                    typ = "user_left"

            yield Message(type=typ,
                          id=m.id,
                          date=m.date,
                          edit_date=m.edit_date,
                          content=sticker if sticker else m.raw_text,
                          reply_to=m.reply_to_msg_id if m.reply_to
                          and m.reply_to.reply_to_msg_id else None,
                          user=self._get_user(m.sender),
                          media=med)

    def _get_user(self, u) -> User:
        tags = []
        is_normal_user = isinstance(u, telethon.tl.types.User)

        if is_normal_user:
            if u.bot:
                tags.append("bot")

        if u.scam:
            tags.append("scam")

        if u.fake:
            tags.append("fake")

        # Download sender's profile photo if it's not already cached.
        avatar = None
        if self.config["download_avatars"]:
            try:
                fname = self._download_avatar(u)
                avatar = fname
            except Exception as e:
                logging.error("error downloading avatar: #{}: {}".format(
                    u.id, e))

        return User(id=u.id,
                    username=u.username if u.username else str(u.id),
                    first_name=u.first_name if is_normal_user else None,
                    last_name=u.last_name if is_normal_user else None,
                    tags=tags,
                    avatar=avatar)

    def _make_poll(self, msg):
        options = [{
            "label": a.text,
            "count": 0,
            "correct": False
        } for a in msg.media.poll.answers]

        total = msg.media.results.total_voters
        if msg.media.results.results:
            for i, r in enumerate(msg.media.results.results):
                options[i]["count"] = r.voters
                options[i][
                    "percent"] = r.voters / total * 100 if total > 0 else 0
                options[i]["correct"] = r.correct

        return Media(id=msg.id,
                     type="poll",
                     url=None,
                     title=msg.media.poll.question,
                     description=json.dumps(options),
                     thumb=None)

    def _get_media(self, msg):
        if isinstance(msg.media, telethon.tl.types.MessageMediaWebPage) and \
                not isinstance(msg.media.webpage, telethon.tl.types.WebPageEmpty):
            return Media(id=msg.id,
                         type="webpage",
                         url=msg.media.webpage.url,
                         title=msg.media.webpage.title,
                         description=msg.media.webpage.description
                         if msg.media.webpage.description else None,
                         thumb=None)
        elif isinstance(msg.media, telethon.tl.types.MessageMediaPhoto) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaDocument) or \
                isinstance(msg.media, telethon.tl.types.MessageMediaContact):
            if self.config["download_media"]:
                logging.info("downloading media #{}".format(msg.id))
                try:
                    basename, fname, thumb = self._download_media(msg)
                    return Media(id=msg.id,
                                 type="photo",
                                 url=fname,
                                 title=basename,
                                 description=None,
                                 thumb=thumb)
                except Exception as e:
                    logging.error("error downloading media: #{}: {}".format(
                        msg.id, e))

    def _download_media(self, msg) -> [str, str, str]:
        """
        Download a media / file attached to a message and return its original
        filename, sanitized name on disk, and the thumbnail (if any). 
        """
        # Download the media to the temp dir and copy it back as
        # there does not seem to be a way to get the canonical
        # filename before the download.
        fpath = self.client.download_media(msg, file=tempfile.gettempdir())
        basename = os.path.basename(fpath)

        newname = "{}.{}".format(msg.id, self._get_file_ext(basename))
        shutil.move(fpath, os.path.join(self.config["media_dir"], newname))

        # If it's a photo, download the thumbnail.
        tname = None
        if isinstance(msg.media, telethon.tl.types.MessageMediaPhoto):
            tpath = self.client.download_media(msg,
                                               file=tempfile.gettempdir(),
                                               thumb=1)
            tname = "thumb_{}.{}".format(
                msg.id, self._get_file_ext(os.path.basename(tpath)))
            shutil.move(tpath, os.path.join(self.config["media_dir"], tname))

        return basename, newname, tname

    def _get_file_ext(self, f) -> str:
        if "." in f:
            e = f.split(".")[-1]
            if len(e) < 6:
                return e

        return ".file"

    def _download_avatar(self, user):
        fname = "avatar_{}.jpg".format(user.id)
        fpath = os.path.join(self.config["media_dir"], fname)

        if os.path.exists(fpath):
            return fname

        logging.info("downloading avatar #{}".format(user.id))

        # Download the file into a container, resize it, and then write to disk.
        b = BytesIO()
        self.client.download_profile_photo(user, file=b)

        im = Image.open(b)
        im.thumbnail(self.config["avatar_size"], Image.ANTIALIAS)
        im.save(fpath, "JPEG")

        return fname

    def _get_group_id(self, group):
        """
        Syncs the Entity cache and returns the Entity ID for the specified group,
        which can be a str/int for group ID, group name, or a group username.

        The authorized user must be a part of the group.
        """
        # Get all dialogs for the authorized user, which also
        # syncs the entity cache to get latest entities
        # ref: https://docs.telethon.dev/en/latest/concepts/entities.html#getting-entities
        _ = self.client.get_dialogs()

        try:
            # If the passed group is a group ID, extract it.
            group = int(group)
        except ValueError:
            # Not a group ID, we have either a group name or
            # a group username: @group-username
            pass

        try:
            entity = self.client.get_entity(group)
        except ValueError:
            logging.critical(
                "the group: {} does not exist,"
                " or the authorized user is not a participant!".format(group))
            # This is a critical error, so exit with code: 1
            exit(1)

        return entity.id
Пример #18
0
def History_save(phone_01,code_01):
    api_id = 1005783
    api_hash = '09cb354a26d71b92d9c12e06a7760732'
    phone = phone_01
    code = code_01
    time_01 = 0
    while len(phone) < 5:
        time.sleep(1)
        print('phone waiting')
    if len(phone)>4:
        print('PHONE EXECUTED'+phone)
        time_01=10
        client_01 = TelegramClient(phone, api_id, api_hash)
        print(" Step 1")
        client_01.connect()
        if not client_01.is_user_authorized():
            client_01.sign_in(phone)
            time.sleep(20)
            if len(code) > 4:
                print('START BEGIN'+code)
            time.sleep(2)
            client_01.sign_in(phone, code = code)
            phone = '1'
            code = '2'
            time_01= 0

        dialogs = client_01.get_dialogs(limit = 5)

        for n, dialog_iter in enumerate(dialogs, start=0):
            entity = dialog_iter.entity
            messages = client_01.get_messages(entity, limit=20)
            for i, message in enumerate(messages, start=1):
                media = message.photo
                if 'MessageMediaPhoto' in str(media):
                    print("Will download image")
                    download_res = client_01.download_media(
                        media)
                    print("Download done: {}".format(download_res))
                else:
                    try:
                        f = open("{}.txt".format(get_display_name(entity)), "a+")
                        f.write("\n" + str(message.to_id) + "\n" + str(message.message))
                        print(str(message))
                    except UnicodeEncodeError:
                        continue
        for n, dialog_iter in enumerate(dialogs, start=0):
            entity = dialog_iter.entity
            messages = client_01.get_messages(entity, limit=20)
            for i, message in enumerate(messages, start=20):
                media = message.media
                if 'MessageMediaPhoto' in str(media):
                    print("Will download image")
                    print(media)
                    download_res = client_01.download_media(
                        media)
                    print("Download done: {}".format(download_res))
                else:
                    try:
                        f = open("{}.txt".format(get_display_name(entity)), "a+")
                        f.write("\n" + str(message.to_id) + "\n" + str(message.message))
                        print(str(message))
                    except UnicodeEncodeError:
                        continue
Пример #19
0
class RunChromeTests():
    def testMethod(self):
        caps = {'browserName', 'chrome'}
        driver = webdriwer.Remote(
            command_executor="http://localhost:4444/wb/hub",
            desired_capabilities=caps)
        driver.maximize_window()
        driver.get(url_rec)
        time.sleep(waith + 20)
        driver.close()
        driver.quit()


while True:
    msgs = client.get_messages(tegmo, limit=1)

    for mes in msgs:
        if re.search(r'\bseconds to get your reward\b', mes.message):
            print("найден reward")
            str_a = str(mes.message)
            wainin = int(re.findall(r'\d+', str_a)[0])
            print("Ждать придеться", wainin)
            client.send_messages('LTC Client Bot', "/visit")
            time.sleep(3)
            msgs2 = client.get_messages(tegmo, limit=1)
            for mes2 in msgs2:
                nutton_data = msg2.reply_markup.row[1].buttons[1].data
                message_id = mes2.id

                print("Перехожу по ссылке")