• About
  • Advertise
  • Privacy & Policy
  • Contact
Raspberry Pi Developing
  • Home
  • Getting Started
    Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

    Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

    All About Batteries

    All About Batteries

    What’s The Difference Between DC, Servo & Stepper Motors?

    What’s The Difference Between DC, Servo & Stepper Motors?

    Which OS is Best for Raspberry PI ?

    Which OS is Best for Raspberry PI ?

  • Pi Projects

    Raspberry Pi UV Sensor using the VEML6075

    Raspberry Pi Nvidia Shield: Stream Games using Moonlight

    Raspberry Pi Accelerometer using the ADXL345

    Raspberry Pi Accelerometer using the ADXL345

    Raspberry Pi Humidity Sensor using the DHT22

    Raspberry Pi Humidity Sensor using the DHT22

  • How to
    How to Install PHPMyAdmin on the Raspberry Pi

    How to Install PHPMyAdmin on the Raspberry Pi

    Setup a Raspberry Pi MYSQL Database

    Setup a Raspberry Pi MYSQL Database

    How to Upgrade Raspbian Stretch to Raspbian Buster

    How to Upgrade Raspbian Stretch to Raspbian Buster

    How to Setup Raspberry Pi RecalBox

    Play Retro Games with Raspberry Pi RetroPie

    Raspberry Pi DOSBox: Play Classic DOS Games on the Pi

    Trending Tags

    • Arduino Projects
      RS-485 Serial Communication between Raspberry Pi and Arduino Uno

      RS-485 Serial Communication between Raspberry Pi and Arduino Uno

      Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

      Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

      The 2019 Thermostat ReThink

      The 2019 Thermostat ReThink

      Tracked Arduino Robot

      Tracked Arduino Robot

    • News
      New report shows how IoT devices remain under ‘constant’ attack

      New report shows how IoT devices remain under ‘constant’ attack

      BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

      BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

      Raspberry Pi Comparison Table

      Raspberry Pi Kernel Updated to 4.19

      Apple Watch Series 2 Is Swimproof and Comes With Built-In GPS

      To regain advertiser trust, Facebook is tracking ads by the millisecond

      National Academy of Sciences endorses embryonic engineering

      Trending Tags

      No Result
      View All Result
      • Home
      • Getting Started
        Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

        Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

        All About Batteries

        All About Batteries

        What’s The Difference Between DC, Servo & Stepper Motors?

        What’s The Difference Between DC, Servo & Stepper Motors?

        Which OS is Best for Raspberry PI ?

        Which OS is Best for Raspberry PI ?

      • Pi Projects

        Raspberry Pi UV Sensor using the VEML6075

        Raspberry Pi Nvidia Shield: Stream Games using Moonlight

        Raspberry Pi Accelerometer using the ADXL345

        Raspberry Pi Accelerometer using the ADXL345

        Raspberry Pi Humidity Sensor using the DHT22

        Raspberry Pi Humidity Sensor using the DHT22

      • How to
        How to Install PHPMyAdmin on the Raspberry Pi

        How to Install PHPMyAdmin on the Raspberry Pi

        Setup a Raspberry Pi MYSQL Database

        Setup a Raspberry Pi MYSQL Database

        How to Upgrade Raspbian Stretch to Raspbian Buster

        How to Upgrade Raspbian Stretch to Raspbian Buster

        How to Setup Raspberry Pi RecalBox

        Play Retro Games with Raspberry Pi RetroPie

        Raspberry Pi DOSBox: Play Classic DOS Games on the Pi

        Trending Tags

        • Arduino Projects
          RS-485 Serial Communication between Raspberry Pi and Arduino Uno

          RS-485 Serial Communication between Raspberry Pi and Arduino Uno

          Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

          Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

          The 2019 Thermostat ReThink

          The 2019 Thermostat ReThink

          Tracked Arduino Robot

          Tracked Arduino Robot

        • News
          New report shows how IoT devices remain under ‘constant’ attack

          New report shows how IoT devices remain under ‘constant’ attack

          BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

          BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

          Raspberry Pi Comparison Table

          Raspberry Pi Kernel Updated to 4.19

          Apple Watch Series 2 Is Swimproof and Comes With Built-In GPS

          To regain advertiser trust, Facebook is tracking ads by the millisecond

          National Academy of Sciences endorses embryonic engineering

          Trending Tags

          No Result
          View All Result
          Raspberry Pi Developing
          No Result
          View All Result

          How to Build a Raspberry Pi Twitter Bot

          tibi by tibi
          March 16, 2019
          Home How to
          Share on FacebookShare on Twitter
          Raspberry PI Twitter Bot

          In this project, we will be exploring how to set up a basic low-cost Raspberry Pi Twitter Bot utilizing the Python programming language.

          In this Twitter bot tutorial, we will be showing you how to write the script while implementing the Twython package, and you will be amazed at how easy it is to set up. We will also be exploring how to use the Twython package and its major functions.

          We will also be showing you how to make the Twitter Bot tweet your Raspberry Pi’s CPU Temperature or periodically take a photo and upload it as a tweet.

          You can use your Raspberry Pi Twitter bot to automate a huge range of different tasks, these range from posting a picture to your Twitter account every hour to monitor the growth of a plant or even tweeting out values from sensors connected to your Raspberry Pi.

           Equipment List

          Below are all the bits and pieces that I used for this Raspberry Pi Twitter Bot tutorial.

          Recommended:

           Raspberry Pi 2 or 3

           Micro SD Card

           Power Supply

           Ethernet Cord or Wifi dongle (The Pi 3 has WiFi inbuilt)

          Optional:

           Raspberry Pi Case

           Registering a Twitter app

          1. To use the Twitter API, we will first have to register our account as a Twitter app. This API will allow us to use the REST interface and is what we will be utilizing to post new tweets to Twitter and generally interact with the website.

          Once you are logged into the Twitter account you plan on using, go to Twitter’s New App page. You will be shown the screen below.

          The three main things you need to focus on here is the Name, Description, and Websiteyou can set these to whatever you like as this will not be a user-facing application. Callback URL can be left blank as we don’t need any callbacks. Once done you can click the “Create your Twitter Application” button.

          Twitter Bot Create an application

          2. After you have created your Twitter App, you will be taken to the page displayed below, on here click the “Keys and Access Tokens” tab.

          Twitter Bot Application Manager

          3. On this screen, you will want to copy down both the Consumer Key (API Key) and the Consumer Secret (API Secret). We will need both of these to connect to the Twitter API.

          You can ignore both the Owner and Owner ID as we don’t require these to interact with the API.

          After copying down these two different values click the “Create my access token” (2.) button.

          Twitter Keys and Access Token

          4. After you have created the access token, the page will refresh. Scroll down to the bottom of the page and copy down both the Access Token and the Access Token Secret. These are the final values we need to be able to set up our Raspberry Pi Twitter Bot.

          Twitter Access Tokens

           Setting up and writing the Twitter Bot for the Raspberry Pi

          1. With our API tokens handy we can now start setting up and writing our Raspberry Pi Twitter bot. The first thing we should do is make sure our Raspberry Pi is up to date by running the following commands on it.

          sudo apt-get update
          sudo apt-get upgrade

          2. With the Raspberry Pi now updated let’s install the tools we will need to set up our Raspberry Pi Twitter Bot. We will be utilizing the Python package twython to interact with Twitter’s API. Let’s begin installing the packages by running the next few commands in the terminal.

          sudo apt-get install python-setuptools
          sudo easy_install pip
          sudo pip install twython

          3. Finally, we can begin writing the Twitter bot on the Raspberry Pi. Thanks to the Twython package that we just installed this is incredibly easy to do. First, let’s make a directory where we will keep our script and begin writing the script by running the following commands.

          mkdir ~/twitterbot
          cd ~/twitterbot
          sudo nano TwitterBot.py

          4. Now in this file, let’s write in the following piece of code. This code is incredibly simple thanks to the Twython library, and we will explain what each piece of the code does before we write it, so you get an idea of how it all works.

          from twython import Twython – We use this to make API calls to Twitter, and it simplifies the Python script a lot.

          import sys – Imports the sys library which we use to grab the system arguments that are passed to the script.

          The next block of code defines the various keys that we wrote down earlier in the tutorial, and we pass these values into Twython. Make sure you replace the values of CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, and ACCESS_SECRET before proceeding.

          We then define our variable API which stores the Twython object, we create this object with all our access and consumer keys. This object makes doing API calls to Twitter simple as all the data is there ready for it to use.

          Finally, we issue a update_status API call to our api object. This call should tweet any text that is passed into the script to your Twitter account.

          #!/usr/bin/env python
          import sys
          from twython import Twython
          
          #Define our constant variables, this is all the data we wrote down in the first part of the tutorial.
          CONSUMER_KEY = '***************YOUR DATA*****************'
          CONSUMER_SECRET = '***************YOUR DATA*****************'
          ACCESS_KEY = '***************YOUR DATA*****************'
          ACCESS_SECRET = '***************YOUR DATA*****************'
          
          #Create a copy of the Twython object with all our keys and secrets to allow easy commands.
          api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) 
          
          #Using our newly created object, utilize the update_status to send in the text passed in through CMD
          api.update_status(status=sys.argv[1])

          Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

          5. With the Twitter Bot script now written, we need to make the script executable, so we can send our text by passing it to the Python file as an argument.

          sudo chmod +x TwitterBot.py

          6. Now let’s test out the Twitter Bot script by running the following command, this will make sure that we are making a valid connection with the Twitter API and ensure we have written. After the command has run, check your Twitter account to see the new tweet.

          sudo python TwitterBot.py "This is a test tweet from PiMyLifeUps Twitter bot"

          7. Once you have confirmed that the tweet was successfully sent we can start doing a few more interesting things with the Twitter Bot, just sending a simple message is kind of boring after all.

          Our next two sections will explore both making the Twitter bot send out an image taken from a webcam and also show you how to get the Twitter bot to tweet out the Raspberry Pi’s CPU temperatures.

          First, off we are going to explore grabbing the CPU temperature and tweeting that out if you are more interested in the webcam picture sending then you can skip on further down the page.

           Tweeting the Raspberry Pi’s CPU temperature

          1. Let’s begin by editing the Twitter Bot script by running the following command on our Raspberry Pi.

          sudo nano TwitterBot.py

          2. Now that we have opened up the fire we can make the following changes.

          Find

          import sys

          Replace With

          import os

          Since we no longer need to worry about arguments being passed in, we can replace the sys library with our new os library. The OS library allows us to interact with the operating system itself, and in our case, we will be using it to issue a command on the OS and get the result. You will see this in our next lot of code changes.

          Find

          api.update_status(status=sys.argv[1])

          Replace With

          cmd = '/opt/vc/bin/vcgencmd measure_temp'
          line = os.popen(cmd).readline().strip()
          temp = line.split('=')[1].split("'")[0]
          api.update_status(status='My current CPU temperature is '+temp+' C')

          Basically, what this bit of code does is issue a command into Raspbian’s terminal, this command calls a binary file that returns the Raspberry Pi’s temperature. We then process this file to grab the correct value that we are after and then simply send out a Tweet with the update_status command that has the value we caught.

          Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

          3. We can test out this new piece of code by running the following command on our Raspberry Pi.

          python TwitterBot.py

          If you check out your Twitter account, you will notice that you will have a new tweet that displays your Raspberry Pi’s CPU temperature.

          With that done, you can now skip down to our automating your Raspberry Pi Twitter Bot section unless you want to learn how to send webcam photos from your Raspberry Pi to Twitter.

           Tweeting Webcam Photos via your Raspberry Pi Twitter Bot

          1. Let’s begin by editing the Twitter Bot script by running the following command on our Raspberry Pi.

          sudo nano TwitterBot.py

          2. Now we can make the following changes to our bot to make it send an image from an attached video interface.

          Find

          import sys

          Replace With

          import pygame
          import pygame.camera
          from pygame.locals import *

          We replace the sys library with pygame as we no longer need to grab any variables passed into the script. Pygame is a library that contains a large range of Python modules designed for writing games. Of course, we aren’t writing a game, but pygame has an excellent and easy to use module for utilizing cameras so we will be making use of that module to set up our Raspberry Pi Twitter Bot.

          Find

          api.update_status(status=sys.argv[1])

          Replace With

          pygame.init()
          pygame.camera.init()
          cam = pygame.camera.Camera("/dev/video0",(640,480))
          cam.start()
          image = cam.get_image()
          pygame.image.save(image,'webcam.jpg')
          
          photo = open('webcam.jpg','rb')
          api.update_status_with_media(media=photo, status='Test Raspberry Pi Image Bot => ')
          

          We need first to replace the original update_status call with several other calls. The first function that we add sets up and initializes the pygame library. We then proceed to initiate pygame’s camera module, and this sets itself up so we can get it to read from one of our interfaces.

          We then store a copy of the camera object in our cam variable, setting it up to use our /dev/video0 interface and use the resolution of 640×480 for pictures we capture from the device.

          Once we have done that, we can use the new object and start the camera up, and this allows us to grab images off the camera which we do in the following line of code.

          With the image now saved to the Raspberry Pi, all we need to do is read back in that image using the open function, and then making use of another handy Twython function.

          This function is update_status_with_media, and it allows us to send a tweet with an image which is perfect for sending our just grabbed webcam photo.

          Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

          3. Please note if you are using your Raspberry Pi camera as your webcam, make sure you run the command below before running this script. This command allows it to appear as a /dev/video* interface.

          sudo modprobe bcm2835-v4l2

          4. We can test out this new piece of code by running the following command.

          python TwitterBot.py

          With that done, you can now skip down to our automating your Twitter Bot section.

           Automating your Twitter Bot

          1. There isn’t much use in your Twitter Bot if you must manually run it all the time, one of the best ways to get your bot to be continually triggered is to use Cron Jobs.

          You may be wondering why we just don’t run the script in a continuous loop, well two reasons for this is that there is no guarantee that the script won’t hang at some point, the other is that it burns up precious processing cycles having to continually loop and check whether we should be tweeting out.

          So now let’s begin by editing the crontab by running the following command.

          sudo crontab -e

          2. To this file you want to add the line of text below to the bottom of the file, basically what this will do is automatically trigger the script every hour.

          If you want to work out your own times for when you want the script to trigger but are not used to dealing with Cron Jobs, you can try using an online tool such as Crontab Guru as it will give a human-readable version of the cron schedule. Just replace */60 * * * * with your generated value.

          */60 * * * * python /home/pi/twitterbot/TwitterBot.py

          Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

          You should now hopefully have a fully operational basic Twitter Bot that will continuously tweet out every time the cron job goes off. We hope we have explained the code enough and kept it basic enough that you can easily extend the bot to do more complicated tasks.

          If you enjoyed this Raspberry Pi Twitter bot tutorial, you can also check out our Twitch moderator bot tutorial as well. If you have any feedback or have run into any issues with this tutorial, then feel free to leave a comment over at the forums.

          Tags: buildraspberrytwitter
          tibi

          tibi

          Next Post
          Raspberry Pi Email Notifier using the Sense HAT

          Raspberry Pi Email Notifier using the Sense HAT

          Leave a Reply Cancel reply

          Your email address will not be published. Required fields are marked *

          Recommended.

          Simple Raspberry Pi WiFi Extender

          Simple Raspberry Pi WiFi Extender

          March 14, 2019

          Peanut is a Tinder-like app for making new mom friends

          March 14, 2019

          Trending.

          Raspberry Pi TorrentBox: Build an Always-On Torrent Machine

          Raspberry Pi TorrentBox: Build an Always-On Torrent Machine

          March 16, 2019
          How to Setup a Raspberry Pi NAS (Network Attached Storage)

          How to Setup a Raspberry Pi NAS (Network Attached Storage)

          April 13, 2019
          How to Setup a Raspberry Pi Nextcloud Server

          How to Setup a Raspberry Pi Nextcloud Server

          March 14, 2019
          Raspberry Pi OwnCloud: Your Own Personal Cloud Storage

          Raspberry Pi OwnCloud: Your Own Personal Cloud Storage

          March 16, 2019
          Raspberry Pi MySQL & PHPMyAdmin Tutorial

          Raspberry Pi MySQL & PHPMyAdmin Tutorial

          April 15, 2019
          Raspberry Pi Developing

          PI Guide Developing is where you can find some of the coolest Raspberry Pi projects and guides on the web. You can check them all out right here.

          Follow Us

          Categories

          • Arduino Projects
          • Getting Started
          • How to
          • News
          • Pi Projects

          Tags

          about adding Apple Watch 2 arduino beginners Best iPhone 7 deals build Buying Guides camera CES 2017 clock digital display drive email games getting guide install installing iOS 10 iPhone 7 learn linux mount mysql network Nintendo Switch phpmyadmin Playstation 4 Pro python raspberry Raspbian sense sensor server setting setup Sillicon Valley simple started storage system tutorial using

          Recent News

          How to Install PHPMyAdmin on the Raspberry Pi

          How to Install PHPMyAdmin on the Raspberry Pi

          July 28, 2019
          Setup a Raspberry Pi MYSQL Database

          Setup a Raspberry Pi MYSQL Database

          July 28, 2019
          • About
          • Advertise
          • Privacy & Policy
          • Contact

          © 2019 PI GUIDE - Premium PI Guide PI GUIDE.

          No Result
          View All Result
          • Home
          • Getting Started
          • How to
          • Pi Projects
          • Arduino Projects
          • News

          © 2019 PI GUIDE - Premium PI Guide PI GUIDE.