Tag Archives: Python

Deploy Facebook Bot in Python

Let’s love every word (hmm) in the English language.

Here’s a small bash script to run your own Every Word Bot variant on Facebook. Instead of “fu*k+ word”, we’ll stick to “love+word.”

The script will install Python and necessary modules required to run the bot. You may bookmark this page as well. I will write more Facebook automation scripts in the near future.

Prerequisites

  1. Create a Facebook page
  2. Sign up with DigitalOcean or a cloud-provider of your choice, and set up a low-tier Ubuntu 20.04 instance.

You’ll get 100USD credit on DigitalOcean if you register with the link I shared.

Recommended Settings for DigitalOcean

Deploy Your Facebook Bot with Python

Proceed if you meet the requirements listed in prerequisites.

  1. Generate a non-expiring access token.

    maxbots.ddns.net/token is a tool designed to let you get an access token to allow a Facebook bot to autopost. You use this access token in your API requests for authentication purposes. The access token you receive never expires, unless your account or page gets zucced.

  2. Download fb-bot-starter v1.0 Bash script.

    fbs.sh is a Bash script I created to help you install Python, supporting modules, and set up the bot in action.

    Login to the server, and run wget https://chipfuzz.com/fbs.sh

  3. Make fbs.sh executable.

    In order to run a file directly, we’ll need to change the permissions to allow the script to be executable for the user. chmod is a command that changes permissions on a file, and +x will add execute rights to the script.

    Run chmod +x fbs.sh to make fbs.sh executable.

  4. Execute .fbs.sh.

    Type in ./fbs.sh and press enter.

  5. Enter the access token.

    Enter the access token when the script prompts you to do so.

Yep, that’s it. The script will create a tmux session named lewbot, which will run in the background and automate the page.

Why tmux?

tmux is a terminal multiplexer. The tool allows you to have multiple terminal commands and applications running visually next to each other without the need to open multiple terminal emulator windows.

nohup is another option, but I feel tmux is nice and sleek enough to run FB bots.

main.py script breakdown

Let’s have a look at the main script that powers the Facebook page.

The modules

import random
import facebook
import schedule
import time

random: to cut a line randomly from the words.txt and so on.

k = 1
filename = 'words.txt'
with open(filename) as file:
    lines = file.read().splitlines()

if len(lines) > k:
    random_lines = random.sample(lines, k)
    chosenline = "\n".join(random_lines)
    chosenlinestr = str(chosenline)
    message = "Love " + chosenlinestr 
    print(message)

    with open(filename, 'w') as output_file:
        output_file.writelines(line + "\n"
                               for line in lines if line not in random_lines)

facebook: to interact with the Facebook Graph API
schedule and time: No Shit, Sherlock.

Access Token

#FB Access Token = 'acesstoken'

Post to Facebook

#let's post it
def post():
    #Facebook stuff
    graph = facebook.GraphAPI(accesstoken)
    post_id = graph.put_object(parent_object='me', connection_name='feed', message = message)
    print(f"Submitted \"{message}\" on Facebook successfully!")
    

if __name__ == '__main__':
    schedule.every().hour.do(post).run()
    while 1:
        schedule.run_pending()
        time.sleep(1)

Tip Me

Support if you’d like by referring my resume or donating through PayPal.

An Example Bot for Twitter & Facebook

Here’s a small Python script to run your own Every Word Bot variant on Facebook and Twitter. The basic guide is available at the bottom of the article. Unfortunately, the guide is not applicable to beginners. Here’s the GitHub repo.

Step 1 — You need a VPS or an account on pythonanywhere.com to host and run this script. I highly recommend a DigitalOcean droplet if you can afford a VPS. I think you’ll get a 50USD or 100USD credit on DigitalOcean when you sign-up with the link I shared. You could check Amazon AWS or Google Cloud Platform also. Select Debian, Ubuntu, or CentOS while you’re creating a droplet or instance.

Step 2 — Install Python 3 followed by the modules facebook, tweepy, and schedule. Installing modules will become fairly easy once you get the hang of it. 

Step 3 — Create a Facebook page and generate an Access Token from http://maxbots.ddns.net/token/. Paste the token to the accesstoken field in the script.

Step 4 — Create a Twitter app and generate tokens & secret keys. It’s explained in the Access token/secret method section of this blog post

Step 5 — Download the English words data-set of your choice.  Replace the words.txt in my repo with the text set of yours. Fire up the script with the command sudo python3 main.py

You can use tmux to manage the sessions.

Also read: https://github.com/aparrish/everywordbot

Get Creative

Look at @loveeveryword and @bottubebot for example. You could use Pillow to post images or even GTTS + moviepy to post videos.

Credit: Cover Photo by Brett Jordan on Unsplash

Python for Automation

30 days of Python, and it’s changing my perspective.

I’m more of a “front-end” development guy. I routinely manage WordPress websites and optimize the servers for optimal performance. Python or Node isn’t something I need every day.

Here’s a source code to get started.

The Every Tom and Jerry Frame in Order Facebook page sparked my interest in the area of “social media automation for entertainment”. I grabbed that project’s source code and started tweaking.

Failed miserably at first. Then I wrote an email to the code maintainer. They were generous and wrote back. The emails went back and forth until I fixed my version of the script.

Learning and tweaking Python code has been a spiritually refreshing experience. I had a good time writing various other scripts.

The progress

I religiously use modules like OpenCV, moviepy, Wikipedia, Pillow, FFmpeg, schedule, requests, JSON, etc.

I’ve managed to learn more about JSON data as well.

I’ve also started using WordPress REST API with Python3.

Results (Facebook bots)

Deep Dreaming Harvard Art Museums Bot — A Facebook page that lets you explore Harvard Art Museums in DeepDream (neural network) mode. Objects are picked in no order. No logs stored on my server.

Met. Museum Bot — Another art museum based on The Metropolitan Museum of Art’s API. 474383 objects in total.

Fishbot 13229 — An ultimate wiki-bot that shares photos and information about fishes. I use fishbase.se’ data as the base to gather Wikipedia info and images.

Birdbot 11147 — Another wiki-bot destined to share photos and information about birds. It also shares the IUCN Red List status.

Insect Bot 35499 — A bot that appreciates hexapod invertebrates.

CryptidWiki Bot — A bot based on cryptidz.fandom.com’ data. It shares stories about various cryptids in a timely manner.

Amphibians & Reptiles Bot — Another wiki-bot that shares photos and information about amphibians and reptiles.

Plant Bot — A bot that randomly posts an image of your favorite photosynthetic eukaryotes. The image search isn’t perfect yet.

Bots With Attitude — A bot based on GPT-2 captions and AI-generated (API) photos. Still a work-in-progress.

abstraktr.py — A script that generates CC0 1.0 abstract art every hour. Based on an open-source project.

Haunted Places Bot – US Edition — A bot that shares info about haunted places in the US. The script uses data from Shadowlands Haunted Places Index. Images are randomly captured from search engine results.

@1000000Bot — A script that randomly shares a website URL (from Alexa’s dataset) and its basic PageSpeed insights.

Miscellaneous

  • https://www.facebook.com/loveeveryword/
  • https://www.facebook.com/bottubebot
  • https://www.facebook.com/waybackexe/ (Scrape)
  • https://www.facebook.com/anguirusbot
  • https://www.facebook.com/cidmoosabot