@@ -20,10 +20,6 @@ const (
2020 keyringUser = "SLACK_TOKEN"
2121)
2222
23- var (
24- api * slack.Client
25- )
26-
2723func main () {
2824 ctx , cancel := signal .NotifyContext (context .Background (), os .Interrupt , syscall .SIGTERM )
2925 defer cancel ()
@@ -52,44 +48,48 @@ func run(ctx context.Context, args []string) error {
5248
5349 switch args [0 ] {
5450 case "configure" :
55- return configure (ctx )
51+ return configureToken (ctx )
5652 case "send-message" :
5753 if len (args ) < 3 {
5854 return fmt .Errorf ("usage: slack send-message <channel|email> <message>" )
5955 }
6056
61- // Get token from env var first, then fall back to keyring
62- token := os .Getenv ("SLACK_TOKEN" )
63- if token == "" {
64- keyringToken , err := keyring .Get (keyringService , keyringUser )
65- if err == nil && keyringToken != "" {
66- token = keyringToken
67- }
68- }
69-
57+ token := getToken ()
7058 if token == "" {
7159 return fmt .Errorf ("Slack token must be set (use 'slack configure' or set SLACK_TOKEN env var)" )
7260 }
7361
7462 // disable HTTP/2 support as it causes issues with some proxies
7563 http .DefaultTransport .(* http.Transport ).ForceAttemptHTTP2 = false
76- api = slack .New (token )
64+ api : = slack .New (token )
7765
78- return sendMessage (ctx , args [1 ], args [2 ])
66+ return sendMessage (ctx , api , args [1 ], args [2 ])
7967 default :
8068 return fmt .Errorf ("unknown sub-command: %s" , args [0 ])
8169 }
8270}
8371
84- func sendMessage (ctx context.Context , identifier , body string ) error {
72+ func getToken () string {
73+ // Get token from env var first, then fall back to keyring
74+ if token := os .Getenv ("SLACK_TOKEN" ); token != "" {
75+ return token
76+ }
77+
78+ keyringToken , err := keyring .Get (keyringService , keyringUser )
79+ if err == nil && keyringToken != "" {
80+ return keyringToken
81+ }
82+
83+ return ""
84+ }
8585
86+ func sendMessage (ctx context.Context , api * slack.Client , identifier , body string ) error {
8687 var channel string
8788 if strings .Contains (identifier , "@" ) {
8889 user , err := api .GetUserByEmailContext (ctx , identifier )
8990 if err != nil {
9091 return fmt .Errorf ("failed to lookup user: %w" , err )
9192 }
92-
9393 channel = user .ID
9494 } else {
9595 channel = identifier
@@ -106,7 +106,7 @@ func sendMessage(ctx context.Context, identifier, body string) error {
106106 return nil
107107}
108108
109- func configure (ctx context.Context ) error {
109+ func configureToken (ctx context.Context ) error {
110110 fmt .Fprintln (os .Stderr , "Enter your Slack API token:" )
111111
112112 scanner := bufio .NewScanner (os .Stdin )
0 commit comments