GetUser fetches the Discord user profile using the access token.
(ctx context.Context, accessToken string)
| 130 | |
| 131 | // GetUser fetches the Discord user profile using the access token. |
| 132 | func GetUser(ctx context.Context, accessToken string) (*DiscordUser, error) { |
| 133 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, discordAPIBase+"/users/@me", nil) |
| 134 | if err != nil { |
| 135 | return nil, fmt.Errorf("discord: create user request: %w", err) |
| 136 | } |
| 137 | req.Header.Set("Authorization", "Bearer "+accessToken) |
| 138 | |
| 139 | client := &http.Client{} |
| 140 | resp, err := client.Do(req) |
| 141 | if err != nil { |
| 142 | return nil, fmt.Errorf("discord: fetch user: %w", err) |
| 143 | } |
| 144 | defer func() { _ = resp.Body.Close() }() |
| 145 | |
| 146 | body, err := io.ReadAll(resp.Body) |
| 147 | if err != nil { |
| 148 | return nil, fmt.Errorf("discord: read user response: %w", err) |
| 149 | } |
| 150 | if resp.StatusCode != http.StatusOK { |
| 151 | return nil, fmt.Errorf("discord: fetch user failed: %s", string(body)) |
| 152 | } |
| 153 | |
| 154 | var u DiscordUser |
| 155 | if err := json.Unmarshal(body, &u); err != nil { |
| 156 | return nil, fmt.Errorf("discord: parse user response: %w", err) |
| 157 | } |
| 158 | return &u, nil |
| 159 | } |
| 160 | |
| 161 | // AvatarURL returns the CDN URL for a Discord user's avatar. |
| 162 | // If avatarHash is empty, returns the default avatar based on user ID. |