def send_text(message):
    log(strftime("%Y-%m-%d %H:%M:%S", gmtime()), message)

    if 'instagram.com/p/' in message.text:
        path = message.text
        looter = PostLooter(path)
        if looter.info['__typename'] == 'GraphImage':
            picture_id = looter.info['id']
            looter.download('./pictures/')
            bot.send_photo(message.chat.id,
                           open('./pictures/{}.jpg'.format(picture_id), 'rb'),
                           caption='🤖 Downloaded with @instsave_bot')
        elif looter.info['__typename'] == 'GraphVideo':
            video_id = looter.info['id']
            looter.download_videos('./videos/')
            bot.send_video(message.chat.id,
                           open('./videos/{}.mp4'.format(video_id), 'rb'),
                           caption='🤖 Downloaded with @instsave_bot')
        elif looter.info['__typename'] == 'GraphSidecar':
            bot.send_message(
                message.chat.id,
                'Sorry, I can\'t send you post with more than 1 photo\n\nPlease try again'
            )
    elif 'private' in message.text:
        bot.send_message(436264579, message.text[7:])
    else:
        bot.send_message(
            message.chat.id,
            'Please, send link or username\n\nNeed more help?\nJust tap: /help'
        )
Exemplo n.º 2
0
def instagram_v(url):
    looter = PostLooter(url)

    # Скачивание
    video_id = looter.info['id']
    looter.download_videos('./videos/')

    file = open('./videos/{}.mp4'.format(video_id), 'rb')
    return file
Exemplo n.º 3
0
def download_instagram_vid(post_id):
    """Attempt to download the video"""
    try:
        looter = PostLooter(post_id)
    except ValueError:
        print("Couldn't get video from the link. The user's profile may be private.")
        sys.exit(1)
    info = looter.get_post_info(post_id)
    video = info['id']
    username = info['owner']['username']
    return video, username, looter.download_videos(destination)
Exemplo n.º 4
0
async def update(tg_chatid, ig_profile):
    write(f"\033[2K\rchecking @{ig_profile}…")
    await bot.send_chat_action(tg_chatid, types.ChatActions.TYPING)
    try:
        pl = ProfileLooter(ig_profile)
    except Exception as e:
        write(f"\033[2K\r\033[31munable to get profile @{ig_profile}\033[0m\n")
        print(tb.format_exc())
        return False
    with open(sent_fp, "r") as f:
        sent = json.load(f)
    sent_something = False
    for j, media in enumerate(pl.medias()):
        i = media["id"]
        sc = media["shortcode"]
        write(f"\033[2K\rchecking @{ig_profile} ({j}|{i}|{sc})")
        if i not in sent:
            write(": \033[sgetting post…")
            _pl = PostLooter(sc)
            try:
                info = _pl.get_post_info(sc)
            except Exception as e:  #because the library I use can randomly throw errors while getting stuff…
                write("\033[u\033[0K\033[31munable to get post\033[0m\n")
                print(tb.format_exc())
                continue
            caption = "\n".join(
                edge["node"]["text"]
                for edge in info["edge_media_to_caption"]["edges"])
            with MemoryFS() as fs:
                if media["is_video"]:
                    await bot.send_chat_action(tg_chatid,
                                               types.ChatActions.RECORD_VIDEO)
                    _pl.download_videos(fs, media_count=1)
                    func = bot.send_video
                    fn = fs.listdir("./")[0]
                    await bot.send_chat_action(tg_chatid,
                                               types.ChatActions.UPLOAD_VIDEO)
                elif media["__typename"].lower() == "graphimage":
                    await bot.send_chat_action(tg_chatid,
                                               types.ChatActions.UPLOAD_PHOTO)
                    _pl.download_pictures(fs, media_count=1)
                    func = bot.send_photo
                    fn = fs.listdir("./")[0]
                elif media["__typename"].lower() == "graphsidecar":
                    await bot.send_chat_action(tg_chatid,
                                               types.ChatActions.UPLOAD_PHOTO)
                    _pl.download_pictures(fs)
                    fn = tuple(fs.listdir("./"))
                    if len(fn) == 1:
                        func = bot.send_photo
                        fn = fn[0]
                    else:
                        func = bot.send_media_group
                else:
                    await bot.send_message(
                        tg_chatid,
                        f"Oh-oh. I've encountered a new post type!\nPlease tell my developer, so he can tell me what I should do with a {media}."
                    )
                    print("\n\033[31mUNKNOWN MEDIA TYPE AAAAA\033[0m", media)
                    break
                if isinstance(fn, tuple):
                    write("\033[u\033[0Ksending album…")
                    f = [fs.openbin(_fn) for _fn in fn]
                    _media = types.input_media.MediaGroup()
                    for _f in f:
                        _media.attach_photo(_f)
                else:
                    write("\033[u\033[0Ksending file…")
                    _media = f = fs.openbin(fn)
                if len(
                        caption
                ) > 100:  #telegram media captions have a character limit of 200 chars & I want to have a buffer
                    caption = caption[:100] + "[…]"
                markdown.quote_html(caption)
                text = f"{caption}\n→<a href=\"https://www.instagram.com/p/{sc}\">original post</a>"
                try:
                    if isinstance(fn, tuple):
                        msg_id = (await func(tg_chatid,
                                             _media))[-1]["message_id"]
                        await bot.send_message(tg_chatid,
                                               text,
                                               reply_to_message_id=msg_id,
                                               parse_mode=types.ParseMode.HTML)
                    else:
                        await func(tg_chatid,
                                   _media,
                                   caption=text,
                                   parse_mode=types.ParseMode.HTML)
                except exceptions.BadRequest as e:
                    write(
                        "\033[u\033[0K\033[31mskipped\033[0m\nGot Bad Request while trying to send message.\n"
                    )
                except exceptions.RetryAfter as e:
                    write(
                        "\nMEEP MEEP FLOOD CONTROL - YOU'RE FLOODING TELEGRAM\nstopping sending messages & waiting for next cycle…\n"
                    )
                    break
                else:
                    sent.append(i)
                    write("\033[u\033[0Ksaving sent messages…\033[0m")
                    with open(sent_fp, "w+") as f:
                        json.dump(sent, f)
                    write("\033[u\033[0K\033[32msent\033[0m\n")
                if isinstance(f, list):
                    for _f in f:
                        _f.close()
                else:
                    f.close()
            sent_something = True
        # sometimes the page has to be reloaded, which would prolong the time the checking post…
        # message would be displayed if I didn't do this
        write(f"\033[2K\rchecking @{ig_profile}…")
    return sent_something
def application(url, path):
    looter = PostLooter(url)
    var = looter.download_videos(f"media/{path}")
    return var