-
Notifications
You must be signed in to change notification settings - Fork 0
/
twt.go
194 lines (156 loc) · 4.53 KB
/
twt.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bufio"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
)
const (
keysFile = "twitter_keys.json"
)
type TwitterKeys struct {
ConsumerKey string `json:"consumer_key"`
ConsumerSecret string `json:"consumer_secret"`
AccessToken string `json:"access_token"`
AccessTokenSecret string `json:"access_token_secret"`
}
func main() {
fmt.Println("Welcome to TWT ,your GO-to twitter")
fmt.Println("Enter your tweet and we will post it for you.")
fmt.Println("use twc -c to change your twitter keys")
changeKeys := flag.Bool("c", false, "Change Twitter API keys")
flag.Parse()
if *changeKeys {
fmt.Println("Changing Twitter API keys...")
keys := getTwitterKeys()
saveKeys(keys)
fmt.Println("Twitter API keys updated successfully.")
return
}
var keys TwitterKeys
if _, err := os.Stat(keysFile); os.IsNotExist(err) {
fmt.Println("No Twitter API keys found. Please enter your keys:")
keys = getTwitterKeys()
saveKeys(keys)
} else {
keys = loadKeys()
}
fmt.Println("\nEnter your tweet:")
tweet := getUserInput()
response := postTweet(keys, tweet)
fmt.Println("\nResponse from Twitter API:")
fmt.Println(response)
}
func getTwitterKeys() TwitterKeys {
var keys TwitterKeys
fmt.Println("Enter your Consumer Key:")
keys.ConsumerKey = getUserInput()
fmt.Println("Enter your Consumer Secret:")
keys.ConsumerSecret = getUserInput()
fmt.Println("Enter your Access Token:")
keys.AccessToken = getUserInput()
fmt.Println("Enter your Access Token Secret:")
keys.AccessTokenSecret = getUserInput()
return keys
}
func postTweet(keys TwitterKeys, tweet string) string {
url := "https://api.twitter.com/2/tweets"
method := "POST"
payload := strings.NewReader(fmt.Sprintf(`{"text": "%s"}`, tweet))
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
return fmt.Sprintf("Error creating request: %v", err)
}
req.Header.Add("Content-Type", "application/json")
oauthHeader := generateOAuthHeader(method, url, keys.ConsumerKey, keys.ConsumerSecret, keys.AccessToken, keys.AccessTokenSecret)
req.Header.Add("Authorization", oauthHeader)
res, err := client.Do(req)
if err != nil {
return fmt.Sprintf("Error sending request: %v", err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Sprintf("Error reading response body: %v", err)
}
return string(body)
}
func generateOAuthHeader(method, apiUrl, consumerKey, consumerSecret, accessToken, accessTokenSecret string) string {
oauthNonce := generateNonce()
oauthTimestamp := fmt.Sprintf("%d", time.Now().Unix())
oauthParams := map[string]string{
"oauth_consumer_key": consumerKey,
"oauth_nonce": oauthNonce,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": oauthTimestamp,
"oauth_token": accessToken,
"oauth_version": "1.0",
}
allParams := url.Values{}
for key, val := range oauthParams {
allParams.Set(key, val)
}
baseString := method + "&" + url.QueryEscape(apiUrl) + "&" + url.QueryEscape(allParams.Encode())
signingKey := url.QueryEscape(consumerSecret) + "&" + url.QueryEscape(accessTokenSecret)
hmacHash := hmac.New(sha1.New, []byte(signingKey))
hmacHash.Write([]byte(baseString))
signature := base64.StdEncoding.EncodeToString(hmacHash.Sum(nil))
oauthHeader := "OAuth "
for key, val := range oauthParams {
oauthHeader += key + "=\"" + val + "\", "
}
oauthHeader += "oauth_signature=\"" + url.QueryEscape(signature) + "\""
return oauthHeader
}
func generateNonce() string {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
nonce := make([]byte, 32)
for i := range nonce {
nonce[i] = letters[rand.Intn(len(letters))]
}
return string(nonce)
}
func getUserInput() string {
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
return input
}
func saveKeys(keys TwitterKeys) {
data, err := json.MarshalIndent(keys, "", " ")
if err != nil {
fmt.Println("Error:", err)
return
}
err = ioutil.WriteFile(keysFile, data, 0644)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Twitter API keys saved successfully.")
}
func loadKeys() TwitterKeys {
var keys TwitterKeys
data, err := ioutil.ReadFile(keysFile)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
err = json.Unmarshal(data, &keys)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
return keys
}