{"id":611,"date":"2022-05-27T15:28:48","date_gmt":"2022-05-27T15:28:48","guid":{"rendered":"https:\/\/andrejacobs.org\/?p=611"},"modified":"2022-05-27T15:28:53","modified_gmt":"2022-05-27T15:28:53","slug":"send-twitter-tweets-using-go","status":"publish","type":"post","link":"https:\/\/andrejacobs.org\/projects\/send-twitter-tweets-using-go\/","title":{"rendered":"Send Twitter tweets using Go"},"content":{"rendered":"\n
Featured image by\u00a0Egon Elbre<\/a><\/p>\n\n\n\n Nothing beats learning like working on an actual project. To that degree I started working on my own command line application ajtweet<\/a> to learn more about building CLI apps and Go in general.<\/p>\n This post goes over the process of how I managed to use the Twitter v2 APIs from Postman as well as from a simple Go application. You can also check out the example code here<\/a>.<\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n I will be following this guide<\/a> on how to make the first request.<\/p>\n The quickest test is to do a user lookup using curl from the terminal.<\/p>\n First I will be setting up and using Postman to send a tweet followed by writing an app in Go to do the same thing.<\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n <\/p>\n TL;DR; You can find the example code here<\/a>.<\/p>\nRegister to get access to Twitter APIs<\/h2>\n
\n
Creating new keys, secrets and tokens<\/h2>\n
\n
\n
\n
\n
\n
Making the first request<\/h2>\n
# First do a fail test, e.g. not providing the credentials\n$ curl "https:\/\/api.twitter.com\/2\/users\/by\/username\/andrejacobs42" -H "Authorization: Bearer $TW_ACCESS_TOKEN"\n{\n "title": "Unauthorized",\n "type": "about:blank",\n "status": 401,\n "detail": "Unauthorized"\n}\n\n# Next set the TW_ACCESS_TOKEN environment variable to the Bearer Token you received earlier\n$ export TW_ACCESS_TOKEN=My top secret token here\n$ curl "https:\/\/api.twitter.com\/2\/users\/by\/username\/andrejacobs42" -H "Authorization: Bearer $TW_ACCESS_TOKEN"\n{"data":{"id":"69640510","name":"Andr\u00e9 Jacobs","username":"andrejacobs42"}}\n\n# Try and lookup someone famous\n$ curl "https:\/\/api.twitter.com\/2\/users\/by\/username\/elonmusk" -H "Authorization: Bearer $TW_ACCESS_TOKEN"\n{"data":{"id":"44196397","name":"Elon Musk","username":"elonmusk"}}\n<\/code><\/pre>\n
\n
App Access Token<\/code> and can be used in the APIs that support
OAuth 2.0 App-Only<\/code> (mentioned in the Twitter docs).<\/li>\n<\/ul>\n
Posting a Tweet<\/h2>\n
Posting a Tweet using Postman<\/h3>\n
\n
\n
\n
\n
\n
\n
\n
\n
OAuth 2.0 App-Only<\/code> method, I will set only the
bearer_token<\/code>‘s initial and current value to the Bearer token I received from the developer dashboard. NOTE: I also set the type to secret so that it doesn\u2019t appear on screen.<\/li>\n<\/ul>\n
\n
\n
\n
\n
OAuth 1.0a User Context<\/code> method for authentication.\n
\n
\n
\n
\n
\n
Posting a Tweet using Golang<\/h3>\n