Skip to content

Usage without GramIO

Write you own type-safe Telegram Bot API wrapper with File uploading support!

ts
import type {
    APIMethods,
    
APIMethodParams
,
TelegramAPIResponse
,
} from "@gramio/types"; import {
request
} from "undici";
import {
isMediaUpload
,
convertJsonToFormData
} from "@gramio/files";
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
) =>
async (
params
:
APIMethodParams
<
T
>) => {
const
reqOptions
:
Parameters
<typeof
request
>[1] = {
method
: "POST",
}; if (
params
&&
isMediaUpload
(
method
,
params
)) {
const
formData
= await
convertJsonToFormData
(
method
,
params
);
reqOptions
.
body
=
formData
;
} else {
reqOptions
.
headers
= {
"Content-Type": "application/json", };
reqOptions
.
body
=
JSON
.
stringify
(
params
);
} const
response
= await
request
(
`${
TBA_BASE_URL
}${
TOKEN
}/${
method
}`,
reqOptions
); const
data
= (await
response
.
body
.
json
()) as
TelegramAPIResponse
;
if (!
data
.
ok
) throw new
Error
(`Some error in ${
method
}`);
return
data
.
result
;
}, });