new request system
This commit is contained in:
47
api.go
47
api.go
@@ -16,6 +16,53 @@ type ApiResponse struct {
|
||||
Result any `json:"result,omitempty"`
|
||||
ErrorCode int `json:"error_code,omitempty"`
|
||||
}
|
||||
type ApiResponseG[R any] struct {
|
||||
Ok bool `json:"ok"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Result R `json:"result,omitempty"`
|
||||
ErrorCode int `json:"error_code,omitempty"`
|
||||
}
|
||||
|
||||
type TelegramRequest[R, P any] struct {
|
||||
method string
|
||||
params P
|
||||
}
|
||||
type EmptyParams struct{}
|
||||
|
||||
func NewRequest[R, P any](method string, params P) TelegramRequest[R, P] {
|
||||
return TelegramRequest[R, P]{
|
||||
method: method,
|
||||
params: params,
|
||||
}
|
||||
}
|
||||
func (r TelegramRequest[R, P]) Do(bot *Bot) (*R, error) {
|
||||
var buf bytes.Buffer
|
||||
err := json.NewEncoder(&buf).Encode(r.params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.Post(fmt.Sprintf("https://api.telegram.org/bot%s/%s", bot.token, r.method), "application/json", &buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer req.Body.Close()
|
||||
data, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response := new(ApiResponseG[R])
|
||||
err = json.Unmarshal(data, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !response.Ok {
|
||||
return nil, fmt.Errorf("[%d] %s", response.ErrorCode, response.Description)
|
||||
}
|
||||
return &response.Result, nil
|
||||
}
|
||||
|
||||
// request is a low-level call to api.
|
||||
func (b *Bot) request(methodName string, params any) (map[string]any, error) {
|
||||
|
||||
Reference in New Issue
Block a user