---
title: How to Create a Twitter Bot with GoLang
description: Learn how to create a bot to run your Twitter social media account for you!
image: https://blog.avenuecode.com/hubfs/smartphone-g2be04212e_1920.jpg
---

[AvenueCode.com](https://avenuecode.com) [News](https://avenuecode.com/news) [Contact](https://avenuecode.com/contact)

[![Avenue Code Snippets Logo](https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/AC-Snippets---Black.png)](https://blog.avenuecode.com/?hsLang=en-us) *menu*

- Technology
  
  [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us) [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us) [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us) [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us) [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
  
  [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us) [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us) [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us) [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

- [Cloud](https://blog.avenuecode.com/blog/topic/cloud?hsLang=en-us)
- [Design](https://blog.avenuecode.com/blog/topic/design?hsLang=en-us)
- [Delivery Infrastructure](https://blog.avenuecode.com/blog/topic/delivery-infrastructure?hsLang=en-us)
- [Solution Architecture](https://blog.avenuecode.com/blog/topic/solution-architecture?hsLang=en-us)
- [Web Experience](https://blog.avenuecode.com/blog/topic/web-experience?hsLang=en-us)
- [Data & ML](https://blog.avenuecode.com/blog/topic/data-and-machine-learning?hsLang=en-us)
- [Agile Mindset](https://blog.avenuecode.com/blog/topic/agile-mindset?hsLang=en-us)
- [Mobile Experience](https://blog.avenuecode.com/blog/topic/mobile-experience?hsLang=en-us)
- [Quality First](https://blog.avenuecode.com/blog/topic/quality-first?hsLang=en-us)
- [Whitepapers](https://blog.avenuecode.com/blog/topic/whitepapers?hsLang=en-us)
- [Spotlight](https://blog.avenuecode.com/blog/topic/spotlight?hsLang=en-us)
- [Extraordinary Women in Tech](https://blog.avenuecode.com/blog/topic/extraordinary-women-in-tech?hsLang=en-us)
- [Avenue Code Culture](https://blog.avenuecode.com/blog/topic/avenue-code-culture?hsLang=en-us)

# [How to Create a Twitter Bot with GoLang](https://blog.avenuecode.com/how-to-create-a-twitter-bot-with-golang)

- [Tweet](https://twitter.com/share)

*perm\_identity* [João Bragança](https://blog.avenuecode.com/how-to-create-a-twitter-bot-with-golang/author/jo%C3%A3o-bragan%C3%A7a?hsLang=en-us)

*schedule* 1/18/23 2:00 PM

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](https://developer.twitter.com/). 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.![](https://lh3.googleusercontent.com/dYD9undLGhRo9JFmAx1Ur4Cr96XKtZuSYPaT9s5y-j9WvctdotnJyBSNlWatyz8-hnwNo1V0YJaOLX3fieQPlGXeni1VP7F88qHjPnWP4mQFZKx2-6fc9NMNM3dJ2QSqOysHo0EM-OYv_cu-hetBwYHE8GToAuLtf7D06-h4Q_10xIbu8EwxxxcJYy69-A)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": 

![](https://lh4.googleusercontent.com/kkyyMCTRFlpVAdWIF18UQwXb2hMJQcVegK_9weQy7LfwCS_GKQpFj-4cLfIFMySPj_GlPlW20haDFAVq2Xpx-1LvVtiroGBdlFvj_roDcrk3soMb6OaUvlopX7aqBWxW85EX7rUb6X08K56hSn-ge20u45xQrHjW1a9VXtv6gxxUoJ3G6McMlYKMnZwDRA)

Then we select "App name," where we will be able to get our access token and key.

![](https://lh5.googleusercontent.com/4-WY8EWzUP-CM4TUR7UI_0kP6pkraHzJnLlqoeaalfmomuBdhqhkj8ZLAQw3zrh3d0-MJ1f5QH2Q3FYW0d1iuf2pBNUU8Li4nhJCEF7WNlX05VYswhj3KNYkq1V3lVUp1xul9xE-cweSvLj4N1n4q_WOws0Bof2Bo8U6LhavC67D_R-AKPnCmnfnHS6aig)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.

![](https://lh3.googleusercontent.com/Sh5uSYUlwBOwpaEdKLE91v9Ikam530SDNPkHdLSqlfuBjTq0eLMILy4fYm4AjJ1hd-4qHwDZMeIyyH_x0SmFnfXVDG4rdIAVZv4RgruhSp3zmq_c5Ry-0rVe81dFKQkUQEjL4VBYLu2YlgixkwsHVTp3-q7WwwIlx_v8G-F1UbJJx4qEF59s8VFtl_XyIQ)

Under User authentication settings, click on the Set upbutton

![](https://lh5.googleusercontent.com/b8Awr-JjDZn0OCm5vwe0MfCgb9mEXHC5epc8wAjlZeITC8kP52Z8YYsJE6-y1FKDVtIFvFFRgIZ_QcGgdlSi0OB6--iWXgCzxfTSTl2ByFvU4VMn8oIdjUvctPDqBxYAmrap88mwqYPaLFI9E830JD8wF_IZMCrmV8lT-Qk4eLOUnil8wuXT24J7mOSFzg)

Under **App Permissions, **we **MUST** give **Read and write** permissions. The **Type of App** is **Web App, Automated App or Bot**. 

![](https://lh4.googleusercontent.com/4_7A3u_-Gfbn7UIVyevQ8zIyyFmqGx-cvzxk9p5Iwc44lQluJvovUlj7bs-h9jyQ4sYsBhmWaWuMH2vWExLFweiFDAooCu5yfQMG8EAdZsRIAUUqYUvYQPWT4WY3VYRSfPEuWa9hrABs-_PeB2XxIvKSaBtVuqOewQ9Y4xnWKor-sDMYT9VbbQ5tRdp2_A)

![](https://lh5.googleusercontent.com/_OntWz7bfko3CkiNT5LNRJLHVQcybFcSRV8UtKPKRkoHzlcnHYJtTCgm6B_EUyS538h7OzYGrXHtUj3jMLEqIYApm8bcrWC7s4ODNvx-6-J5GnvxdKq0lmZa1JNTW_ZN8W-vcjrQdInzcNGce97AGc1qFTjygvacvX7z2Dn3venJ13DBLXJI9_xk1_qR6A)

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**.

![](https://lh5.googleusercontent.com/8-5Zoz3IBGmMfPRiajaXopZgTMdKpMHwi9jCCgz7CwIuzVHHboyBXY72uvbw_Bliqic9NoO2QoftAGgq-rExnLbB51tpx2QXZtR6tdQBFgK_xqGlPIwqVc9n1xB7L5bNppG4QAFT_QgECMQvJM2eyhdjO_z1hRPCoLghSXHsVyqE_kdMkulFx9ZobRMxCw)

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.

![](https://lh3.googleusercontent.com/1Ps7WYL5iGUDRG305J1kTKuEGDWw2x3sM-9XVHC_I7x9gGHV1PSmtJb5I04ylrmHZtdYmoegIB_1ktI_hEoVDFTRny3PeJ2s0dyZdOAukuBEkFgP3iWOqEDlp6wM02EekGXZ00vjXL2CUc--dQnwrvzAV9TZtJTcQBFZemdEekEJS6HiJNGQrVfpGKrwew)  
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$cd 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 $ go get github.com/dghubble/go-twitter $ go get github.com/dghubble/oauth1 |
| --- |

 

##### 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= API\_KEY\_SECRET= ACCESS\_TOKEN= ACCESS\_TOKEN\_SECRET= |
| --- |

 

##### 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") *// if there is any problem loading the variables the program will exit* if err != nil {   log.Fatalf(".env File not found") } |
| --- |

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* config := oauth1.NewConfig(os.Getenv("API\_KEY"), os.Getenv("API\_KEY\_SECRET")) *// setting up the token* token := oauth1.NewToken(os.Getenv("ACCESS\_TOKEN"), os.Getenv("ACCESS\_TOKEN\_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* httpClient := config.Client(oauth1.NoContext, token) *// creates a twitter client from the installed package with a httpClient* client := twitter.NewClient(httpClient) |
| --- |

 

##### 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) *// check for errors and if there is any it will print it and exit the program* if err != nil {   log.Fatal(err) } |
| --- |

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:

![](https://lh6.googleusercontent.com/fktMJN2YSsp_BYLlw3dR1JI2Giwc65jqWp9ua7LrV7G0fwK9Xu8rmPM_k-4j8mihurorAh6b9Eg-fCuMAVPuF-FW8tqgrlZZthhRPFOWUTSIixDlzl-BpGdsJSSIGBGfN-3KpG16_k4YIjgu3WbS30g9Y2UFCcj08fdG63uIvNxocQn3TGlXyW2LdRSTSg)

##### 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{   Query: "#golang", *// the word of phrase we want to query, note that it is case insensitive*   Count: 5,         *// the amount of tweets to be returned* }) *// check for errors and exit the program* if err != nil {   log.Fatal(err) } *// iterates over the results and print them* for \_, tweet := range tweets.Statuses {   log.Print(tweet.Text) } |
| --- |

 

##### 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* for \_, tweet := range tweets.Statuses {   \_, \_, err := client.Statuses.Retweet(tweet.ID, nil)   if err != nil {     log.Fatal(err)   } } |
| --- |

##### Whole content of main.go

| package main import (   "github.com/dghubble/go-twitter/twitter"   "github.com/dghubble/oauth1"   "github.com/joho/godotenv"   "log"   "os" ) func main() {   err := godotenv.Load(".env")   if err != nil {     log.Fatalf(".env File not found")   }   config := oauth1.NewConfig(os.Getenv("API\_KEY"),     os.Getenv("API\_KEY\_SECRET"))   token := oauth1.NewToken(os.Getenv("ACCESS\_TOKEN"),     os.Getenv("ACCESS\_TOKEN\_SECRET"))   httpClient := config.Client(oauth1.NoContext, token)   client := twitter.NewClient(httpClient)   */\*\*  tweet, res, err := client.Statuses.Update("Hello, World! This is the first message from the twitter bot.", nil)  // check for errors and if there is any it will print it and exit the program  if err != nil {    log.Fatal(err)  }  log.Println(tweet.Text)  \*/*   tweets, \_, err := client.Search.Tweets(&twitter.SearchTweetParams{     Query: "#golang", *// the word of phrase we want to query, note that it is case insensitive*     Count: 5,         *// the amount of tweets to be returned*   })   *// check for errors and exit the program*   if err != nil {     log.Fatal(err)   }   *// iterates over the results and retweet every tweet*   for \_, tweet := range tweets.Statuses {     \_, \_, err := client.Statuses.Retweet(tweet.ID, nil)     if err != nil {         log.Fatal(err)     }   } } |
| --- |

 

##### 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](https://pkg.go.dev/github.com/dghubble/go-twitter/twitter) to learn more. You can check out the whole bot code on GitHub [here](https://github.com/jvbraganca/golang-bot). 

 

##### About Avenue Code

Curious about what we do when we're not building bots? Learn more on our [website](https://avenuecode.com/what-we-do/)!

---

### 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.

---

### Related Posts

### Building Accessible Web Applications

[READ MORE](https://blog.avenuecode.com/building-accessible-web-applications?hsLang=en-us)

### How the Mulesoft JWT Validation Policy Works

[READ MORE](https://blog.avenuecode.com/mulesoft-jwt-validation-policy-works?hsLang=en-us)

### How to Use Redis Cache to Prevent DDoS Attacks

[READ MORE](https://blog.avenuecode.com/use-redis-cache-to-prevent-attacks?hsLang=en-us)

### Using Spring Webflux for REST APIs: Annotated and Functional Endpoints

[READ MORE](https://blog.avenuecode.com/using-spring-webflux-for-rest-apis-annotated-and-functional-endpoints?hsLang=en-us)

### Leave a Comment!

### Avenue Code Social

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Blog/facebook.png?t=1486470796564)](https://www.facebook.com/avenuecode)

[![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Blog/twitter.png?t=1486470796842)](https://twitter.com/AvenueCode)

[![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Blog/linkedin.png?t=1486470796556)](https://www.linkedin.com/company/avenuecode/)

### Newsletter

Want to stay on top of all tips and news from Avenue Code?

### Popular Snippets

![Avenue Code-primary versions_logo white avenue code endorsement 2](https://blog.avenuecode.com/hs-fs/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_logo%20white%20avenue%20code%20endorsement%202.png?width=1180&name=Avenue%20Code-primary%20versions_logo%20white%20avenue%20code%20endorsement%202.png "Avenue Code-primary versions_logo white avenue code endorsement 2")

### About Us

- [Who We Are](https://www.avenuecode.com/who-we-are)
- [What We Do](https://www.avenuecode.com/what-we-do)
- [Portfolio](https://www.avenuecode.com/portfolio)
- [Partners](https://www.avenuecode.com/partners)
- [News](https://www.avenuecode.com/news)
- [Events](https://www.avenuecode.com/events)
- [Blog](https://blog.avenuecode.com/)
- [Contact](https://www.avenuecode.com/contact)

### Our Offices

San Francisco

[+1 415 766 4178](tel:+553125161448) [ac.inquiries@avenuecode.com](mailto:brazil.info@avenuecode.com)

Belo Horizonte

[+55 31 2516 1448](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

São Paulo

[+55 11 3205 3232](tel:+553125161448) [brazil.info@avenuecode.com](mailto:brazil.info@avenuecode.com)

### We're Hiring!

- [Belo Horizonte](https://www.avenuecode.com/who-we-are)
- [New York](https://www.avenuecode.com/what-we-do)
- [San Francisco](https://www.avenuecode.com/portfolio)
- [São Paulo](https://www.avenuecode.com/partners)

---

©2015 - 2017 Avenue Code

[![Facebook Icon](https://blog.avenuecode.com/hubfs/Images/Icons/facebook-2.png)](https://www.facebook.com/avenuecode) [![Twitter Icon](https://blog.avenuecode.com/hubfs/Images/Icons/twitter-2.png)](https://twitter.com/AvenueCode) [![LinkedIn Icon](https://blog.avenuecode.com/hubfs/Images/Icons/linkedin-2.png)](https://www.linkedin.com/company/avenue-code) [![Glassdoor Icon](https://blog.avenuecode.com/hubfs/Images/Icons/glassdoor-icon-1.png)](https://www.glassdoor.com/Overview/Working-at-Avenue-Code-EI_IE456173.11,22.htm) [![YouTube Icon](https://blog.avenuecode.com/hubfs/Images/Icons/youtube-2.png)](https://www.youtube.com/user/AvenueCodePlay)

Please enable JavaScript to view the [comments powered by Disqus.](http://disqus.com/?ref_noscript)

© 2026 Avenue Code

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "João Bragança",
    "url" : "https://blog.avenuecode.com/author/joão-bragança"
  },
  "dateModified" : "2023-01-18T17:00:00.724Z",
  "datePublished" : "2023-01-18T17:00:00.000Z",
  "headline" : "How to Create a Twitter Bot with GoLang",
  "image" : [ "https://blog.avenuecode.com/hubfs/smartphone-g2be04212e_1920.jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.avenuecode.com/how-to-create-a-twitter-bot-with-golang",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.avenuecode.com/hubfs/Avenue%20Code%20New%20Logos%20-%202023/Avenue%20Code-primary%20versions_LOGO%20HORIZONTAL%20group%201-7.png"
    },
    "name" : "Avenue Code"
  }
}
```