Twitter - Twitter API with oauth in Golang

twitter: Twitter API with oauth in Golang

GitHub license GoDoc Build Status

Installation and Usage

Install

go get github.com/kkdai/twitter

Usage

Use Desktop Mode OAuth in Twitter

Use Desktop oauth mode to sign in Twitter

package main

import (
    "github.com/kkdai/twitter"
)

const (
	//Get consumer key and secret from https://dev.twitter.com/apps/new
	ConsumerKey string = ""
	ConsumerSecret string = ""
)
func main() {
	twitterClient = NewDesktopClient(ConsumerKey, ConsumerSecret)
	
	//Show a UI to display URL.
	//Please go to this URL to get code to continue
	twitterClient.DoAuth()
	
	//Get timeline only latest one
	timeline, byteData, err :=twitterClient.QueryTimeLine(1)
	
	if err == nil {
		fmt.Println("timeline struct=", timeline, " byteData=", string(byteData) )
	}
}

Use Server Mode OAuth in Twitter (Three-legged Authentication)

Refer to twitter document, use server oauth mode to sign in Twitter

Please note, you might get error if you don't set Callback_URL in twitter setting. You need input valid URL:

  1. Could not be localhost, use other setting in hosts if you want to test it locally.
  2. Must need input any URL otherwise your app will treat as desktop app.
package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"

	. "github.com/kkdai/twitter"
)

var ConsumerKey string
var ConsumerSecret string
var twitterClient *ServerClient

func init() {
	ConsumerKey = os.Getenv("ConsumerKey")
	ConsumerSecret = os.Getenv("ConsumerSecret")
}

const (
	//This URL need note as follow:
	// 1. Could not be localhost, change your hosts to a specific domain name
	// 2. This setting must be identical with your app setting on twitter Dev
	CallbackURL string = "http://YOURDOMAIN.com/maketoken"
)

func main() {

	if ConsumerKey == "" && ConsumerSecret == "" {
		fmt.Println("Please setup ConsumerKey and ConsumerSecret.")
		return
	}

	var port *int = flag.Int(
		"port",
		8888,
		"Port to listen on.")

	flag.Parse()

	fmt.Println("[app] Init server key=", ConsumerKey, " secret=", ConsumerSecret)
	twitterClient = NewServerClient(ConsumerKey, ConsumerSecret)
	http.HandleFunc("/maketoken", GetTwitterToken)
	http.HandleFunc("/request", RedirectUserToTwitter)
	http.HandleFunc("/follow", GetFollower)
	http.HandleFunc("/followids", GetFollowerIDs)
	http.HandleFunc("/time", GetTimeLine)
	http.HandleFunc("/user", GetUserDetail)
	http.HandleFunc("/", MainProcess)

	u := fmt.Sprintf(":%d", *port)
	fmt.Printf("Listening on '%s'\n", u)
	http.ListenAndServe(u, nil)
}

func MainProcess(w http.ResponseWriter, r *http.Request) {

	if !twitterClient.HasAuth() {
		fmt.Fprintf(w, "<BODY><CENTER><A HREF='/request'><IMG SRC='https://g.twimg.com/dev/sites/default/files/images_documentation/sign-in-with-twitter-gray.png'></A></CENTER></BODY>")
		return
	} else {
		//Logon, redirect to display time line
		timelineURL := fmt.Sprintf("http://%s/time", r.Host)
		http.Redirect(w, r, timelineURL, http.StatusTemporaryRedirect)
	}
}

func RedirectUserToTwitter(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Enter redirect to twitter")
	fmt.Println("Token URL=", CallbackURL)
	requestUrl := twitterClient.GetAuthURL(CallbackURL)

	http.Redirect(w, r, requestUrl, http.StatusTemporaryRedirect)
	fmt.Println("Leave redirtect")
}

func GetTimeLine(w http.ResponseWriter, r *http.Request) {
	timeline, bits, _ := twitterClient.QueryTimeLine(1)
	fmt.Println("TimeLine=", timeline)
	fmt.Fprintf(w, "The item is: "+string(bits))

}
func GetTwitterToken(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Enter Get twitter token")
	values := r.URL.Query()
	verificationCode := values.Get("oauth_verifier")
	tokenKey := values.Get("oauth_token")

	twitterClient.CompleteAuth(tokenKey, verificationCode)
	timelineURL := fmt.Sprintf("http://%s/time", r.Host)

	http.Redirect(w, r, timelineURL, http.StatusTemporaryRedirect)
}

func GetFollower(w http.ResponseWriter, r *http.Request) {
	followers, bits, _ := twitterClient.QueryFollower(10)
	fmt.Println("Followers=", followers)
	fmt.Fprintf(w, "The item is: "+string(bits))
}

func GetFollowerIDs(w http.ResponseWriter, r *http.Request) {
	followers, bits, _ := twitterClient.QueryFollowerIDs(10)
	fmt.Println("Follower IDs=", followers)
	fmt.Fprintf(w, "The item is: "+string(bits))
}
func GetUserDetail(w http.ResponseWriter, r *http.Request) {
	followers, bits, _ := twitterClient.QueryFollowerById(2244994945)
	fmt.Println("Follower Detail of =", followers)
	fmt.Fprintf(w, "The item is: "+string(bits))
}

Inspired By

Project52

It is one of my project 52.

License

This package is licensed under MIT license. See LICENSE for details.

Similar Resources

An app/container built in Go to automate a Twitter account using Notion

Notion Tweeter Notion Tweeter is a utility I built using Go to help automate scheduling my tweets using Notion as a backend. More documentation coming

Sep 26, 2022

Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple Weather API Simple weather api app created using golang and Open Weather

Feb 6, 2022

An API client for the Notion API implemented in Golang

An API client for the Notion API implemented in Golang

Dec 30, 2022

A API scanner written in GOLANG to scan files recursively and look for API keys and IDs.

GO FIND APIS _____ ____ ______ _____ _ _ _____ _____ _____ _____ / ____|/ __ \ | ____|_ _| \ | | __ \ /\ | __ \_

Oct 25, 2021

Arweave-api - Arweave API implementation in golang

Arweave API Go implementation of the Arweave API Todo A list of endpoints that a

Jan 16, 2022

Reservationbox-api - Reservationbox Api with golang

Reservationbox-api - Reservationbox Api with golang

reservationbox-api How to set up application Cloning git on this link : https://

Jan 30, 2022

Go api infra - Infrastructure for making api on golang so easy

Go Infra Api Infrastructre methods and types for make api simple Response abstra

Jun 18, 2022

A GoLang wrapper for Politics & War's API. Forego the hassle of accessing the API directly!

A GoLang wrapper for Politics & War's API. Forego the hassle of accessing the API directly!

Mar 5, 2022

Golang API for Whatsapp API MultiDevice version

Golang API for Whatsapp API MultiDevice version

Go Whatsapp API Multi Device Version Required Mac OS: brew install vips export C

Jan 3, 2023
wtf? paranormal twitter.com activity using Twitter Cards. Migros.tr #DoITYourself

GTKE - go-tweet-kart-ele wtf? paranormal twitter.com activity using Twitter Cards. Migros.tr #DoITYourself Just for fun. Go. # You have go. go install

Dec 7, 2021
Go-twitter - Simple Prototype for Twitter with frontend and backend
Go-twitter - Simple Prototype for Twitter with frontend and backend

Twitter Clone Introduction A Twitter clone created with Golang, PostgreSQL, Redi

Feb 21, 2022
Scrape the Twitter Frontend API without authentication with Golang.

Twitter Scraper Twitter's API is annoying to work with, and has lots of limitations — luckily their frontend (JavaScript) has it's own API, which I re

Dec 29, 2022
A Go client library for the Twitter 1.1 API

Anaconda Anaconda is a simple, transparent Go package for accessing version 1.1 of the Twitter API. Successful API queries return native Go structs th

Jan 1, 2023
Go Twitter REST and Streaming API v1.1

go-twitter go-twitter is a Go client library for the Twitter API. Check the usage section or try the examples to see how to access the Twitter API. Fe

Dec 28, 2022
A REST API microservices-based Twitter Clone server.

Simple API Twitter Clone A REST API microservices-based project to fetch, edit, post, and delete tweets. API documentation The API documentation is bu

May 13, 2022
Twitter backend - Golang
Twitter backend - Golang

A Twitter-like Website This repository contains the backend code for the final project of Fall 2020 Internet Engineering course. In this project,

Nov 26, 2022
Twitter ID Finder For Golang

Twitter ID Finder n文字の全数IDを探せます Usage $ make go build -o main main.go $ ./main Twitter ID Finder Creator: @_m_vt Digits: 2 Target IDs: 100 Really? [

Dec 12, 2021
twitter clone front-end for Internet Engineering course - fall 99 built by go+echo

twitter backend build twitter-like back-end for internet engeering course - fall 99 with go+echo+gorm team mates Roozbeh Sharifnasab + Parsa Fadaee +

Nov 9, 2022
Periodically collect data about my Twitter account and check in to github to preserve an audit trail.

Twitter audit trail backup This repository backs up my follower list, following list, blocked accounts list and muted accounts list periodically using

Dec 28, 2022