-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter.go
51 lines (40 loc) · 1.41 KB
/
twitter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/dghubble/oauth1"
)
// TwitterCredentials stores all access/consumer tokens and secret keys needed
// for authentication against the twitter REST API.
type TwitterCredentials struct {
ConsumerKey string
ConsumerSecret string
AccessToken string
AccessTokenSecret string
}
// Tweet uses twitter credentials to post a tweet using Twitter v2 API.
// https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
func Tweet(text string) {
creds := TwitterCredentials{
AccessToken: os.Getenv("TWITTER_ACCESS_TOKEN"),
AccessTokenSecret: os.Getenv("TWITTER_ACCESS_TOKEN_SECRET"),
ConsumerKey: os.Getenv("TWITTER_CONSUMER_KEY"),
ConsumerSecret: os.Getenv("TWITTER_CONSUMER_SECRET"),
}
config := oauth1.NewConfig(creds.ConsumerKey, creds.ConsumerSecret)
token := oauth1.NewToken(creds.AccessToken, creds.AccessTokenSecret)
httpClient := config.Client(oauth1.NoContext, token)
path := "https://api.twitter.com/2/tweets"
reqBody := []byte(fmt.Sprintf(`{"text": "%s"}`, text))
resp, err := httpClient.Post(path, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
log.Printf("Error making http request to post a tweet %s\n", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
log.Printf("Posted a Tweet")
log.Printf("HTTP Response: %s", string(body))
}