Created
November 14, 2018 18:29
-
-
Save poy/02fb2b01b455494e143ba0b664dc8c20 to your computer and use it in GitHub Desktop.
bot initiated message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/google" | |
chat "google.golang.org/api/chat/v1" | |
) | |
func main() { | |
// serviceAccountKeyPath is the path to a JSON file. | |
serviceAccountKeyPath := os.Getenv("SERVICE_ACCOUNT_KEY_PATH") | |
if serviceAccountKeyPath == "" { | |
log.Fatal("missing required SERVICE_ACCOUNT_KEY_PATH") | |
} | |
// Parent can be found via the URL (e.g., https://chat.google.com/dm/{ID}) | |
parent := os.Getenv("CHAT_SPACE") | |
if parent == "" { | |
log.Fatal("missing required CHAT_SPACE") | |
} | |
msgText := os.Getenv("MESSAGE_TEXT") | |
if msgText == "" { | |
msgText = "hello world" | |
} | |
service, err := chat.New(getOauthClient(serviceAccountKeyPath)) | |
if err != nil { | |
log.Fatalf("failed to create service client: %s", err) | |
} | |
msgService := chat.NewSpacesMessagesService(service) | |
call := msgService.Create("spaces/"+parent, &chat.Message{ | |
Text: msgText, | |
}) | |
msg, err := call.Do() | |
if err != nil { | |
log.Fatalf("failed to create message: %s", err) | |
} | |
log.Printf("msg: %+v", msg) | |
} | |
func getOauthClient(serviceAccountKeyPath string) *http.Client { | |
ctx := context.Background() | |
data, err := ioutil.ReadFile(serviceAccountKeyPath) | |
if err != nil { | |
log.Fatal(err) | |
} | |
creds, err := google.CredentialsFromJSON(ctx, data, "https://www.googleapis.com/auth/chat.bot") | |
if err != nil { | |
log.Fatal(err) | |
} | |
return oauth2.NewClient(ctx, creds.TokenSource) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment