Ejemplo n.º 1
0
def main():
    load_dotenv()
    os.makedirs('images', exist_ok=True)

    fetch_spacex_last_launch('https://api.spacexdata.com/v3/launches/latest')
    fetch_hubble_pictures('http://hubblesite.org/api/v3/images?page=all&collection_name=printshop')
    publish_photos()
Ejemplo n.º 2
0
def main():
    load_dotenv()
    username = os.getenv('INSTAGRAM_USERNAME')
    password = os.getenv('INSTAGRAM_PASSWORD')
    Path('images').mkdir(parents=True, exist_ok=True)
    Path('converted_images').mkdir(parents=True, exist_ok=True)
    fetch_spacex_last_launch()
    fetch_hubble_collection('news')
    post_all_images(username, password)
Ejemplo n.º 3
0
def main():
    directory_for_save = 'images'
    fetch_spacex_last_launch(directory_for_save)
    get_hubble_collection('wallpaper', directory_for_save)
    instagram_login, instagram_password = get_login_pass()
    for image_file_name in get_images_list():
        make_image_square(image_file_name)
        post_image_to_instagram(instagram_login, instagram_password,
                                image_file_name)
        time.sleep(3)
Ejemplo n.º 4
0
def upload_inst(path_image):
    bot = Bot()
    bot.login()
    fetch_collection('wallpaper')
    fetch_spacex_last_launch()
    resize_img("img/")
    list_img = os.listdir(path_image)
    for img in list_img:
        try:
            bot.upload_photo(path_image + img, caption="Elon Mask")
        except RuntimeError:
            continue
Ejemplo n.º 5
0
def main():
    load_dotenv()
    dir_name = os.path.join("images", "")
    create_dir_image(dir_name)

    fetch_spacex_last_launch()
    get_colection_from_Hubble("spacecraft")

    inst_login = os.getenv("INTGR_LOGIN")
    inst_passwd = os.getenv("INTGR_PASSWD")
    bot = Bot()
    bot.login(username=inst_login, password=inst_passwd)
    file_unload_instagramm("images")
Ejemplo n.º 6
0
def main():
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument("-u", type=str, help="username")
    parser.add_argument("-p", type=str, help="password")
    parser.add_argument("-proxy", type=str, help="proxy")
    args = parser.parse_args()

    images_spacex = fetch_spacex.fetch_spacex_last_launch()
    file_name = 'spacex'
    images.save_images_in_directory(images_spacex, file_name)

    current_images_directory = images.get_directory_images()
    collection_hubble_name = 'holiday_cards'
    images_data = fetch_hubble.receive_images_from_collection(collection_hubble_name)
    for image_numerator, image_data in enumerate(images_data):
        image_name = image_data['image_name']
        url = image_data['url']
        extension_image = images.get_file_extension(url)
        name = f'{image_name}_{image_numerator}{extension_image}'
        full_name = Path(current_images_directory).joinpath(name)
        images.download_image(url, full_name)

    upload_to_instagram.prepare_images_for_publicatioin()
    username = args.u
    password = args.p
    proxy = args.proxy
    upload_to_instagram.upload_pictures_to_instagram(username, password, proxy)
def main():
    load_dotenv()
    insta_login = os.getenv("INSTA_LOGIN")
    insta_password = os.getenv("INSTA_PASSWORD")

    parser = argparse.ArgumentParser()
    parser.add_argument("collection")
    args = parser.parse_args()
    collection = args.collection

    insta_bot = Bot()
    insta_bot.login(username=insta_login, password=insta_password)

    fetch_spacex_last_launch()
    fetch_huble_images_from_collection(collection=collection)
    public_photos(insta_bot, 'media')
Ejemplo n.º 8
0
def main():

    fetch_hubble.fetch_hubble_images()
    fetch_spacex.fetch_spacex_last_launch(settings.SPACEX_PHOTO_NAME)
    bot = Bot()
    bot.login(username=os.getenv('LOGIN'), password=os.getenv('PASSWORD'))
    print('Начинаем выгрузку файлов в Instagram  ,пожалуйста подождите...')
    extensions = ('.jpg', '.JPG', '.png', '.PNG')
    for img in os.listdir(settings.IMAGE_DIR):
        if os.path.isfile(settings.IMAGE_DIR + '/' +
                          img) and img.endswith(extensions):
            bot.upload_photo(settings.IMAGE_DIR + '/' + img,
                             caption=settings.INSTAGRAM_PHOTO_CAPTIONS)
            time.sleep(3)
        else:
            print('Подходящие файлы не найдены')
Ejemplo n.º 9
0
def main():
  load_dotenv()

  parser = argparse.ArgumentParser(
    description='Описание что делает программа'
  )
  parser.add_argument('-dir', '--dir',
                       help='Имя директории для картинок',
                       default='images')
  parser.add_argument('-space', '--space',
                       action='store_true',
                       help='Фото запусков SpaceX')
  parser.add_argument('-hab', '--habble',
                       action='store_true',
                       help='Фото телескопа Habble')
  parser.add_argument('-col', '--collection',
                       help='Фото коллекции телескопа Habble',
                       default='spacecraft')
  args = parser.parse_args()
  print(args.dir, args.space, args.habble, args.collection)

  bot = Bot()
  USERNAME = os.getenv('LOGIN')
  PASSWORD = os.getenv('PASSWORD')
  bot.login(username=USERNAME, password=PASSWORD)

  images_dir = set_path(args.dir)

  if args.space:
    fetch_spacex_last_launch(images_dir)

  hubble_collections = ['holiday_cards',
                        'wallpaper',
                        'spacecraft',
                        'news',
                        'printshop',
                        'stsci_gallery']
  if args.collection in hubble_collections:     
    hubble_collection: str = args.collection

  if args.habble:
    get_hubble_collection(hubble_collection, images_dir)

  resize_and_convert(images_dir)

  publish_in_insta(bot, images_dir)
Ejemplo n.º 10
0
def main():
    description = ('This program downloads photos of the last SpaceX rocket '
                   'launch and from the collection "spacecraft" '
                   '(you can chose your collection)')
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('login')
    parser.add_argument('password')
    args = parser.parse_args()
    login = args.login
    password = args.password

    fetch_spacex_last_launch()
    get_images_id_collections('spacecraft')
    myfiles = os.listdir('images')
    bot = Bot()
    bot.login(username=login, password=password)

    for image in myfiles:
        if image != '.DS_Store':
            bot.upload_photo(f'images/{image}')
Ejemplo n.º 11
0
def main():
    urls_spacex_images = fetch_spacex_last_launch()
    count_spacex_images = len(urls_spacex_images)
    for index, img_url in enumerate(urls_spacex_images, start=1):
        print(f'Скачивается фото с Spacex - {index}/{count_spacex_images}')
        download_image(f'spacex{index}', img_url)
    urls_huble_images = list(fetch_huble_collection())
    count_huble_images = len(urls_huble_images)
    for index, img_url in enumerate(urls_huble_images, start=1):
        print(f'Скачивается фото с Huble - {index}/{count_huble_images}')
        download_image(f'huble{index}', img_url)
    print('Публикуем сохранённые фотографии в Инстаграм')
    publish_on_instagram(fetch_save_images())
Ejemplo n.º 12
0
def main():

    current_directory = os.path.dirname(__file__)
    logfile = os.path.join(current_directory, 'autoposting.log')
    logging.basicConfig(filename=logfile, filemode='w')
    logging.info("Program started")

    try:
        fetch_spacex.fetch_spacex_last_launch()
    except requests.exceptions.HTTPError as error:
        logging.info(
            "Не могу получить данные с сервера Space X:\n{0}".format(error))

    try:
        fetch_hubble.fetch_hubble_images()
    except requests.exceptions.HTTPError as error:
        logging.info(
            "Не могу получить данные с сервера habble:\n{0}".format(error))

    posting_images.posting_images()

    logging.info("Done!")
Ejemplo n.º 13
0
def main():
    images_path = 'Images/'
    os.makedirs(images_path, exist_ok=True)
    try:
        fetch_spacex.fetch_spacex_last_launch(images_path)
    except requests.exceptions.HTTPError:
        print(
            'Неправильный запрос, фотографии с сайта spacex не будут загружены'
        )
    try:
        fetch_hubble.fetch_hubble_collections(images_path)
    except requests.exceptions.HTTPError:
        print(
            'Неправильный запрос, фотографии с сайта hubble не будут загружены'
        )
    load_dotenv()
    LOGIN = os.getenv('LOGIN_INSTAGRAM')
    PASSWORD = os.getenv('PASSWORD_INSTAGRAM')
    bot = Bot()
    bot.login(username=LOGIN, password=PASSWORD)
    pics = os.listdir(images_path)
    pics = sorted(pics)
    for pic in pics:
        try:
            print(f'upload: {images_path}{pic}')
            bot.upload_photo(f'{images_path}{pic}')
            if bot.api.last_response.status_code != 200:
                print(bot.api.last_response)
        except requests.exceptions.HTTPError:
            print('Instagram не работает')
        finally:
            try:
                os.remove(f'{images_path}{pic}.REMOVE_ME')
            except FileNotFoundError:
                for file in os.listdir(images_path):
                    os.remove(os.path.join(images_path, file))
Ejemplo n.º 14
0
    mypics = listdir(pic_dir)
    mypics.sort()
    for mypic in mypics:
        full_path_img = './{}/{}'.format(pic_dir, mypic)
        if full_path_img in posted_pic_list:
            continue
        bot.upload_photo(full_path_img, caption=mypic)
        posted_pic_list.append(full_path_img)
        with open('pics.txt', 'a', encoding='utf8') as f:
            f.write(full_path_img + "\n")


def clear_img_dir(pic_dir):
    remove_files = glob.glob('./{}/*CONVERTED*'.format(pic_dir))
    for remove_file in remove_files:
        os.remove(remove_file)


if __name__ == '__main__':

    pic_dir = 'images'
    fetch_spacex_last_launch(pic_dir)
    collection = 'printshop'
    get_hubble_image_id(collection, pic_dir)

    load_dotenv()
    login = os.getenv("INSTA_LOGIN")
    password = os.getenv("INSTA_PASS")
    upload_to_instagram(login, password, pic_dir)
    clear_img_dir(pic_dir)
def main():
    fetch_spacex_last_launch(SPACEX_URL)
    download_hubble_collections(IMAGE_COLLECTION, IMAGE_DIRECTORY)
    use_pillow_for_image_resize(IMAGE_DIRECTORY, PROCESSED_IMAGES)
    insta_bot(PROCESSED_IMAGES)
Ejemplo n.º 16
0
def main():

    # init

    logging.basicConfig(format = u'[LINE:%(lineno)d]#  %(message)s', level = logging.DEBUG)

    load_dotenv()
    insta_login = os.getenv("INSTA_LOGIN")
    insta_password = os.getenv("INSTA_PASSWORD")


    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    img_dir = joinpath(BASE_DIR, 'images')

    parser = argparse.ArgumentParser(
        description='Программа автоматизирует сбор фотографий космоса и публикует их в соцсеть Instagram.'
        )

    parser.add_argument(
        '-t', 
        '--timeout', 
        type=int, 
        default=2, 
        help='задержка между публикациями изображений в Instagram (по умолчанию 2 часа)'
    )
    parser.add_argument(
        '-c', 
        '--collections', 
        nargs='*', 
        default='wallpaper', 
        help='введите имена коллекций Hubble (holiday_cards wallpaper spacecraft news printshop stsci_gallery)'
    )

    args = parser.parse_args()

    timeout = 60 * 60 * args.timeout
    hubble_collection_names = [args.collections]


    bot = Bot()
    bot.login(username=insta_login, password=insta_password)


    # do

    try:
        fetch_spacex_last_launch(img_dir)

        for collection_name in hubble_collection_names:
            hubble_collection = fetch_hubble_collection(collection_name)

            for image in hubble_collection:
                hubble_url = image['url']
                hubble_filename = 'hubble-{id}'.format(id=image['id'])

                download_picture(hubble_url, img_dir, hubble_filename)

    except HTTPError:
        logging.error('HTTPError: Not Found', exc_info=True)


    for image in os.listdir(img_dir):
        if isfile(joinpath(img_dir, image)):
            try:
                resize_image(img_dir, image)
            except FileNotFoundError:
                logging.error('Error: file or dirrectory not found', exc_info=True)
            else:
                path = joinpath(img_dir, image)
                os.remove(path)


    for image in os.listdir(img_dir):
        if isfile(joinpath(img_dir, image)):
            try:
                os.chdir(img_dir)
                bot.upload_photo(image)
            except FileNotFoundError:
                logging.error('Error: file or dirrectory not found', exc_info=True)


    time.sleep(timeout)
Ejemplo n.º 17
0
    bot = Bot()
    bot.login(username=login, password=password)
    timeout = 30
    posted_pic_list = get_posted_pics()
    pics = glob.glob(folder_path + "/*.*")
    for pic in pics:
        bot.upload_photo(pic)
        if bot.api.last_response.status_code != 200:
            break
        if pic not in posted_pic_list:
            posted_pic_list.append(pic)
            with open("pics.txt", "a", encoding="utf8") as f:
                f.write(pic + "\n")
        sleep(timeout)


if __name__ == "__main__":
    parser = configargparse.ArgParser(description='instagram pic uploader',
                                      default_config_files=['.env'])
    parser.add("--login", help="instagram login")
    parser.add("--password", help="instagram password")
    parser.add("--directory", help="directory with images")
    args = parser.parse_args()
    login, password, directory = args.login, args.password, args.directory
    if not os.path.exists(directory):
        fetched_images = fetch_spacex_last_launch()
        fetched_images += fetch_hubble_urls()
        save_images(fetched_images, directory)
        crop_files_in_folder(directory)
    upload_pics(login, password, "./{directory}/cropped")
Ejemplo n.º 18
0
import os
import pathlib
import fetch_hubble
import fetch_spacex
import insta

files_directory = "images/"
os.makedirs(directory, exist_ok=True)

url = 'https://api.spacexdata.com/v3/launches/latest'
fetch_spacex.fetch_spacex_last_launch(url, files_directory)

url = 'http://hubblesite.org/api/v3/image/{}'
fetch_hubble.fetch_hubble_images(url, files_directory, 1)

insta.create_insta_post()
Ejemplo n.º 19
0
from fetch_spacex import fetch_spacex_last_launch
from fetch_hubble import fetch_hubble_collection
from transfer_image import upload_images_to_instagram

if __name__ == '__main__':
    print('Download images from spacex')
    fetch_spacex_last_launch()

    print('Download images from hubble')
    collection_name = 'spacecraft'
    fetch_hubble_collection()

    print('Upload images to instagram')
    upload_images_to_instagram()
Ejemplo n.º 20
0
                        '--spacex',
                        action='store_true',
                        help='Need to download last Space X launch')
    arguments = parser.parse_args()
    return arguments


if __name__ == '__main__':
    args = parse_arguments()
    load_dotenv()
    insta_login = getenv('LOGIN')
    insta_password = getenv('PASSWORD')
    directory_for_images = args.directory
    try:
        if args.spacex:
            space_x_last_images = fetch_spacex_last_launch()
            print('Start downloading last Space X launch photos')
            download_collection(space_x_last_images, directory_for_images,
                                'space_X')

        if args.collection:
            collection = args.collection
            hubble_collection = get_hubble_image_collection(collection)
            print(f'Start downloading {collection} photos from Hubble')
            download_collection(hubble_collection, directory_for_images,
                                'from_hubble')

        if args.upload:
            print(
                f'Start uploading images from {directory_for_images} to Instagram {insta_login}'
            )