Project, Python, Research

Automating Making Memes & Instagram Posts 7: Automating The Cat Geek Posts

Originally I was going to train a neural network to “talk” like a cat and have that create captions for my The Cat Geek Instagram account. I decided to hold off using the neural networks for now, and instead use the famous quote JSON file I downloaded in my previous post Automating Making Memes & Instagram Posts 3: Improving the Script.

Instead of using the quotes as-is, I ran them through this handy lolcat translator to turn them into a cat’s version of “saying” famous quotes. So now I can use these as the Instagram captions to go along with a randomly chosen cat photo from my external harddrive that is attached to my raspberry pi server.

And soon I will take over the world!!!!

I’ll spend more time in the future on populating the pictures folder, so for now I’ll just get my auto-poster script functioning.

To start my script, I need to copy and paste an image into my active directory, and then move the original to a folder so it is not accidentally used again in the future.

import os
photo_path = '/home/pi/.virtualenvs/etc/photo.jpg' #change to be whatever the filepath is to the meme folder where the meme will be stored
directory = '/media/pi/etc/The Cat Geek'
src=''
for filename in os.listdir(directory):
        if filename.endswith('.JPG'):
            if src=='':
                src = directory + "/" + filename
                dst = directory + "/Used"
#copy and paste image to alter and upload
from shutil import copyfile
from shutil import move
if src <> '':
    copyfile(src, photo_path)
    move(src,dst)
Way too many words in this post, here’s a puppy break

To make an Instagram caption, I read the first line from the lolquote text file I made, and then added the hashtags to the end of the string.

#make IG caption
f = open("/home/pi/.virtualenvs/etc/lolquotes.txt")
lolquote = str(f.readline())
hashtags = " #MadamCrookshanks #TheCatGeek"
caption = lolquote + hashtags

Now that I’ve selected and edited the photo and made the caption, I just need to run the InstagramAPI code to post.

from InstagramAPI import InstagramAPI
InstagramAPI = InstagramAPI("aadsfsafd", "asfasdfasdf")
InstagramAPI.login()  # login
InstagramAPI.uploadPhoto(photo_path, caption=caption)

Unfortunately, my photo failed to post since it is somehow not compliant with Instagram’s requirements. To allow the program to edit the picture automatically, I need to install the original Instagram-API that was written in PHP. That way I can use the code that automatically formats the photo so it will post successfully.

Rewriting code multiple times is kind of what programming is all about….

In order to install it, I tried to follow the Wiki on github, but the command to install didn’t work. I Googled and found a thread with several suggestions, and eventually figured out that I needed to install composer so I could use it to install the Instagram-API. Below are the commands that I used to finally get PHP and the composer installed on my Raspbian OS raspberry pi.

sudo apt-get install php7.0 
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
php composer.phar require mgp25/instagram-php

Aaaaaaaaaand I am almost positive I crashed my raspberry pi from trying to use the composer. >.< FML

uuuuggggghhhhh

Three hours later, I was finally able to connect to my rpi, but discovered that the installation failed.

wtf does this even mean?

So from what I gather, my little bitty raspberry pi ran out of memory to properly complete the installation. One possible solution is to increase something called the “swap file” that allows part of the harddrive act as virtual memory. Fortunately, it was a simple procedure to increase on a raspberry pi.

sudo dphys-swapfile swapoff
sudo nano /etc/dphys-swapfile
##edit CONF_SWAPSIZE=1024 and Ctrl+X to save/close changes##
sudo dphys-swapfile swapon
sudo reboot #for changes to take effect
free -h #lists memory to ensure changes took effect
php composer.phar require mgp25/instagram-php

This time I ran into the same dependency errors that I came across in my post Automating Making Memes & Instagram Posts 2: Instagram-API-Python.

sudo apt-get install php-curl 
sudo apt-get install php-gd
sudo apt-get install php-mbstring
sudo apt-get install php-bcmath
php composer.phar require mgp25/instagram-php

And it finally worked!

YAASSSS

It also gave suggestions to install other things, but I couldn’t figure it out, so I decided to just keep pressing on.

???

In order to use the Instagram-API, I located the “uploadPhoto.php” script from the “/home/pi/vendor/mgp25/instagram-php/examples” folder and modified it with my username, password, and photo location. But when I ran the script, I got an error stating it could not find the “autoload.php” file. So I manually found the autoload.php file and edited line 6 of the uploadPhoto.php script to reference its location directly.

require __DIR__.'/../vendor/autoload.php'; #ORIGINAL
require '/home/pi/vendor/autoload.php'; #NEW

The script executed successfully, so all that is left to do is combine my python script above with the new php script. To do this, I’m going to use the python script to move the photo and create the caption, and then I’ll call the php script and pass the caption as variable.

Sounds easy, right?

After failing to get it to work after an hour , I decided to switch gears and move the caption generation into the PHP script. Then I’d call the python script from PHP to move an image and there’d be no need to pass variables at all.

$file = '/home/pi/.virtualenvs/etc/quotes.txt';
$hashtags = ' #MadamCrookshanks #TheCatGeek';
$line = fgets(fopen($file, 'r'));
$captionText = $line.$hashtags;
exec('python /home/pi/.virtualenvs/etc/scriptname.py');

My final task was to remove the used caption from the quote text file, and save it in a “used quotes” file. This seemed easy, and it really is, but there are multiple ways to do it (python, php, bash). Ultimately, I ended up adding this to my PHP script and setting variables to repurpose this for my other social media accounts.

$line = fgets(fopen($file, 'r'));
$hashtagline = fgets(fopen($hashtags, 'r'));
$captionText = $line.' '.$hashtagline;
$newfile = file($file);
unset($newfile[0]);
file_put_contents($file, $newfile);
file_put_contents($usedfile, $line, FILE_APPEND | LOCK_EX);

Now that everything is working, I just need to hook it up to The Cat Geek Instagram, set it on a schedule to run, and populate my picture folder. I have 2 factor verification on my IG account, so I replaced the login PHP script with the two-factor Instagram-API code. And in order to choose when to schedule my posts I consulted the help of the internet.

Well that was a freebie
crontab -e
#0 9,15 * * * php "/pathtoscript/scriptname.php" >> /home/pi/cronlog.txt

And with that, my Instagram is officially in the hands (paws?) of my kitties!

I may revisit this project to turn the kitties into memes, but for now I’m going to move on to automating a few other social media accounts. Including a new project that is very personal to me…….but more on that later. For now, I’m going to enjoy my victory!

Leave a Reply