Welcome to the next tutorial of our Raspberry Pi programming course. Our previous tutorial taught us to configure our raspberry pi for voice control. We also discussed some methods of reducing vexing noises so that the voice command program understands you. However, in this lesson, we will learn how to tweet from Raspberry pi.
What will we learn?
Assume you wish to add tweeting into a Raspberry Pi software you’re developing. This article will show you how to build a Twitter app, get access privilege tokens, and post a tweet. On our Raspberry Pi, we’ll make a simple program that tweets the result of the uptime command. This is a made-up example, but it demonstrates what is needed to tweet from a raspberry pi.
For this session, a repo has been set up. Because we’ll be referring to code within the repository, cloning it will be helpful. You could use this program as a reference point for your programs or copy the components you need.
Let’s start by installing git with the command below.
We’re going to clone the repository into our current working directory now:
After that, change the directory into the repository.
The Twitter Application programming interface requires that all queries use OAuth for authentication. To access the Application programming interface, you must first create the authentication credentials. Four text strings make up these credentials:
- Consumers keys
- Consumers secrets
- Login Tokens
- Login Secrets
If you’re a Twitter account, go through the procedures below to get the keys, tokens, and secrets. If you don’t have a Twitter account, you’ll need to establish one first.
Step 1: To become a Twitter Developer, fill out the form below.
Visit Twitter’s developer site to sign up for a new account. You must now select the Twitter subscriber in charge of this account. It’s most likely going to be yourself or your company. This is how this page appears:
After that, Twitter asks you questions about whatever you want to utilize the developer’s account, as seen below:
You must specify the developer account’s username and whether it will be used for commercial or personal purposes.
Step 2: Create an application
Apps and not accounts have access to Twitter’s authentication credentials. Every tool or program that uses Twitter’s API qualifies as an app. To perform API calls, you must first register your application. Navigate to the Twitter applications page and click on the option to create an application to register the app.
The following details regarding your application and its aim must be provided:
- App name: a name that will help people remember your app (such as examplebot)
- The objective of your application is described in the application description
- Uses of the app: how customers will utilize your application
- The uniform resource locator of your app’s website is required; however, it could be a personal website’s URL because bots do not require a URL to function.
Step 3: Create your Credentials for Authentication
Navigate to your Twitter applications page to generate the authentication credentials. This is how the Apps page looks:
The Details button for your app can be found here. After hitting this button, you’ll be sent to the following page, on which you can obtain your credentials. You could generate and copy the keys to use in your code by selecting the Keys and Tokens tab:
Save the credentials after you’ve generated them to use them later in your code.
The following snippet can be used to test the credentials:
How can we set the app permissions?
Ensure that the “Read, access, and write direct message” is ticked in the “Permissions” section.
How can we Install Tweepy?
Tweepy is a Library for python for utilizing the Twitter API, and it’s included in the requirements.txt document, so all you have to do is:
How does tweepy work?
Tweepy is a library that simplifies the Twitter application programming interface. Tweepy is a collection of functions and classes that mirror Twitter models and application programming interfaces, and it handles implementation details discreetly, such as:
- Decoding and encoding of data
- Hypertext transfer protocol requests
- Results paging
- Rate restrictions
If you didn’t use Tweepy, you’d have to deal with low-level features like hypertext transfer protocol, data encoding, authorization, and speed limits. This may consume a lot of time and is subject to mistakes. Tweepy allows us to concentrate on the functionalities we wish to implement.
Tweepy can be used to access the Twitter application programming interface features. Let’s have a simple example to see what we’re talking about.
The example command below will download all of your tweets from your timeline and output each one to the console. Twitter mandates that all requests be authenticated using OAuth. Tweepy makes using OAuth simple for you. We’ll need to establish an account for our application to get started. Build a new app, and when it’s done, you should get your authentication token and secret. Keep these two with you at all times; you’ll need them.
Next, create an instance of OAuthHandler. We enter our user token and secret, which we received in the previous line, into this:
If you’re utilizing a callbacks uniform resource locators that need to be given dynamically in a web application, you will pass it in like this:
If the callback uniform resource locator isn’t going to change, it’s preferable to put it up as static on Twitter when creating your app.
Unlike basic authentication, we must first perform the OAuth “dance” before we can use the API. The steps below must be completed for this:
- Redirect the user to the Twitter account to approve our application by obtaining a request tokens from Twitter
- Twitter sends the user to our website whenever a callback is used. Otherwise, the user will have to enter the verification code manually.
- Substitute an access token for the authorized request token.
So, to start the dance, let’s get our request token:
This call asks Twitter for a token and then provides the authorization uniform resource locator, to which the user should be redirected to approve us. Simply keeping our OAuthHandler object alive till the user returns is sufficient. In a web app, a callback will be used. As a result, the request token must be saved in the session because it will be required in the callback uniform resource locator request. A fictitious example of saving the request tokens in a session is as follows:
As a result, we can now redirect the visitor to the uniform resource locator returned by our authorization URL() function.
If it is a desktop program (or any other software that doesn’t employ callbacks), we’ll need to ask for the “verifier code” that Twitter will provide after they have authorized us. This verifying code is sent in the callback query from the Twitter account as a GET query argument in the URL within a web application.
The request token is then exchanged with an access token in the last phase. The access token is the “key” to the Twitter Application programming interface treasure chest. To obtain this token, we must perform the following steps:
It’s good to keep the access token on hand if you need it later. It is not necessary to fetch it every time. Because Twitter does not currently expire tokens, they would become invalid only when the user revokes our application’s access. Your application determines the location where you store the authentication token. Essentially, you must save two string values: secret and key:
You can save these in a database, a file, or wherever else your data is stored. To re-create an OAuthHandler using this cached access token, follow these steps:
Since we have an access token for our OAuthHandler, we can move on to the following step:
Tweet python code
How is API used in this library?
The application programming interface class gives you access to the Twitter RESTful API’s entire methods. Each method can take different parameters and provide different results. The API methods are classified into the following groups:
User timeline methods
These ways allow you to read mentions, tweets, and retweets on your timeline and any other public user’s timeline.
These methods deal with tweet creation, retrieval, and retweeting. Tweepy is used in the following code to produce a tweet with specific text:
The functions in this group may be used to retrieve users using a filtering criterion, extract user data, and show followers for each user so long as the account is public.
This set of routines includes methods for following as well as unfollowing persons, requesting followers for a user, and displaying the profiles a user is following.
Using these methods, you may write and view your profile information. This code sample might be used to change your profile information, for example:
You can designate any twitter message as Liked or delete the Like tag if it has already been added using these API calls.
Blocking user method
This collection of methods includes unblocking and blocking members and a list of blocked users. You can view the users you’ve blocked in the following way:
You may search tweets using these methods using language, text, and other filters. For instance, this code will return the ten latest public tweets in English that contain the term “Python”:
This set of tools allows you to generate a list of the most recent developments for any place. Here’s how to construct a list of worldwide hot issues, for example:
Streaming enables you to actively monitor tweets in real-time for those that meet particular criteria. This indicates the program waits for the latest tweet to be produced before processing it if no other tweets satisfy the requirements.
You must construct two objects to use streaming:
- The stream object retrieves tweets that meet certain criteria using the Twitter API. A streaming listener receives tweets from this source.
- The streaming listener receives the tweets from the stream.
This is how you do it:
How about models?
Most of the time, when we call an API method, we’ll get a Tweepy class model object back. This will hold Twitter’s data, which we can use in our program. The following code, for example, returns a user model:
The following are the model classes:
- Search Result
Let’s assume you want to obtain a list of all the tweets that mention you, then like each one and follow the author. This is how we can go about doing it:
Since every tweet object given by the mentioned timeline() belongs to the Statuses class, you can use the following syntax:
- favorite() to make it a favorite
- favorite() to make it a favorite
Tweet.user property is also a user object. Follow() may add the author of that tweet to the list of individuals to follow. Using Tweepy models allows us to write concise and understandable code.
What is next after setting up our app?
Maybe we can put a motion detector and a camera on our cat and tweet images of it. Alternatively, we could set up a temperature sensor and tweet some weather-appropriate status updates. We can also leave the repository unchanged and tweet the uptime command if we only want others to know our pi’s load average.
You may take the Twitter presence to another level by creating your personal Twitter bots. You may use bots to automate content generation and other Twitter tasks. This may save time and provide a better user experience for your viewers. The Tweepy library hides numerous low-level Twitter application programming interface details, allowing you to concentrate on the logic behind your Twitter bots.
In this tutorial, we learned how to set up our tweeter app on our Raspberry pi. We also learned how to generate access tokens, set up our app’s permissions, and send a tweet. However, In the following tutorial, we will learn how to print on a Raspberry pi.