package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"google.golang.org/api/sheets/v4"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
)
const (
spreadsheetID = "YOUR_SPREADSHEET_ID"
)
var (
client *http.Client
)
func main() {
ctx := context.Background()
// Step 1: Set up OAuth2 authentication
client = getClient(ctx)
// Step 2: Fetch cryptocurrency price data
cryptoData, err := fetchCryptoData()
if err != nil {
fmt.Println("Error fetching cryptocurrency data:", err)
return
}
// Step 3: Update Google Sheets with cryptocurrency data
err = updateGoogleSheets(ctx, cryptoData)
if err != nil {
fmt.Println("Error updating Google Sheets:", err)
return
}
fmt.Println("Cryptocurrency data updated successfully.")
}
func getClient(ctx context.Context) *http.Client {
b, err := ioutil.ReadFile("credentials.json")
if err != nil {
fmt.Println("Unable to read client secret file:", err)
os.Exit(1)
}
config, err := google.ConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
fmt.Println("Unable to parse client secret file to config:", err)
os.Exit(1)
}
client, err := getClientToken(ctx, config)
if err != nil {
fmt.Println("Unable to get client token:", err)
os.Exit(1)
}
return client
}
func getClientToken(ctx context.Context, config oauth2.Config) (http.Client, error) {
tokenFile := "token.json"
token, err := tokenFromFile(tokenFile)
if err != nil {
token = getTokenFromWeb(config)
saveToken(tokenFile, token)
}
return config.Client(ctx, token), nil
}
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
func getTokenFromWeb(config oauth2.Config) oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
fmt.Println("Unable to read authorization code:", err)
os.Exit(1)
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Println("Unable to retrieve token from web:", err)
os.Exit(1)
}
return tok
}
func saveToken(file string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.Create(file)
if err != nil {
fmt.Printf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
func fetchCryptoData() (map[string]interface{}, error) {
// Implement logic to fetch cryptocurrency price data from your preferred API
// and return the data as a map[string]interface{}
// For example, you can use the CoinGecko API or any other cryptocurrency data source.
// Replace the logic below with your actual implementation.
// Sample implementation (replace with actual logic):
cryptoData := make(map[string]interface{})
cryptoData["bitcoin"] = 45000.0
cryptoData["ethereum"] = 3000.0
// Add more cryptocurrency data as needed
return cryptoData, nil
}
func updateGoogleSheets(ctx context.Context, cryptoData map[string]interface{}) error {
srv, err := sheets.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return err
}
rangeToUpdate := "Sheet1!A1" // Update this with the desired range in your Google Sheets
var values [][]interface{}
for symbol, price := range cryptoData {
values = append(values, []interface{}{symbol, price})
}
valueRange := sheets.ValueRange{
Values: values,
}
_, err = srv.Spreadsheets.Values.Update(spreadsheetID, rangeToUpdate, &valueRange).
ValueInputOption("RAW").
Do()
if err != nil {
return err
}
return nil
}