How to make a Bot that automatically responds to comments on Facebook

●5 MIN READ

How to make a Bot that automatically responds to comments on Facebook

A week ago, a Belgian telecom company created this awesome post on Facebook.

Screen-Shot-2018-01-03-at-23.35.28

(“Stout” means “bad” in Dutch)

You had to tag a friend in the comments and the page would automatically respond with an image showing the profile picture of that friend, plus a note of ‘Sinterklaas’ (a Santa Claus-like figure roaming Belgium and the Netherlands in early December) judging your behaviour of the past year.

My meme-loving sister tagged me and apparently I’ve been bad in the past year. Sad!

Lots of people thought there was someone making these images by hand, but I knew better. At the time of writing, the post has over 8200 comments. No way those 4100 pictures were made by hand.

After looking around I found out that Inti De Ceukelaire created such a thing before and has written about it here. I’m a sucker for these things and wanted to find out exactly how difficult it was to make myself.

About 200 lines of python later, I pulled it off. Behold the Facebook Autoreplier bot in action.

Update: As there was some interest from marketers to use this for their brands, I decided to offer the autoresponder as a service. For more info, check the autoresponder info page!

ogp-cover-3

I’ve released the code under the MIT license on Github for you to play around with. You’ll need some knowledge of python to create different images and change the copy, but overall the process pretty straightforward.

So let’s get started and create your own Facebook Autoreplier bot!

What you need

You’ll need to install Python3 and all the requirements that are in the requirements.txt file inside the Github repo.

Facebook-wise you’ll need:

  • A Facebook page, duh.
  • A Facebook app in the Facebook Developer Portal
  • A page access token (normally this expires after a few hours, I think? We will create an access token that lasts 60 days)

Getting the long-lived Facebook access token

If you don’t have a page yet, start by making a Facebook page here.

Then head over to the Facebook Developer Portal, click on My Apps in the top right and Add a New App. You can give it any name you want, other people won’t see it anyway. Same goes for the contact email.

Screen-Shot-2018-01-03-at-23.45.49

We need to do two things here: copy the API credentials and make sure our app can post comments on our Facebook page.

To get the API credentials, click on the top-left dashboard. There you’ll see the App Id and the App Secret. Copy-paste these into a working environment, a simple text editor will do.

To allow our app to post comments, click on App Review in the side menu. Make sure you keep your app in development! Start a submission, then select both the manage pages and publish pages permission.

Next, let’s get you an access token! To do this, go to the Facebook Open Graph Explorer. Make sure you select the application you just created. In my case it’s called “test13”.

accesstoken-1024x239

Then click on Get Token and make sure you select Get Page Access Token. Open it up again, and select the page you want to comment on. In my case I took the page with the name “Quehue”. Then click on the bottom one again and see if “Allow to post as page” appeared. If it did, click it, if it didn’t, it ’s fine. To check if everything works, click submit and you should see the ID and name of the page appear.

Copy the access token and add it to the document where you just pasted your App ID and App Secret. Now, this access token is a short-lived one. We are going to get a long-lived, just because I’m too lazy to constantly refresh it.

Go to this URL, but change the APP_ID, APP_SECRET and EXISTING_ACCESS_TOKEN in your own ID, secret and token :

https://graph.facebook.com/oauth/accesstoken?clientid=APPID&
clientsecret=APPSECRET&
granttype=fbexchangetoken&
fbexchangetoken=EXISTINGACCESSTOKEN

You’ll get some code back, including the long-lived access token.

That’s it, we’re now ready to dive in to the code!

Monitor the comments

Clone or download the code from Github and open the autoresponder.py file. Here we’ll have to fill in which Facebook post it should monitor as well as the access token.

Head over to Facebook, create a new post with your page and copy both the Page ID and the Story/Post ID into autoresponder.py. To get those IDs, click on the timestamp of your post. If you just created it, it will be “just now”. In my case, I created it 2 hours ago. Then you will see the story_fbid parameter in the URL. This is the Post ID. The id param behind it is the Page ID.

fbpostid

Now you’ll be able to run autoresponder.py and it will monitor that particular Facebook post. Every time a new comment is posted (or if there’s an existing comment that is not yet in the comments.sqlite3 database), it will reply to that comment with a custom image.

Making the custom image

In the make_new_profile_pic method, a new image is created and returned. If you want to customize it (change the size of the profile picture, add some text etc.) you will need some knowledge of python3 and pillow/PIL to change the code.

If you just want to try it out, you can save your own “overlay picture” in the folder, change the background/foreground image path to yours and it should work. The image is resized to 480x480 pixels, but you can change that – the bigger the picture, the slower it is.

In the background version it uses the image fcdk_overlay.png as the background image and pastes the profile picture on top of this, located 100px from the top and 100px from the left. When you open fcdk_overlay.png you will see it has a white border of exactly 100px wide.

In the foreground version the tgr_overlay.png picture is pasted on top of the profile picture. This is a great way to make custom profile pictures for your Facebook fans!

Conclusion

The amount of comments some of these posts have is staggering! If you’re smart, you can reach tons of people. Especially if you let people tag other people.

If you need more inspiration, here are some other automatic responders:

(This bot gave you a personalized metal avatar) (This bot offends you. There's a whole backstory about a Dutch rapper) (This bot will suggest New Year resolutions, like "get new friends")

More polaroids I want to share

CLICK OR DRAG THE TOP ONE ASIDE

You've reached the end of the shoebox. More polaroids and other posts live on my Instagram.

@GMJELLE →
Polaroid of a calm lake at dusk reflecting pink clouds and dark hills, at a wild campsite near Adana, Turkey
Polaroid of Josip Broz Tito's marble tomb seen through plant leaves in Belgrade, Serbia
Polaroid of a motorcycle parked at a Soviet-era bus stop decorated with a flower mosaic in Moldova
Polaroid of a large stone statue of a bearded man in a long coat on a hillside near Buzludzha, Bulgaria
Polaroid of the saucer-shaped Buzludzha Monument on a distant hilltop above the trees in Bulgaria
Polaroid of a man standing in front of the Buzludzha Monument and its tower in Bulgaria
Polaroid of a valley of pale, cone-shaped rock formations in Cappadocia, Turkey
Polaroid of hot air balloons silhouetted against the dawn sky in Cappadocia, Turkey
Polaroid of the brutalist Cosmos Hotel tower in Chisinau, Moldova
Polaroid of the Tomb of Cyrus the Great on its stepped stone base at Pasargadae, Iran
Polaroid of a close view of the Tomb of Cyrus the Great at Pasargadae, Iran
Polaroid of a converted red fire truck camper and a motorcycle at a campsite on the west coast of Turkey
Polaroid of a mosque minaret and domes silhouetted against a cloudy sky in Edirne, Turkey
Polaroid of the Mimar Sinan statue in front of the Selimiye Mosque in Edirne, Turkey
Polaroid of the courtyard of a historic house with a fountain and colored-glass windows in Isfahan, Iran
Polaroid of a man standing next to an Isfahan city emblem sign on a sidewalk in Isfahan, Iran
Polaroid of the tiled dome and entrance portal of the Sheikh Lotfollah Mosque in Isfahan, Iran
Polaroid of the tiled entrance portal and twin minarets of the Shah Mosque in Isfahan, Iran
Polaroid of a columned palace silhouetted at sunset behind a fountain pool on Naqsh-e Jahan Square, Isfahan, Iran
Polaroid of a dark interior lit through colorful stained-glass windows in a historic house in Isfahan, Iran
Polaroid of rocky ridges and rock formations under a cloudy sky near Goreme, Cappadocia, Turkey
Polaroid of a loaded motorcycle parked by a desert road with mountains behind it in Iran
Polaroid of a loaded motorcycle with a helmet on the mirror, parked on a coastal road near Izmir, Turkey
Polaroid of a Soviet-era mosaic of workers and a motorcyclist on a building wall in Lutsk, Ukraine
Polaroid of a Soviet-era mosaic of a crowned woman holding scales, framed by tree leaves in Lviv, Ukraine
Polaroid of the Lviv Opera House facade with a fountain in front in Lviv, Ukraine
Polaroid of a Soviet WWII memorial column with a stork's nest on top in northern Moldova
Polaroid of a large Soviet-era mural of figures on a wall beside a tree in Moldova
Polaroid of royal tombs carved into the cliff face at Naqsh-e Rustam near Persepolis, Iran
Polaroid of a stone relief of a Persian soldier holding a spear at Persepolis, Iran
Polaroid of the Gate of All Nations with its winged bull statues and columns at Persepolis, Iran
Polaroid of four men sharing dinner at a table in a traditional hostel in Shiraz, Iran
Polaroid of the tiled courtyard and reflecting pool of the Nasir al-Mulk (Pink) Mosque in Shiraz, Iran
Polaroid of two men smiling at a restaurant table in Tabriz, Iran
Polaroid of the mirrored hall of Golestan Palace lit by large chandeliers in Tehran, Iran
Polaroid of the bronze statue of Leonidas raising a spear at the Thermopylae monument, Greece
Polaroid of a man looking up at the wooden Trojan Horse from the Troy film in Canakkale, Turkey
Polaroid of a backgammon board on a table overlooking the sea at a campsite in Turkey
Polaroid of a Soviet-era mosaic of a woman in traditional dress under a Ukrainian coat of arms in Ukraine
Polaroid of a motorcycle parked at a bus stop with a mosaic of three knights in Ukraine
Polaroid of a man standing on a boardwalk in front of the stairway of the Ziggurat of Ur, Iraq
Polaroid looking up the brick stairway of the Ziggurat of Ur, Iraq
Polaroid of eroded mud-brick ruins with a small sign in front at Uruk, Iraq
Polaroid of a man and two boys crouching by a freshly slaughtered sheep on grass on the road to Van, Turkey
Polaroid looking up at the curved glass Zlota 44 skyscraper in Warsaw, Poland
Polaroid of the Palace of Culture and Science lit at dusk in Warsaw, Poland
Polaroid of the Zoroastrian Fire Temple with a round reflecting pool in Yazd, Iran