-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add usage without gramio in files
- Loading branch information
1 parent
2e2da4c
commit 710051c
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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 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,47 @@ | ||
# Usage without GramIO | ||
|
||
## Write you own type-safe TBA API wrapper with File uploading support! | ||
|
||
```ts | ||
import type { ApiMethods, TelegramAPIResponse } from "@gramio/types"; | ||
import { isMediaUpload, convertJsonToFormData } from "@gramio/files"; | ||
import { FormDataEncoder } from "form-data-encoder"; | ||
|
||
const TBA_BASE_URL = "https://api.telegram.org/bot"; | ||
const TOKEN = ""; | ||
|
||
const api = new Proxy({} as ApiMethods, { | ||
get: | ||
<T extends keyof ApiMethods>(_target: ApiMethods, method: T) => | ||
(params: Parameters<ApiMethods[T]>[0]) => { | ||
const reqOptions: RequestInit = { | ||
method: "POST", | ||
duplex: "half", | ||
}; | ||
|
||
if (isMediaUpload(method, params)) { | ||
const formData = await convertJsonToFormData(method, params); | ||
|
||
const encoder = new FormDataEncoder(formData); | ||
|
||
reqOptions.body = encoder.encode(); | ||
reqOptions.headers = encoder.headers; | ||
} else { | ||
reqOptions.headers = { | ||
"Content-Type": "application/json", | ||
}; | ||
reqOptions.body = JSON.stringify(params); | ||
} | ||
|
||
const response = await fetch( | ||
`${TBA_BASE_URL}${TOKEN}/${method}`, | ||
reqOptions | ||
); | ||
|
||
const data = (await response.json()) as TelegramAPIResponse; | ||
if (!data.ok) throw new APIError({ method, params }, data); | ||
|
||
return data.result; | ||
}, | ||
}); | ||
``` |