As a software engineer, I am always looking for ways to automate things using APIs. And having a bot doing what you wish is really cool. For instance, if you want to share some knowledge with your Twitter community, you can write a bot that searches for the information and publishes it for you without any sweat. So today we are going to learn how to write, query, and retweet using the Twitter API and a GoLang client.
Creating Your Bot
The first step you need to take to create a Twitter Bot is to sign up for a developer account by clicking here. Log in with your Twitter account and click the Sign up button at the top right corner of your screen. Make sure you are logged in to the account you wish to automate.From here, you will click on the Create Project button, where you will describe your project. First, enter the project name and then the use case. For this article, I wrote:
1. Project name: GoLand Bot
2. Use case: Making a bot
3. Project description: A bot to tweet, retweet, and reply to others.
The app environment I selected was "Development":
Then we select "App name," where we will be able to get our access token and key.
On the next page, your API Key and API Key Secret will be displayed. Be sure to copy them to a safe place. Then click on the Go To Dashboard button. We need to configure our app authentication for this, so click on the gear icon and go to the App Settings page.
Under User authentication settings, click on the Set up button
Under App Permissions, we MUST give Read and write permissions. The Type of App is Web App, Automated App or Bot.
Under App info, feel free to insert whatever you want. Under Callback URI and Website URL, I inserted the bot’s GitHub repository. Then, click the Save button. You will be prompted to input your Client ID and Client Secret; copy them if you want to use OAuth 2, but for this article we will be using OAuth 1.
When redirected to the project dashboard, go to the Keys and tokens tab and copy your access token and secret. Make sure it was generated with Read and write permissions.
Again, copy them to a safe place. Now we are ready to begin coding.
Creating the GoLang project
Open your terminal and create a Go project. First, create a folder for your project (mine will be named golang-bot), and change it to its directory.
$ mkdir golang-bot |
Now, we can create our GoLang project. Move into your favorite IDE (mine is GoLand). Create a main.go file so we can write the bot’s code, and initialize a module with:
$ go mod init theNameOrPathToYourModule |
Installing the Necessary Libraries
In this project, we have three necessary libs. Install them with:
$ go get github.com/joho/godotenv |
Configuring the Project
Then, create your .env file and populate it with the API KEY, API KEY SECRET, ACCESS TOKEN, ACCESS TOKEN SECRET, in the following format:
API_KEY= |
Loading the Environment Variables
We can proceed to load our environment variables with godotenv package, for which we must use godotenv.Load(“.env”):
err := godotenv.Load(".env") |
Now we want to configure our access to the Twitter through oauth1 package as shown below:
// setting up the oauth1 library with our api key and secret |
Creating the Client
Now it’s necessary to create a httpClient with oauth1 and then a Twitter Client.
// creating a HTTP Client with the token |
Posting a Tweet from the Bot
Finally, we are able to have some fun! To create a tweet, you can use the client we declared with the twitter package. And for tweeting, you may code:
tweet, res, err := client.Statuses.Update("Hello, World! This is the first message from the twitter bot.", nil) |
The res variable contains the http.Response from our request to the Twitter Api. In this case it is irrelevant, so I am going to replace it with _. The tweet variable contains all the data of the posted tweet. To see what was posted, you may log it with tweet.Text
log.Println(tweet.Text) |
Now, run the program on the terminal with:
$ go run main.go |
And here is the output:
$ 2022/12/01 20:18:40 Hello, World! This is the first message from the twitter bot. |
You can see the tweet by going to your Twitter profile. Here's mine:
Querying Tweets
Great! Now you know how to post tweets from your own client. The next step is to learn how to search tweets containing certain keywords. For this, we will still be using the same Twitter client but a different method. If we want to search for tweets containing the hashtag #golang, all we have to do is:
tweets, _, err := client.Search.Tweets(&twitter.SearchTweetParams{ |
Retweeting
And run the program again to see the results. The last thing for us to learn is how to retweet. This is pretty simple as well. After querying for a list of tweets, all you have to do is:
// iterates over the results and retweet every tweet |
Whole content of main.go
package main |
Conclusion
Today we covered the basics of how to start using the Twitter API. You may also create a cron job to run this bot every 15 minutes, or host it on Azure Functions, and it will keep running and executing your tasks. If you are eager to discover what else you are able to do with the Go Twitter package, visit the documentation page to learn more. You can check out the whole bot code on GitHub here.
About Avenue Code
Curious about what we do when we're not building bots? Learn more on our website!
Author
João Bragança
João Bragança is a Backend Software Engineer at Avenue Code. He has been passionate about technology since his early teens, and about aviation for as long as he can remember.