-
Notifications
You must be signed in to change notification settings - Fork 1
feat(chatops-lark): get bot name from api #245
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3787388
feat: get botname from api first
purelind 0065df8
chore: get botname at server start
purelind cbe7412
docs: update README
purelind 42f728f
update comment
purelind c9ab4f6
update comment
purelind af88709
chore: add some ut to package botinfo
purelind ded783f
chore: more informative message
purelind 5f2dfc9
chore: handle errors better
purelind b94775c
Update log to help users troubleshoot
purelind ba48719
format
purelind File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| package botinfo | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "time" | ||
|
|
||
| "github.com/rs/zerolog/log" | ||
| ) | ||
|
|
||
| // Lark API endpoints | ||
| const ( | ||
| tenantAccessTokenURL = "https://open.larksuite.com/open-apis/auth/v3/tenant_access_token/internal" | ||
| botInfoURL = "https://open.larksuite.com/open-apis/bot/v3/info" | ||
| ) | ||
|
|
||
| // HTTPClient interface for easier testing | ||
| type HTTPClient interface { | ||
| Do(req *http.Request) (*http.Response, error) | ||
| } | ||
|
|
||
| // defaultHTTPClient is the default HTTP client | ||
| var defaultHTTPClient HTTPClient = &http.Client{} | ||
|
|
||
| // setHTTPClient allows setting a custom HTTP client (used for testing) | ||
| func setHTTPClient(client HTTPClient) { | ||
| defaultHTTPClient = client | ||
| } | ||
|
|
||
| // TenantAccessTokenRequest represents the request body for getting a tenant access token | ||
| type TenantAccessTokenRequest struct { | ||
| AppID string `json:"app_id"` | ||
| AppSecret string `json:"app_secret"` | ||
| } | ||
|
|
||
| // TenantAccessTokenResponse represents the response from the tenant access token API | ||
| type TenantAccessTokenResponse struct { | ||
| Code int `json:"code"` | ||
| Msg string `json:"msg"` | ||
| TenantAccessToken string `json:"tenant_access_token"` | ||
| Expire int `json:"expire"` | ||
| } | ||
|
|
||
| // BotInfoResponse represents the response from the bot info API | ||
| type BotInfoResponse struct { | ||
| Code int `json:"code"` | ||
| Msg string `json:"msg"` | ||
| Bot struct { | ||
| ActivateStatus int `json:"activate_status"` | ||
| AppName string `json:"app_name"` | ||
| AvatarURL string `json:"avatar_url"` | ||
| IPWhiteList []string `json:"ip_white_list"` | ||
| OpenID string `json:"open_id"` | ||
| } `json:"bot"` | ||
| } | ||
|
|
||
| // GetBotName fetches the bot name from Lark API using app credentials | ||
| func GetBotName(ctx context.Context, appID, appSecret string) (string, error) { | ||
| logger := log.With().Str("component", "botinfo").Logger() | ||
|
|
||
| ctxWithTimeout, cancel := context.WithTimeout(ctx, 10*time.Second) | ||
purelind marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| defer cancel() | ||
|
|
||
| token, err := getTenantAccessToken(ctxWithTimeout, appID, appSecret) | ||
| if err != nil { | ||
| logger.Err(err).Msg("Failed to get tenant access token") | ||
| return "", fmt.Errorf("failed to get tenant access token: %w", err) | ||
| } | ||
|
|
||
| botInfo, err := getBotInfo(ctxWithTimeout, token) | ||
| if err != nil { | ||
| logger.Err(err).Msg("Failed to get bot info") | ||
| return "", fmt.Errorf("failed to get bot info: %w", err) | ||
| } | ||
|
|
||
| if botInfo.Bot.AppName == "" { | ||
| logger.Warn().Msg("Bot name is empty in API response") | ||
| return "", fmt.Errorf("bot name is empty in API response") | ||
| } | ||
|
|
||
| return botInfo.Bot.AppName, nil | ||
| } | ||
|
|
||
| // getTenantAccessToken gets a tenant access token using app credentials | ||
| func getTenantAccessToken(ctx context.Context, appID, appSecret string) (string, error) { | ||
| reqBody := TenantAccessTokenRequest{ | ||
| AppID: appID, | ||
| AppSecret: appSecret, | ||
| } | ||
|
|
||
| jsonBody, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return "", fmt.Errorf("error marshaling request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "POST", tenantAccessTokenURL, bytes.NewBuffer(jsonBody)) | ||
| if err != nil { | ||
| return "", fmt.Errorf("error creating request: %w", err) | ||
| } | ||
| req.Header.Set("Content-Type", "application/json") | ||
|
|
||
| resp, err := defaultHTTPClient.Do(req) | ||
| if err != nil { | ||
| return "", fmt.Errorf("error making request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return "", fmt.Errorf("error reading response: %w", err) | ||
| } | ||
|
|
||
| var tokenResp TenantAccessTokenResponse | ||
| if err := json.Unmarshal(body, &tokenResp); err != nil { | ||
| return "", fmt.Errorf("error parsing response: %w", err) | ||
| } | ||
|
|
||
| if tokenResp.Code != 0 { | ||
| return "", fmt.Errorf("API error: %s (code: %d)", tokenResp.Msg, tokenResp.Code) | ||
| } | ||
|
|
||
| return tokenResp.TenantAccessToken, nil | ||
| } | ||
|
|
||
| // getBotInfo gets information about the bot using the tenant access token | ||
| func getBotInfo(ctx context.Context, token string) (*BotInfoResponse, error) { | ||
| // Create a new request | ||
| req, err := http.NewRequestWithContext(ctx, "GET", botInfoURL, nil) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error creating request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Add("Authorization", "Bearer "+token) | ||
| req.Header.Add("Content-Type", "application/json") | ||
|
|
||
| resp, err := defaultHTTPClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error making request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error reading response: %w", err) | ||
| } | ||
|
|
||
| var botResp BotInfoResponse | ||
| if err := json.Unmarshal(body, &botResp); err != nil { | ||
| return nil, fmt.Errorf("error parsing response: %w", err) | ||
| } | ||
|
|
||
| if botResp.Code != 0 { | ||
| return nil, fmt.Errorf("API error: %s (code: %d)", botResp.Msg, botResp.Code) | ||
| } | ||
|
|
||
| return &botResp, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.