Tutorial: a Facebook Bot for beginners

WARNING!: the usage of this bot could lead to a Facebook profile permanent banning and end up in the Facebook Jail. Only use this tutorial for learning purposes, and never try to use it for spamming or web scrapping with your real account or any other account.

Photo by Alex Knight on Unsplash

Before starting my learning programming journey, I remember thinking about bots as taboos or a tool that only advanced programmers could create. It was only a matter of time before I realized that creating a bot is a straightforward task, and even non-programmers could develop it. I’m writing this article for all those persons who, as I used, think this is a task only for advanced programmers.

First of all, I would like to clear out our bot’s purpose:

> Automate the process of writing posts in Facebook groups.

Let’s put our hands to work.

- Step 1: Installing Ruby

Before starting our attempt to write code, we have to install our language. In this case, as we have said, we are going to use Ruby. Installing it is a pretty easy-to-follow task, but make sure you follow each step carefully and copy and paste every command line to prevent typos.

If you are already using Mac-OS or Linux, you can go directly to install Ruby from your terminal (description) by just following the link marked below.

Mac-Os/Ubuntu/Xubuntu/WSL: click on this link and select the small arrow to the left of the Operating System you are using. Follow the proper tutorial step by step, and make sure you don’t miss any point.

Windows:

Ruby on Windows 10 Tutorial

Ruby has a straightforward syntax; therefore, it’s a good option for this tutorial and complex enough on its features to let us develop more applications in the future.

- Step 2: Installing a Text Editor

As you might know, code is text ordered in a way the computer can understand it, and the way you arrange your code (syntax) is going to depend on the programming language you are using. However, the text editors we use commonly like Microsoft Word and Libre-Office-Writer are great for writing documents, but these won’t be useful for writing code. We need a completely different set of features in our editors such as plugins, syntax highlighting, auto-closing of brackets and braces, and linting. At this step, we are going to install an excellent free code editor VSCode (Visual Studio Code).

  • You can download it from here. (VSCode)

Now that you have Ruby and VSCode installed, we are going to proceed.

  • Create a folder anywhere within your system (location and name is your choice) where you’d like to save your bot files. In this tutorial, I’m going to name my folder as ‘Facebook-Bot’.
  • Open VSCode and access your folder: File > Open Folder > -Select your folder- > OK.
    As your folder is empty, you won’t see anything in your VSCode UI but the folder’s name.
Your folder’s name is on the left side of the screen.
  • Create your first Ruby file: File > New File > Ctrl-S [Mac: Cmd-S] > Save.
    Name your file as you want, but the .rb extension is important. In this tutorial, I’m going to name my file as bot.rb.
Save your bot.rb file
Save your bot.rb file
Saving my file as bot.rb (the .rb extension is important)

After saving your file, you can see a Ruby icon on the left side of your screen. It means you can start developing Ruby code.

File extension check .rb with the icon

It’s time to start programming, so let’s give some room to our next step.

- Step 3: using Ruby gems to access Facebook

  • Mozilla Firefox
    At this step, we are going to use the Firefox web browser. If you haven't installed it yet, you can access this link and follow the instructions.
  • What’s a gem?
    In general terms, a gem is a collection of Ruby methods and functionalities that we can extract into a base code.

We have to divide our bot’s general functionality (write posts on Facebook) mentioned above into smaller and simpler tasks: (functions). Therefore, our first small task to complete is to open our web browser and access the Facebook login page. To achieve this, we use a Ruby gem: Selenium-Webdriver.

- Selenium Webdriver gem
Selenium WebDriver tool is used to automate web application testing to verify that it works as expected. It supports many browsers such as Firefox, Chrome, IE, and Safari.

In other words, this gem is the key to automate navigation on the internet.

  • Open the terminal in your VSCode UI
    Follow this path in your VSCode UI: Terminal > New Terminal. You will see a new terminal displayed at the bottom of your screen.
Terminal displayed at the bottom of the screen.
  • Installing Selenium-Webdriver gem
    -
    Copy and paste this command-line in your terminal and press Enter.
    Use Ctrl + Shift + V to paste the text into your terminal.
gem install selenium-webdriver
Command-line pasted into the terminal with the correct path.

Your file’s path is going to change depending on its location within your system. For sure, it is NOT going to be like mine: C:\Users\Usuario\Documents\GitHub\Facebook-Bot>
Make sure the path displayed in your terminal ends with the folder’s name where your bot file location. Otherwise, get back to the preview steps and open the right folder.

If everything runs well, you will get your gem installed with a terminal displayed like this.

Terminal after installing the selenium-webdriver gem.
  • Accessing to the Facebook login page.
    We have our gem up and running now, and its features ready to use. We can proceed to write code.
    In your bot.rb file, paste the next code and save changes.
require “selenium-webdriver”
driver = Selenium::WebDriver.for :firefox
url = ‘https://www.facebook.com/'
driver.get(url)

This code indicates your computer to use the gem and open the Facebook page in our Firefox browser.

Code saved in my ruby file.

It’s time to run our file and check if the gem and our code are working.

  • Copy and paste the next command-line into the terminal and press Enter
    Reminder: bot.rb is the name of my file. If you have saved it with a different name, make sure you use that name instead of bot.rb.
ruby bot.rb
Command-line to run the ruby file.

After pressing Enter on your keyboard, your computer is going to start processing the instructions you have given to it. It will open the Facebook page on your Firefox browser.

Facebook page after running our bot’s file.

If you get the same result, you have done a GOOD JOB!. So far, you’ve finished the most complicated part of this tutorial. From here, it’s just coding a couple of functions before having our bot done.

- Step 4: Facebook login

After having automatized the process of accessing Facebook, it’s time to teach our bot how to log in. For this subject, it’s better to understand a crucial term so you can use it for future projects.

  • Xpath: It is a syntax or language for finding any element on the web page using the XML path expression.

Why is Xpath important? Because your bot has to know which element of your webpage is going to apply events. E.g., when you want your bot to write your email and your password automatically, it has to know where’s the correct space to write on. The way the bot is going to find the element is by using Xpath.

How can you get the XPath of any element? The answer is straightforward:
1.- Right-click “inspect” on the item you are trying to find the XPath. E.g., an email field, a password field, a submit button.
2.- Right-click on the highlighted area on the console.
3.- Go to Copy XPath.

Copy Xpath of an element demonstration.
Xpath tutorial.

This term is essential to learn because famous websites tend to update their layout frequently, and at the time you are reading this tutorial, you could get problems finding the elements used in the next steps. Therefore, you might have to update the Xpath.

Once we have cleared this topic, we can start writing the code.

  • Copy and paste the next code in your bot file below the code previously written.
email = ‘yourname@email.com’
password = ‘yourpassword’
def login(email, password, driver)
email_element = driver.find_element(xpath: ‘//*[@id=”email”]’)
password_element = driver.find_element(xpath: ‘//*[@id=”pass”]’)
email_element.clear()
email_element.send_keys(email)
password_element.send_keys(password)
password_element.submit
sleep(5)
endlogin(email, password, driver)
  • Modify the first two lines of the code shown above with your real email and password inside the single-quotes. Save the file.
Facebook login code without real email and password.

Remember, you can test the code by running the command-line showed below. Use your terminal.

ruby bot.rb

Important: if you get errors as ‘unable to locate element’ in your terminal, it means that your Xpath is not updated, and your browser couldn’t find it. Don’t worry. You only have to copy the correct Xpath from your browser following the instructions marked at the beginning of this section and paste it into your code right after the ‘.find_element(XPath:…)’ text and inside the single-quotes.

Put the element Xpath inside the single-quotes, replacing its content.

At this moment, if you run your code, you will see that your bot now can access Facebook and log in to your Facebook account automatically. What would be the next step?

- Step 5: Access to Facebook groups

IMPORTANT: make sure you are already a member of every group you want the bot to post. Otherwise, your bot could not find any field to write on.

We can go through these steps very quickly. We only have to teach our bot to access every group where we want to post and write content for our posts.

  • We are going to create an array of links to the groups we want the bot to access. You can put all the links you want to access inside, but I will use three links just for this example.

Important: An array is defined inside square brackets => []. Each link inside your array should be separated by commas and should be inside single-quotes.

[‘https://www.facebook.com/groups/275366519230814’, ‘https://www.facebook.com/groups/rordevelopers’, ‘https://www.facebook.com/groups/javascript.morioh’]
  • Write your array of links below your password and set it equal to a variable named ‘groups’.
The array of links.
  • Copy and paste the next function below the ‘login’ function previously created.
def openGroups(groups, driver)
groups.each do | group |
driver.get(group)
sleep(3)
end
end
  • Copy and paste the next code line at the end of your file and save it.
openGroups(groups, driver)

Your code should look like:

OpenGroups function created.

You can check your code running the command-line ‘ruby bot.rb’ in your terminal. You will see that your bot automatically opens the web browser, logs in, and navigates through each of the links grouped into our array.

- Step 6: Publish a post on every Facebook group

  • We need to find the Xpath of the element where we want the bot to click in order to start writing on every group (a text field). At the moment I am writing this tutorial, the group's text field before click for posting looks like:
Facebook text field for posting in a group.
  • Set your Xpath element equal to a variable named ‘field’ inside the ‘OpenGroups’ function.
field = driver.find_element(xpath: ‘your element xpath here’)
Field Xpath inside the OpenGroups function.
  • After clicking the text field for posting in the browser, a modal will cover your screen. Find the Xpath of the post button we are going to need it inside the next function.
Get the Xpath of the post button.
  • We proceed to create our function to write text in the field and post it. Copy and paste the next function right below the ‘OpenGroups’ function, and make sure you use the correct Xpath for the post button.
    Important: If you get a long Xpath, don’t worry, it is just the absolute Xpath and will work as well.
def WriteAndPost(field, text, driver)
begin
field.click
sleep(3)
driver.action.send_keys(text).perform
sleep(2)
driver.find_element(xpath: ‘/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[2]/div[1]/div[1]’).click
rescue
sleep(2)
end
end
  • Add a text variable as an argument to your ‘OpenGroups’ function, and call the ‘WriteAndPost’ function inside. After all this work, you should have a code like this:
  • Finally, we are on our last step. We only have to indicate to our bot what to post. For this, we need to write a text inside single-quotes and set it equal to a variable named ‘text’ at the top of your code, below the groups variable.
text = ‘write the content of your posts here’
Text variable below groups.

We have done three essential functions to have our bot complying with its purpose. The first function (login) has the code to indicate to your bot how to login to Facebook. The second one (OpenGroups) has the code to teach your bot how to access all the groups you want and have placed inside the array. The third and the last function (WriteAndPost) has the code to teach your bot what to write and how to press the post button to publish your text.

I would recommend you to review the complete code line by line to have a better understanding of the functions and gem methods.

Congratulations!

You can run your bot now and see how it automatically posts on every Facebook group you have pasted inside the array!
It is the way a bot works. Of course, there are a lot more functionalities you can implement to your bot; however, with the topics we have reviewed in this tutorial, I bet you can build your bot to automatize an astonishing process on the internet.

  • Here you have the complete bot.rb file, so you can compare your code and make some changes if it’s required.

I leave my Github profile. Feel free to give your feedback and give me all the stars you want and a follow.

I'm a full-stack web developer and visual creator. I'm always trying to do my best at the things I'm passionate about. I love you all!