Exemplo n.º 1
0
def get_post(post_id):
    print("get post : %s" % post_id)
    looter = PostLooter(post_id)
    post = looter.get_post_info(post_id)
    res = {
        "id": post["shortcode"],
        "user_name": post["owner"]["username"],
        "image_url": post["display_url"],
    }
    return res
Exemplo n.º 2
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.º 3
0
    def test_pr_122_download_post(self):
        """Feature implemented by @susundberg.

        Set the access time and modification time of a downloaded media
        according to its IG date.
        """
        code = 'BY77tSfBnRm'
        post_looter = PostLooter(code, session=self.session, template='{code}')
        info = post_looter.get_post_info(code)
        post_looter.download(self.destfs)
        stat = self.destfs.getdetails('{}.jpg'.format(code))
        self.assertEqual(stat.raw["details"]["accessed"], info['taken_at_timestamp'])
        self.assertEqual(stat.raw["details"]["modified"], info['taken_at_timestamp'])
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