@effect-ak/tg-bot-client 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bot.d.ts +20 -19
- package/dist/bot.js +1 -1
- package/dist/bot.mjs +1 -1
- package/dist/{config-CmVKgghE.d.ts → config-BZUAEyeb.d.ts} +3 -0
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/bot.d.ts
CHANGED
|
@@ -1,10 +1,28 @@
|
|
|
1
|
-
import { U as Update, A as Api, a as TgBotApiToken, T as TgBotClientError } from './config-CmVKgghE.js';
|
|
2
|
-
import * as effect_Cause from 'effect/Cause';
|
|
3
1
|
import * as effect_Types from 'effect/Types';
|
|
2
|
+
import { A as Api, U as Update, a as TgBotApiToken, T as TgBotClientError } from './config-BZUAEyeb.js';
|
|
3
|
+
import * as effect_Cause from 'effect/Cause';
|
|
4
4
|
import * as Micro from 'effect/Micro';
|
|
5
5
|
import * as Data from 'effect/Data';
|
|
6
6
|
import * as Context from 'effect/Context';
|
|
7
7
|
|
|
8
|
+
type BotResult = {
|
|
9
|
+
[K in keyof Api]: K extends `send_${infer R}` ? {
|
|
10
|
+
type: R;
|
|
11
|
+
} & Omit<Parameters<Api[K]>[0], 'chat_id'> : never;
|
|
12
|
+
}[keyof Api];
|
|
13
|
+
declare const BotResponse_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Readonly<A> & {
|
|
14
|
+
readonly _tag: "BotResponse";
|
|
15
|
+
};
|
|
16
|
+
declare class BotResponse extends BotResponse_base<{
|
|
17
|
+
response?: BotResult;
|
|
18
|
+
}> {
|
|
19
|
+
static make(result: BotResult): BotResponse;
|
|
20
|
+
static readonly ignore: BotResponse;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
declare const BotUpdateHandlersTag_base: Context.TagClass<BotUpdateHandlersTag, "BotUpdateHandlers", BotMode>;
|
|
24
|
+
declare class BotUpdateHandlersTag extends BotUpdateHandlersTag_base {
|
|
25
|
+
}
|
|
8
26
|
type PollSettings = {
|
|
9
27
|
log_level: "info" | "debug";
|
|
10
28
|
on_error: "stop" | "continue";
|
|
@@ -28,20 +46,6 @@ type ExtractedUpdate<K extends AvailableUpdateTypes> = {
|
|
|
28
46
|
type: K;
|
|
29
47
|
} & Update[K];
|
|
30
48
|
type AvailableUpdateTypes = Exclude<keyof Update, 'update_id'>;
|
|
31
|
-
type BotResult = {
|
|
32
|
-
[K in keyof Api]: K extends `send_${infer R}` ? {
|
|
33
|
-
type: R;
|
|
34
|
-
} & Omit<Parameters<Api[K]>[0], 'chat_id'> : never;
|
|
35
|
-
}[keyof Api];
|
|
36
|
-
declare const BotResponse_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Readonly<A> & {
|
|
37
|
-
readonly _tag: "BotResponse";
|
|
38
|
-
};
|
|
39
|
-
declare class BotResponse extends BotResponse_base<{
|
|
40
|
-
response?: BotResult;
|
|
41
|
-
}> {
|
|
42
|
-
static make(result: BotResult): BotResponse;
|
|
43
|
-
static readonly ignore: BotResponse;
|
|
44
|
-
}
|
|
45
49
|
type HandleUpdateFunction<U> = (update: U) => BotResponse | PromiseLike<BotResponse>;
|
|
46
50
|
type BotUpdatesHandlers = {
|
|
47
51
|
readonly [K in AvailableUpdateTypes as `on_${K}`]?: HandleUpdateFunction<NonNullable<Update[K]>>;
|
|
@@ -56,9 +60,6 @@ interface BotBatchMode extends HandleBatchUpdateFunction {
|
|
|
56
60
|
type: "batch";
|
|
57
61
|
}
|
|
58
62
|
type BotMode = BotSingleMode | BotBatchMode;
|
|
59
|
-
declare const BotUpdateHandlersTag_base: Context.TagClass<BotUpdateHandlersTag, "BotUpdateHandlers", BotMode>;
|
|
60
|
-
declare class BotUpdateHandlersTag extends BotUpdateHandlersTag_base {
|
|
61
|
-
}
|
|
62
63
|
|
|
63
64
|
declare const extractUpdate: <U extends AvailableUpdateTypes>(input: Update) => ExtractedUpdate<U> | undefined;
|
|
64
65
|
declare class BatchUpdateResult extends Data.Class<{
|
package/dist/bot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ee=Object.create;var T=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty;var se=(e,o)=>{for(var t in o)T(e,t,{get:o[t],enumerable:!0})},P=(e,o,t,r)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of oe(o))!re.call(e,n)&&n!==t&&T(e,n,{get:()=>o[n],enumerable:!(r=te(o,n))||r.enumerable});return e};var c=(e,o,t)=>(t=e!=null?ee(ne(e)):{},P(o||!e||!e.__esModule?T(t,"default",{value:e,enumerable:!0}):t,e)),ie=e=>P(T({},"__esModule",{value:!0}),e);var me={};se(me,{BatchUpdateResult:()=>B,BotPollSettings:()=>x,BotPollSettingsTag:()=>m,BotResponse:()=>_,BotRunService:()=>U,BotUpdateHandlersTag:()=>g,HandleUpdateError:()=>M,defineBot:()=>le,extractUpdate:()=>z,handleEntireBatch:()=>V,handleOneByOne:()=>W,handleOneUpdate:()=>J,handleUpdates:()=>F,launchBot:()=>I,runTgChatBot:()=>de});module.exports=ie(me);var H=c(require("effect/Data")),_=class e extends H.TaggedClass("BotResponse"){static make(o){return new e({response:o})}static ignore=new e({})};var s=c(require("effect/Micro")),v=c(require("effect/Data")),A=c(require("effect/Function"));var K=c(require("effect/String")),u=c(require("effect/Micro"));var D=c(require("effect/Data")),y=class e extends D.TaggedError("TgBotClientError"){static missingSuccess=new e({cause:{type:"ClientInternalError",cause:"Expected 'success' to be defined"}})};var $=e=>typeof e=="object"&&e!=null&&"file_content"in e&&e.file_content instanceof Uint8Array&&"file_name"in e&&typeof e.file_name=="string",N=e=>typeof e=="object"&&e!=null&&"ok"in e&&typeof e.ok=="boolean";var k=c(require("effect/Context"));var O="https://api.telegram.org",C={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},Me=Object.keys(C);var E=class extends k.Reference()("TgBotApiBaseUrl",{defaultValue:()=>O}){},h=class extends k.Tag("TgBotApiToken")(){};var G=e=>{let o=Object.entries(e);if(o.length==0)return;let t=new FormData;for(let[r,n]of o)n&&(typeof n!="object"?t.append(r,`${n}`):$(n)?t.append(r,new Blob([n.file_content]),n.file_name):t.append(r,JSON.stringify(n)));return t};var b=(e,o)=>u.gen(function*(){let t=yield*u.service(h),r=yield*u.service(E),n=yield*u.tryPromise({try:()=>fetch(`${r}/bot${t}/${K.snakeToCamel(e)}`,{body:G(o)??null,method:"POST"}),catch:l=>new y({cause:{type:"ClientInternalError",cause:l}})}),i=yield*u.tryPromise({try:()=>n.json(),catch:()=>new y({cause:{type:"NotJsonResponse",response:n}})});return N(i)?n.ok?i.result:yield*u.fail(new y({cause:{type:"NotOkResponse",...i.error_code?{errorCode:i.error_code}:void 0,...i.description?{details:i.description}:void 0}})):yield*u.fail(new y({cause:{type:"UnexpectedResponse",response:i}}))});var R=c(require("effect/Context")),j=c(require("effect/Data")),g=class extends R.Tag("BotUpdateHandlers")(){},x=class e extends j.Class{static make(o){let t=o.batch_size??10,r=o.poll_timeout??10,n=o.max_empty_responses,i=o.log_level??"info",l=o.on_error;(t<10||t>100)&&(console.warn("Wrong batch_size, must be in [10..100], using 10 instead"),t=10),(r<2||r>120)&&(console.warn("Wrong poll_timeout, must be in [2..120], using 20 instead"),r=20),n&&n<2&&(console.warn("Wrong max_empty_responses, must be in [2..infinity], using infinity"),n=void 0),i||(i="info"),l||(l="stop");let p=new e({batch_size:t,poll_timeout:r,max_empty_responses:n,log_level:i,on_error:l});return console.log("bot poll settings",p),p}},m=class extends R.Reference()("BotSettings",{defaultValue(){return x.make({})}}){};var z=e=>{for(let[o,t]of Object.entries(e))if(o!="update_id")return{type:o,...t}},B=class extends v.Class{},F=e=>s.gen(function*(){let o=yield*s.service(m),t=yield*s.service(g);return t.type=="single"?yield*W(e,t,o):yield*V(e,t)}),V=(e,o)=>s.try({try:()=>o.on_batch(e),catch:A.identity}).pipe(s.andThen(t=>t instanceof Promise?s.tryPromise({try:()=>t,catch:A.identity}):s.succeed(t)),s.andThen(t=>new B({hasErrors:!t,updates:e})),s.catchAll(t=>(console.warn("handle batch error",{errorMessage:t instanceof Error?t.message:void 0,updates:e.map(r=>Object.keys(r).at(1)),error:t}),s.succeed(new B({hasErrors:!0,updates:e}))))),M=class extends v.TaggedError("HandleUpdateError"){},W=(e,o,t)=>s.forEach(e,r=>J(r,o).pipe(s.catchAll(n=>(console.log("update handle error",{updateId:r.update_id,updateKey:Object.keys(r).at(1),name:n._tag,...n.cause instanceof Error?{error:n.cause.message}:void 0}),s.succeed(n)))),{concurrency:10}).pipe(s.andThen(r=>(t.log_level=="debug"&&console.debug("handle batch result",r),new B({hasErrors:!r.every(n=>n==null),updates:e})))),J=(e,o)=>s.gen(function*(){let t=z(e);if(!t)return yield*s.fail(new M({name:"UnknownUpdate",update:e}));let r=o[`on_${t.type}`];if(!r)return yield*s.fail(new M({name:"HandlerNotDefined",update:e}));t.type=="message"&&"text"in t&&console.info("Got a new text message",{chatId:t.chat.id,chatType:t.chat.type,message:`${t.text.slice(0,5)}...`});let n,i=yield*s.try({try:()=>r(t),catch:p=>new M({name:"BotHandlerError",update:e,cause:p})}).pipe(s.andThen(p=>p instanceof Promise?s.tryPromise({try:()=>p,catch:Z=>new M({name:"BotHandlerError",update:e,cause:Z})}):s.succeed(p)),s.catchAll(p=>(n=p,console.log("error",{updateId:e.update_id,updateKey:Object.keys(e).at(1),name:p._tag,...p.cause instanceof Error?{error:p.cause.message}:void 0}),s.succeed(_.make({type:"message",text:`Some internal error has happend(${p.name}) while handling this message`,message_effect_id:C["\u{1F4A9}"],...e.message?.message_id?{reply_parameters:{message_id:e.message?.message_id}}:void 0}))))),l=yield*s.service(m);if(!i&&l.log_level=="debug"){console.log(`Bot response is undefined for update with ID #${e.update_id}.`);return}if("chat"in t&&i.response){let p=yield*b(`send_${i.response.type}`,{...i.response,chat_id:t.chat.id});l.log_level=="debug"&&console.debug("bot response",p)}return n});var f=c(require("effect/Micro")),X=c(require("effect/Context"));var Q=c(require("effect/Context")),a=c(require("effect/Micro"));var L=c(require("effect/Context")),q=c(require("effect/Data")),d=c(require("effect/Micro"));var w=class extends L.Reference()("BotFetchUpdatesService",{defaultValue:()=>{let o={lastUpdateId:void 0,emptyResponses:0},t=ae(o).pipe(d.tap(n=>{let i=n.map(l=>l.update_id).sort().at(-1);console.log("updating last update id",i),o.lastUpdateId=i?i+1:void 0,console.log(o)})),r=ce(o);return{state:o,fetchUpdates:t,commit:r}}}){},S=class extends q.TaggedError("FetchUpdatesError"){},ae=e=>d.gen(function*(){let o=yield*d.service(m);if(o.max_empty_responses&&e.emptyResponses==o.max_empty_responses)return yield*d.fail(new S({name:"TooManyEmptyResponses"}));let t=e.lastUpdateId;o.log_level=="debug"&&console.debug("getting updates",e);let r=yield*b("get_updates",{timeout:o.poll_timeout,...t?{offset:t}:void 0}).pipe(d.andThen(n=>n.sort(i=>i.update_id)));return r.length?(console.debug(`got a batch of updates (${r.length})`),e.emptyResponses=0,r):(e.emptyResponses+=1,[])}),ce=e=>d.gen(function*(){return console.log("commit",{pollState:e}),e.lastUpdateId?yield*b("get_updates",{offset:e.lastUpdateId,limit:0}).pipe(d.andThen(d.andThen(d.service(m),o=>{o.log_level=="debug"&&console.debug("committed offset",e)}))):yield*d.fail(new S({name:"NoUpdatesToCommit"}))});var U=class extends Q.Reference()("BotRunService",{defaultValue:()=>{console.log("Initiating BotRunService");let o={fiber:void 0};return{runBotInBackground:pe(o),getFiber:()=>o.fiber}}}){},pe=e=>a.gen(function*(){console.log("running telegram chat bot");let o=yield*a.service(w),t=yield*a.service(m),r=i=>t.on_error=="continue"?!0:!i,n=a.delay(1e3)(o.fetchUpdates.pipe(a.andThen(F),a.tap(i=>i.updates.length>0&&r(i.hasErrors)?o.commit:a.void))).pipe(a.repeat({while:i=>r(i.hasErrors)}),a.forkDaemon,a.tap(i=>i.addObserver(l=>{console.log("bot's fiber has been closed",l)})));e.fiber&&(console.log("killing previous bot's fiber"),yield*a.fiberInterrupt(e.fiber)),e.fiber=yield*n,console.log("Fetching bot updates via long polling...")});var I=e=>f.gen(function*(){let o=yield*f.service(U),t=X.make(h,e.bot_token);return yield*o.runBotInBackground.pipe(f.provideService(g,e.mode),f.provideService(m,x.make(e.poll??{})),f.provideContext(t)),{reload:n=>o.runBotInBackground.pipe(f.provideService(g,n),f.provideContext(t),f.runPromise),fiber:o.getFiber}});var Y=c(require("effect/Micro"));var de=e=>I(e).pipe(Y.runPromise),le=e=>(Object.keys(e).length==0&&console.warn("No handlers are defined for bot"),e);0&&(module.exports={BatchUpdateResult,BotPollSettings,BotPollSettingsTag,BotResponse,BotRunService,BotUpdateHandlersTag,HandleUpdateError,defineBot,extractUpdate,handleEntireBatch,handleOneByOne,handleOneUpdate,handleUpdates,launchBot,runTgChatBot});
|
package/dist/bot.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as s from"effect/Micro";import*as
|
|
1
|
+
import*as C from"effect/Data";var _=class e extends C.TaggedClass("BotResponse"){static make(o){return new e({response:o})}static ignore=new e({})};import*as s from"effect/Micro";import*as E from"effect/Data";import*as S from"effect/Function";import*as D from"effect/String";import*as f from"effect/Micro";import*as A from"effect/Data";var u=class e extends A.TaggedError("TgBotClientError"){static missingSuccess=new e({cause:{type:"ClientInternalError",cause:"Expected 'success' to be defined"}})};var F=e=>typeof e=="object"&&e!=null&&"file_content"in e&&e.file_content instanceof Uint8Array&&"file_name"in e&&typeof e.file_name=="string",I=e=>typeof e=="object"&&e!=null&&"ok"in e&&typeof e.ok=="boolean";import*as U from"effect/Context";var P="https://api.telegram.org",w={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},ne=Object.keys(w);var b=class extends U.Reference()("TgBotApiBaseUrl",{defaultValue:()=>P}){},y=class extends U.Tag("TgBotApiToken")(){};var H=e=>{let o=Object.entries(e);if(o.length==0)return;let t=new FormData;for(let[r,n]of o)n&&(typeof n!="object"?t.append(r,`${n}`):F(n)?t.append(r,new Blob([n.file_content]),n.file_name):t.append(r,JSON.stringify(n)));return t};var h=(e,o)=>f.gen(function*(){let t=yield*f.service(y),r=yield*f.service(b),n=yield*f.tryPromise({try:()=>fetch(`${r}/bot${t}/${D.snakeToCamel(e)}`,{body:H(o)??null,method:"POST"}),catch:d=>new u({cause:{type:"ClientInternalError",cause:d}})}),i=yield*f.tryPromise({try:()=>n.json(),catch:()=>new u({cause:{type:"NotJsonResponse",response:n}})});return I(i)?n.ok?i.result:yield*f.fail(new u({cause:{type:"NotOkResponse",...i.error_code?{errorCode:i.error_code}:void 0,...i.description?{details:i.description}:void 0}})):yield*f.fail(new u({cause:{type:"UnexpectedResponse",response:i}}))});import*as T from"effect/Context";import*as $ from"effect/Data";var g=class extends T.Tag("BotUpdateHandlers")(){},x=class e extends $.Class{static make(o){let t=o.batch_size??10,r=o.poll_timeout??10,n=o.max_empty_responses,i=o.log_level??"info",d=o.on_error;(t<10||t>100)&&(console.warn("Wrong batch_size, must be in [10..100], using 10 instead"),t=10),(r<2||r>120)&&(console.warn("Wrong poll_timeout, must be in [2..120], using 20 instead"),r=20),n&&n<2&&(console.warn("Wrong max_empty_responses, must be in [2..infinity], using infinity"),n=void 0),i||(i="info"),d||(d="stop");let c=new e({batch_size:t,poll_timeout:r,max_empty_responses:n,log_level:i,on_error:d});return console.log("bot poll settings",c),c}},m=class extends T.Reference()("BotSettings",{defaultValue(){return x.make({})}}){};var J=e=>{for(let[o,t]of Object.entries(e))if(o!="update_id")return{type:o,...t}},B=class extends E.Class{},N=e=>s.gen(function*(){let o=yield*s.service(m),t=yield*s.service(g);return t.type=="single"?yield*q(e,t,o):yield*L(e,t)}),L=(e,o)=>s.try({try:()=>o.on_batch(e),catch:S.identity}).pipe(s.andThen(t=>t instanceof Promise?s.tryPromise({try:()=>t,catch:S.identity}):s.succeed(t)),s.andThen(t=>new B({hasErrors:!t,updates:e})),s.catchAll(t=>(console.warn("handle batch error",{errorMessage:t instanceof Error?t.message:void 0,updates:e.map(r=>Object.keys(r).at(1)),error:t}),s.succeed(new B({hasErrors:!0,updates:e}))))),M=class extends E.TaggedError("HandleUpdateError"){},q=(e,o,t)=>s.forEach(e,r=>Q(r,o).pipe(s.catchAll(n=>(console.log("update handle error",{updateId:r.update_id,updateKey:Object.keys(r).at(1),name:n._tag,...n.cause instanceof Error?{error:n.cause.message}:void 0}),s.succeed(n)))),{concurrency:10}).pipe(s.andThen(r=>(t.log_level=="debug"&&console.debug("handle batch result",r),new B({hasErrors:!r.every(n=>n==null),updates:e})))),Q=(e,o)=>s.gen(function*(){let t=J(e);if(!t)return yield*s.fail(new M({name:"UnknownUpdate",update:e}));let r=o[`on_${t.type}`];if(!r)return yield*s.fail(new M({name:"HandlerNotDefined",update:e}));t.type=="message"&&"text"in t&&console.info("Got a new text message",{chatId:t.chat.id,chatType:t.chat.type,message:`${t.text.slice(0,5)}...`});let n,i=yield*s.try({try:()=>r(t),catch:c=>new M({name:"BotHandlerError",update:e,cause:c})}).pipe(s.andThen(c=>c instanceof Promise?s.tryPromise({try:()=>c,catch:W=>new M({name:"BotHandlerError",update:e,cause:W})}):s.succeed(c)),s.catchAll(c=>(n=c,console.log("error",{updateId:e.update_id,updateKey:Object.keys(e).at(1),name:c._tag,...c.cause instanceof Error?{error:c.cause.message}:void 0}),s.succeed(_.make({type:"message",text:`Some internal error has happend(${c.name}) while handling this message`,message_effect_id:w["\u{1F4A9}"],...e.message?.message_id?{reply_parameters:{message_id:e.message?.message_id}}:void 0}))))),d=yield*s.service(m);if(!i&&d.log_level=="debug"){console.log(`Bot response is undefined for update with ID #${e.update_id}.`);return}if("chat"in t&&i.response){let c=yield*h(`send_${i.response.type}`,{...i.response,chat_id:t.chat.id});d.log_level=="debug"&&console.debug("bot response",c)}return n});import*as l from"effect/Micro";import*as j from"effect/Context";import*as K from"effect/Context";import*as a from"effect/Micro";import*as O from"effect/Context";import*as G from"effect/Data";import*as p from"effect/Micro";var k=class extends O.Reference()("BotFetchUpdatesService",{defaultValue:()=>{let o={lastUpdateId:void 0,emptyResponses:0},t=X(o).pipe(p.tap(n=>{let i=n.map(d=>d.update_id).sort().at(-1);console.log("updating last update id",i),o.lastUpdateId=i?i+1:void 0,console.log(o)})),r=Y(o);return{state:o,fetchUpdates:t,commit:r}}}){},R=class extends G.TaggedError("FetchUpdatesError"){},X=e=>p.gen(function*(){let o=yield*p.service(m);if(o.max_empty_responses&&e.emptyResponses==o.max_empty_responses)return yield*p.fail(new R({name:"TooManyEmptyResponses"}));let t=e.lastUpdateId;o.log_level=="debug"&&console.debug("getting updates",e);let r=yield*h("get_updates",{timeout:o.poll_timeout,...t?{offset:t}:void 0}).pipe(p.andThen(n=>n.sort(i=>i.update_id)));return r.length?(console.debug(`got a batch of updates (${r.length})`),e.emptyResponses=0,r):(e.emptyResponses+=1,[])}),Y=e=>p.gen(function*(){return console.log("commit",{pollState:e}),e.lastUpdateId?yield*h("get_updates",{offset:e.lastUpdateId,limit:0}).pipe(p.andThen(p.andThen(p.service(m),o=>{o.log_level=="debug"&&console.debug("committed offset",e)}))):yield*p.fail(new R({name:"NoUpdatesToCommit"}))});var v=class extends K.Reference()("BotRunService",{defaultValue:()=>{console.log("Initiating BotRunService");let o={fiber:void 0};return{runBotInBackground:Z(o),getFiber:()=>o.fiber}}}){},Z=e=>a.gen(function*(){console.log("running telegram chat bot");let o=yield*a.service(k),t=yield*a.service(m),r=i=>t.on_error=="continue"?!0:!i,n=a.delay(1e3)(o.fetchUpdates.pipe(a.andThen(N),a.tap(i=>i.updates.length>0&&r(i.hasErrors)?o.commit:a.void))).pipe(a.repeat({while:i=>r(i.hasErrors)}),a.forkDaemon,a.tap(i=>i.addObserver(d=>{console.log("bot's fiber has been closed",d)})));e.fiber&&(console.log("killing previous bot's fiber"),yield*a.fiberInterrupt(e.fiber)),e.fiber=yield*n,console.log("Fetching bot updates via long polling...")});var z=e=>l.gen(function*(){let o=yield*l.service(v),t=j.make(y,e.bot_token);return yield*o.runBotInBackground.pipe(l.provideService(g,e.mode),l.provideService(m,x.make(e.poll??{})),l.provideContext(t)),{reload:n=>o.runBotInBackground.pipe(l.provideService(g,n),l.provideContext(t),l.runPromise),fiber:o.getFiber}});import*as V from"effect/Micro";var Pe=e=>z(e).pipe(V.runPromise),He=e=>(Object.keys(e).length==0&&console.warn("No handlers are defined for bot"),e);export{B as BatchUpdateResult,x as BotPollSettings,m as BotPollSettingsTag,_ as BotResponse,v as BotRunService,g as BotUpdateHandlersTag,M as HandleUpdateError,He as defineBot,J as extractUpdate,L as handleEntireBatch,q as handleOneByOne,Q as handleOneUpdate,N as handleUpdates,z as launchBot,Pe as runTgChatBot};
|
|
@@ -3047,6 +3047,9 @@ type ErrorReason = Readonly<{
|
|
|
3047
3047
|
} | {
|
|
3048
3048
|
type: "BotHandlerError";
|
|
3049
3049
|
cause: unknown;
|
|
3050
|
+
} | {
|
|
3051
|
+
type: "NotJsonResponse";
|
|
3052
|
+
response: unknown;
|
|
3050
3053
|
}>;
|
|
3051
3054
|
declare const TgBotClientError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
3052
3055
|
readonly _tag: "TgBotClientError";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as Micro from 'effect/Micro';
|
|
2
|
-
import { A as Api, T as TgBotClientError, a as TgBotApiToken, U as Update } from './config-
|
|
3
|
-
export { bF as AcceptedGiftTypes, c as AddStickerToSetInput, bG as AffiliateInfo, bE as AllowedUpdateName, bH as Animation, d as AnswerCallbackQueryInput, e as AnswerInlineQueryInput, f as AnswerPreCheckoutQueryInput, g as AnswerShippingQueryInput, h as AnswerWebAppQueryInput, i as ApproveChatJoinRequestInput, bI as Audio, bJ as BackgroundFill, bK as BackgroundFillFreeformGradient, bL as BackgroundFillGradient, bM as BackgroundFillSolid, bN as BackgroundType, bO as BackgroundTypeChatTheme, bP as BackgroundTypeFill, bQ as BackgroundTypePattern, bR as BackgroundTypeWallpaper, B as BanChatMemberInput, j as BanChatSenderChatInput, bS as Birthdate, bT as BotCommand, bU as BotCommandScope, bV as BotCommandScopeAllChatAdministrators, bW as BotCommandScopeAllGroupChats, bX as BotCommandScopeAllPrivateChats, bY as BotCommandScopeChat, bZ as BotCommandScopeChatAdministrators, b_ as BotCommandScopeChatMember, b$ as BotCommandScopeDefault, c0 as BotDescription, c1 as BotName, c2 as BotShortDescription, c3 as BusinessBotRights, c4 as BusinessConnection, c5 as BusinessIntro, c6 as BusinessLocation, c7 as BusinessMessagesDeleted, c8 as BusinessOpeningHours, c9 as BusinessOpeningHoursInterval, ca as CallbackGame, cb as CallbackQuery, cc as Chat, cd as ChatAdministratorRights, ce as ChatBackground, cf as ChatBoost, cg as ChatBoostAdded, ch as ChatBoostRemoved, ci as ChatBoostSource, cj as ChatBoostSourceGiftCode, ck as ChatBoostSourceGiveaway, cl as ChatBoostSourcePremium, cm as ChatBoostUpdated, cn as ChatFullInfo, co as ChatInviteLink, cp as ChatJoinRequest, cq as ChatLocation, cr as ChatMember, cs as ChatMemberAdministrator, ct as ChatMemberBanned, cu as ChatMemberLeft, cv as ChatMemberMember, cw as ChatMemberOwner, cx as ChatMemberRestricted, cy as ChatMemberUpdated, cz as ChatPermissions, cA as ChatPhoto, cB as ChatShared, cC as ChosenInlineResult, k as CloseForumTopicInput, l as CloseGeneralForumTopicInput, C as CloseInput, cD as Contact, m as ConvertGiftToStarsInput, n as CopyMessageInput, o as CopyMessagesInput, cE as CopyTextButton, p as CreateChatInviteLinkInput, q as CreateChatSubscriptionInviteLinkInput, r as CreateForumTopicInput, s as CreateInvoiceLinkInput, t as CreateNewStickerSetInput, D as DeclineChatJoinRequestInput, u as DeleteBusinessMessagesInput, v as DeleteChatPhotoInput, w as DeleteChatStickerSetInput, x as DeleteForumTopicInput, y as DeleteMessageInput, z as DeleteMessagesInput, E as DeleteMyCommandsInput, F as DeleteStickerFromSetInput, G as DeleteStickerSetInput, H as DeleteStoryInput, I as DeleteWebhookInput, cF as Dice, cG as Document, J as EditChatInviteLinkInput, K as EditChatSubscriptionInviteLinkInput, L as EditForumTopicInput, M as EditGeneralForumTopicInput, N as EditMessageCaptionInput, O as EditMessageLiveLocationInput, P as EditMessageMediaInput, Q as EditMessageReplyMarkupInput, R as EditMessageTextInput, S as EditStoryInput, V as EditUserStarSubscriptionInput, cH as EncryptedCredentials, cI as EncryptedPassportElement, W as ExportChatInviteLinkInput, cJ as ExternalReplyInfo, cK as File, cL as ForceReply, cM as ForumTopic, cN as ForumTopicClosed, cO as ForumTopicCreated, cP as ForumTopicEdited, cQ as ForumTopicReopened, X as ForwardMessageInput, Y as ForwardMessagesInput, cR as Game, cS as GameHighScore, cT as GeneralForumTopicHidden, cU as GeneralForumTopicUnhidden, Z as GetAvailableGiftsInput, _ as GetBusinessAccountGiftsInput, $ as GetBusinessAccountStarBalanceInput, a0 as GetBusinessConnectionInput, a2 as GetChatAdministratorsInput, a1 as GetChatInput, a4 as GetChatMemberCountInput, a3 as GetChatMemberInput, a5 as GetChatMenuButtonInput, a6 as GetCustomEmojiStickersInput, a7 as GetFileInput, a8 as GetForumTopicIconStickersInput, a9 as GetGameHighScoresInput, aa as GetMeInput, ab as GetMyCommandsInput, ac as GetMyDefaultAdministratorRightsInput, ad as GetMyDescriptionInput, ae as GetMyNameInput, af as GetMyShortDescriptionInput, ag as GetStarTransactionsInput, ah as GetStickerSetInput, ai as GetUpdatesInput, aj as GetUserChatBoostsInput, ak as GetUserProfilePhotosInput, al as GetWebhookInfoInput, cV as Gift, cW as GiftInfo, am as GiftPremiumSubscriptionInput, cX as Gifts, cY as Giveaway, cZ as GiveawayCompleted, c_ as GiveawayCreated, c$ as GiveawayWinners, an as HideGeneralForumTopicInput, d0 as InaccessibleMessage, d1 as InlineKeyboardButton, d2 as InlineKeyboardMarkup, d3 as InlineQuery, d4 as InlineQueryResult, d5 as InlineQueryResultArticle, d6 as InlineQueryResultAudio, d7 as InlineQueryResultCachedAudio, d8 as InlineQueryResultCachedDocument, d9 as InlineQueryResultCachedGif, da as InlineQueryResultCachedMpeg4Gif, db as InlineQueryResultCachedPhoto, dc as InlineQueryResultCachedSticker, dd as InlineQueryResultCachedVideo, de as InlineQueryResultCachedVoice, df as InlineQueryResultContact, dg as InlineQueryResultDocument, dh as InlineQueryResultGame, di as InlineQueryResultGif, dj as InlineQueryResultLocation, dk as InlineQueryResultMpeg4Gif, dl as InlineQueryResultPhoto, dn as InlineQueryResultVenue, dp as InlineQueryResultVideo, dq as InlineQueryResultVoice, dm as InlineQueryResultsButton, dr as InputContactMessageContent, ds as InputFile, dt as InputInvoiceMessageContent, du as InputLocationMessageContent, dv as InputMedia, dw as InputMediaAnimation, dx as InputMediaAudio, dy as InputMediaDocument, dz as InputMediaPhoto, dA as InputMediaVideo, dB as InputMessageContent, dC as InputPaidMedia, dD as InputPaidMediaPhoto, dE as InputPaidMediaVideo, dF as InputPollOption, dG as InputProfilePhoto, dH as InputProfilePhotoAnimated, dI as InputProfilePhotoStatic, dJ as InputSticker, dK as InputStoryContent, dL as InputStoryContentPhoto, dM as InputStoryContentVideo, dN as InputTextMessageContent, dO as InputVenueMessageContent, dP as Invoice, dQ as KeyboardButton, dR as KeyboardButtonPollType, dS as KeyboardButtonRequestChat, dT as KeyboardButtonRequestUsers, dU as LabeledPrice, ao as LeaveChatInput, dV as LinkPreviewOptions, dW as Location, dX as LocationAddress, ap as LogOutInput, dY as LoginUrl, dZ as MaskPosition, d_ as MaybeInaccessibleMessage, d$ as MenuButton, e0 as MenuButtonCommands, e1 as MenuButtonDefault, e2 as MenuButtonWebApp, e3 as Message, e4 as MessageAutoDeleteTimerChanged, e5 as MessageEntity, e6 as MessageId, e7 as MessageOrigin, e8 as MessageOriginChannel, e9 as MessageOriginChat, ea as MessageOriginHiddenUser, eb as MessageOriginUser, ec as MessageReactionCountUpdated, ed as MessageReactionUpdated, ee as OrderInfo, ef as OwnedGift, eg as OwnedGiftRegular, ei as OwnedGiftUnique, eh as OwnedGifts, ej as PaidMedia, ek as PaidMediaInfo, el as PaidMediaPhoto, em as PaidMediaPreview, en as PaidMediaPurchased, eo as PaidMediaVideo, ep as PaidMessagePriceChanged, eq as PassportData, er as PassportElementError, es as PassportElementErrorDataField, et as PassportElementErrorFile, eu as PassportElementErrorFiles, ev as PassportElementErrorFrontSide, ew as PassportElementErrorReverseSide, ex as PassportElementErrorSelfie, ey as PassportElementErrorTranslationFile, ez as PassportElementErrorTranslationFiles, eA as PassportElementErrorUnspecified, eB as PassportFile, eC as PhotoSize, aq as PinChatMessageInput, eD as Poll, eE as PollAnswer, eF as PollOption, ar as PostStoryInput, eG as PreCheckoutQuery, eH as PreparedInlineMessage, as as PromoteChatMemberInput, eI as ProximityAlertTriggered, eJ as ReactionCount, eK as ReactionType, eL as ReactionTypeCustomEmoji, eM as ReactionTypeEmoji, eN as ReactionTypePaid, at as ReadBusinessMessageInput, au as RefundStarPaymentInput, eO as RefundedPayment, av as RemoveBusinessAccountProfilePhotoInput, aw as RemoveChatVerificationInput, ax as RemoveUserVerificationInput, ay as ReopenForumTopicInput, az as ReopenGeneralForumTopicInput, aA as ReplaceStickerInSetInput, eP as ReplyKeyboardMarkup, eQ as ReplyKeyboardRemove, eR as ReplyParameters, eS as ResponseParameters, aB as RestrictChatMemberInput, eT as RevenueWithdrawalState, eU as RevenueWithdrawalStateFailed, eV as RevenueWithdrawalStatePending, eW as RevenueWithdrawalStateSucceeded, aC as RevokeChatInviteLinkInput, aD as SavePreparedInlineMessageInput, aE as SendAnimationInput, aF as SendAudioInput, aG as SendChatActionInput, aH as SendContactInput, aI as SendDiceInput, aJ as SendDocumentInput, aK as SendGameInput, aL as SendGiftInput, aM as SendInvoiceInput, aN as SendLocationInput, aO as SendMediaGroupInput, aP as SendMessageInput, aQ as SendPaidMediaInput, aR as SendPhotoInput, aS as SendPollInput, aT as SendStickerInput, aU as SendVenueInput, aV as SendVideoInput, aW as SendVideoNoteInput, aX as SendVoiceInput, eX as SentWebAppMessage, aY as SetBusinessAccountBioInput, aZ as SetBusinessAccountGiftSettingsInput, a_ as SetBusinessAccountNameInput, a$ as SetBusinessAccountProfilePhotoInput, b0 as SetBusinessAccountUsernameInput, b1 as SetChatAdministratorCustomTitleInput, b2 as SetChatDescriptionInput, b3 as SetChatMenuButtonInput, b4 as SetChatPermissionsInput, b5 as SetChatPhotoInput, b6 as SetChatStickerSetInput, b7 as SetChatTitleInput, b8 as SetCustomEmojiStickerSetThumbnailInput, b9 as SetGameScoreInput, ba as SetMessageReactionInput, bb as SetMyCommandsInput, bc as SetMyDefaultAdministratorRightsInput, bd as SetMyDescriptionInput, be as SetMyNameInput, bf as SetMyShortDescriptionInput, bg as SetPassportDataErrorsInput, bh as SetStickerEmojiListInput, bi as SetStickerKeywordsInput, bj as SetStickerMaskPositionInput, bk as SetStickerPositionInSetInput, bl as SetStickerSetThumbnailInput, bm as SetStickerSetTitleInput, bn as SetUserEmojiStatusInput, bo as SetWebhookInput, eY as SharedUser, eZ as ShippingAddress, e_ as ShippingOption, e$ as ShippingQuery, f0 as StarAmount, f1 as StarTransaction, f2 as StarTransactions, f3 as Sticker, f4 as StickerSet, bp as StopMessageLiveLocationInput, bq as StopPollInput, f5 as Story, f6 as StoryArea, f7 as StoryAreaPosition, f8 as StoryAreaType, f9 as StoryAreaTypeLink, fa as StoryAreaTypeLocation, fb as StoryAreaTypeSuggestedReaction, fc as StoryAreaTypeUniqueGift, fd as StoryAreaTypeWeather, fe as SuccessfulPayment, ff as SwitchInlineQueryChosenChat, fg as TextQuote, b as TgBotApiBaseUrl, fh as TransactionPartner, fi as TransactionPartnerAffiliateProgram, fj as TransactionPartnerChat, fk as TransactionPartnerFragment, fl as TransactionPartnerOther, fm as TransactionPartnerTelegramAds, fn as TransactionPartnerTelegramApi, fo as TransactionPartnerUser, br as TransferBusinessAccountStarsInput, bs as TransferGiftInput, bt as UnbanChatMemberInput, bu as UnbanChatSenderChatInput, bv as UnhideGeneralForumTopicInput, fp as UniqueGift, fq as UniqueGiftBackdrop, fr as UniqueGiftBackdropColors, fs as UniqueGiftInfo, ft as UniqueGiftModel, fu as UniqueGiftSymbol, bw as UnpinAllChatMessagesInput, bx as UnpinAllForumTopicMessagesInput, by as UnpinAllGeneralForumTopicMessagesInput, bz as UnpinChatMessageInput, bA as UpgradeGiftInput, bB as UploadStickerFileInput, fv as User, fw as UserChatBoosts, fx as UserProfilePhotos, fy as UsersShared, fz as Venue, bC as VerifyChatInput, bD as VerifyUserInput, fA as Video, fB as VideoChatEnded, fC as VideoChatParticipantsInvited, fD as VideoChatScheduled, fE as VideoChatStarted, fF as VideoNote, fG as Voice, fH as WebAppData, fI as WebAppInfo, fJ as WebhookInfo, fK as WriteAccessAllowed } from './config-CmVKgghE.js';
|
|
2
|
+
import { A as Api, T as TgBotClientError, a as TgBotApiToken, U as Update } from './config-BZUAEyeb.js';
|
|
3
|
+
export { bF as AcceptedGiftTypes, c as AddStickerToSetInput, bG as AffiliateInfo, bE as AllowedUpdateName, bH as Animation, d as AnswerCallbackQueryInput, e as AnswerInlineQueryInput, f as AnswerPreCheckoutQueryInput, g as AnswerShippingQueryInput, h as AnswerWebAppQueryInput, i as ApproveChatJoinRequestInput, bI as Audio, bJ as BackgroundFill, bK as BackgroundFillFreeformGradient, bL as BackgroundFillGradient, bM as BackgroundFillSolid, bN as BackgroundType, bO as BackgroundTypeChatTheme, bP as BackgroundTypeFill, bQ as BackgroundTypePattern, bR as BackgroundTypeWallpaper, B as BanChatMemberInput, j as BanChatSenderChatInput, bS as Birthdate, bT as BotCommand, bU as BotCommandScope, bV as BotCommandScopeAllChatAdministrators, bW as BotCommandScopeAllGroupChats, bX as BotCommandScopeAllPrivateChats, bY as BotCommandScopeChat, bZ as BotCommandScopeChatAdministrators, b_ as BotCommandScopeChatMember, b$ as BotCommandScopeDefault, c0 as BotDescription, c1 as BotName, c2 as BotShortDescription, c3 as BusinessBotRights, c4 as BusinessConnection, c5 as BusinessIntro, c6 as BusinessLocation, c7 as BusinessMessagesDeleted, c8 as BusinessOpeningHours, c9 as BusinessOpeningHoursInterval, ca as CallbackGame, cb as CallbackQuery, cc as Chat, cd as ChatAdministratorRights, ce as ChatBackground, cf as ChatBoost, cg as ChatBoostAdded, ch as ChatBoostRemoved, ci as ChatBoostSource, cj as ChatBoostSourceGiftCode, ck as ChatBoostSourceGiveaway, cl as ChatBoostSourcePremium, cm as ChatBoostUpdated, cn as ChatFullInfo, co as ChatInviteLink, cp as ChatJoinRequest, cq as ChatLocation, cr as ChatMember, cs as ChatMemberAdministrator, ct as ChatMemberBanned, cu as ChatMemberLeft, cv as ChatMemberMember, cw as ChatMemberOwner, cx as ChatMemberRestricted, cy as ChatMemberUpdated, cz as ChatPermissions, cA as ChatPhoto, cB as ChatShared, cC as ChosenInlineResult, k as CloseForumTopicInput, l as CloseGeneralForumTopicInput, C as CloseInput, cD as Contact, m as ConvertGiftToStarsInput, n as CopyMessageInput, o as CopyMessagesInput, cE as CopyTextButton, p as CreateChatInviteLinkInput, q as CreateChatSubscriptionInviteLinkInput, r as CreateForumTopicInput, s as CreateInvoiceLinkInput, t as CreateNewStickerSetInput, D as DeclineChatJoinRequestInput, u as DeleteBusinessMessagesInput, v as DeleteChatPhotoInput, w as DeleteChatStickerSetInput, x as DeleteForumTopicInput, y as DeleteMessageInput, z as DeleteMessagesInput, E as DeleteMyCommandsInput, F as DeleteStickerFromSetInput, G as DeleteStickerSetInput, H as DeleteStoryInput, I as DeleteWebhookInput, cF as Dice, cG as Document, J as EditChatInviteLinkInput, K as EditChatSubscriptionInviteLinkInput, L as EditForumTopicInput, M as EditGeneralForumTopicInput, N as EditMessageCaptionInput, O as EditMessageLiveLocationInput, P as EditMessageMediaInput, Q as EditMessageReplyMarkupInput, R as EditMessageTextInput, S as EditStoryInput, V as EditUserStarSubscriptionInput, cH as EncryptedCredentials, cI as EncryptedPassportElement, W as ExportChatInviteLinkInput, cJ as ExternalReplyInfo, cK as File, cL as ForceReply, cM as ForumTopic, cN as ForumTopicClosed, cO as ForumTopicCreated, cP as ForumTopicEdited, cQ as ForumTopicReopened, X as ForwardMessageInput, Y as ForwardMessagesInput, cR as Game, cS as GameHighScore, cT as GeneralForumTopicHidden, cU as GeneralForumTopicUnhidden, Z as GetAvailableGiftsInput, _ as GetBusinessAccountGiftsInput, $ as GetBusinessAccountStarBalanceInput, a0 as GetBusinessConnectionInput, a2 as GetChatAdministratorsInput, a1 as GetChatInput, a4 as GetChatMemberCountInput, a3 as GetChatMemberInput, a5 as GetChatMenuButtonInput, a6 as GetCustomEmojiStickersInput, a7 as GetFileInput, a8 as GetForumTopicIconStickersInput, a9 as GetGameHighScoresInput, aa as GetMeInput, ab as GetMyCommandsInput, ac as GetMyDefaultAdministratorRightsInput, ad as GetMyDescriptionInput, ae as GetMyNameInput, af as GetMyShortDescriptionInput, ag as GetStarTransactionsInput, ah as GetStickerSetInput, ai as GetUpdatesInput, aj as GetUserChatBoostsInput, ak as GetUserProfilePhotosInput, al as GetWebhookInfoInput, cV as Gift, cW as GiftInfo, am as GiftPremiumSubscriptionInput, cX as Gifts, cY as Giveaway, cZ as GiveawayCompleted, c_ as GiveawayCreated, c$ as GiveawayWinners, an as HideGeneralForumTopicInput, d0 as InaccessibleMessage, d1 as InlineKeyboardButton, d2 as InlineKeyboardMarkup, d3 as InlineQuery, d4 as InlineQueryResult, d5 as InlineQueryResultArticle, d6 as InlineQueryResultAudio, d7 as InlineQueryResultCachedAudio, d8 as InlineQueryResultCachedDocument, d9 as InlineQueryResultCachedGif, da as InlineQueryResultCachedMpeg4Gif, db as InlineQueryResultCachedPhoto, dc as InlineQueryResultCachedSticker, dd as InlineQueryResultCachedVideo, de as InlineQueryResultCachedVoice, df as InlineQueryResultContact, dg as InlineQueryResultDocument, dh as InlineQueryResultGame, di as InlineQueryResultGif, dj as InlineQueryResultLocation, dk as InlineQueryResultMpeg4Gif, dl as InlineQueryResultPhoto, dn as InlineQueryResultVenue, dp as InlineQueryResultVideo, dq as InlineQueryResultVoice, dm as InlineQueryResultsButton, dr as InputContactMessageContent, ds as InputFile, dt as InputInvoiceMessageContent, du as InputLocationMessageContent, dv as InputMedia, dw as InputMediaAnimation, dx as InputMediaAudio, dy as InputMediaDocument, dz as InputMediaPhoto, dA as InputMediaVideo, dB as InputMessageContent, dC as InputPaidMedia, dD as InputPaidMediaPhoto, dE as InputPaidMediaVideo, dF as InputPollOption, dG as InputProfilePhoto, dH as InputProfilePhotoAnimated, dI as InputProfilePhotoStatic, dJ as InputSticker, dK as InputStoryContent, dL as InputStoryContentPhoto, dM as InputStoryContentVideo, dN as InputTextMessageContent, dO as InputVenueMessageContent, dP as Invoice, dQ as KeyboardButton, dR as KeyboardButtonPollType, dS as KeyboardButtonRequestChat, dT as KeyboardButtonRequestUsers, dU as LabeledPrice, ao as LeaveChatInput, dV as LinkPreviewOptions, dW as Location, dX as LocationAddress, ap as LogOutInput, dY as LoginUrl, dZ as MaskPosition, d_ as MaybeInaccessibleMessage, d$ as MenuButton, e0 as MenuButtonCommands, e1 as MenuButtonDefault, e2 as MenuButtonWebApp, e3 as Message, e4 as MessageAutoDeleteTimerChanged, e5 as MessageEntity, e6 as MessageId, e7 as MessageOrigin, e8 as MessageOriginChannel, e9 as MessageOriginChat, ea as MessageOriginHiddenUser, eb as MessageOriginUser, ec as MessageReactionCountUpdated, ed as MessageReactionUpdated, ee as OrderInfo, ef as OwnedGift, eg as OwnedGiftRegular, ei as OwnedGiftUnique, eh as OwnedGifts, ej as PaidMedia, ek as PaidMediaInfo, el as PaidMediaPhoto, em as PaidMediaPreview, en as PaidMediaPurchased, eo as PaidMediaVideo, ep as PaidMessagePriceChanged, eq as PassportData, er as PassportElementError, es as PassportElementErrorDataField, et as PassportElementErrorFile, eu as PassportElementErrorFiles, ev as PassportElementErrorFrontSide, ew as PassportElementErrorReverseSide, ex as PassportElementErrorSelfie, ey as PassportElementErrorTranslationFile, ez as PassportElementErrorTranslationFiles, eA as PassportElementErrorUnspecified, eB as PassportFile, eC as PhotoSize, aq as PinChatMessageInput, eD as Poll, eE as PollAnswer, eF as PollOption, ar as PostStoryInput, eG as PreCheckoutQuery, eH as PreparedInlineMessage, as as PromoteChatMemberInput, eI as ProximityAlertTriggered, eJ as ReactionCount, eK as ReactionType, eL as ReactionTypeCustomEmoji, eM as ReactionTypeEmoji, eN as ReactionTypePaid, at as ReadBusinessMessageInput, au as RefundStarPaymentInput, eO as RefundedPayment, av as RemoveBusinessAccountProfilePhotoInput, aw as RemoveChatVerificationInput, ax as RemoveUserVerificationInput, ay as ReopenForumTopicInput, az as ReopenGeneralForumTopicInput, aA as ReplaceStickerInSetInput, eP as ReplyKeyboardMarkup, eQ as ReplyKeyboardRemove, eR as ReplyParameters, eS as ResponseParameters, aB as RestrictChatMemberInput, eT as RevenueWithdrawalState, eU as RevenueWithdrawalStateFailed, eV as RevenueWithdrawalStatePending, eW as RevenueWithdrawalStateSucceeded, aC as RevokeChatInviteLinkInput, aD as SavePreparedInlineMessageInput, aE as SendAnimationInput, aF as SendAudioInput, aG as SendChatActionInput, aH as SendContactInput, aI as SendDiceInput, aJ as SendDocumentInput, aK as SendGameInput, aL as SendGiftInput, aM as SendInvoiceInput, aN as SendLocationInput, aO as SendMediaGroupInput, aP as SendMessageInput, aQ as SendPaidMediaInput, aR as SendPhotoInput, aS as SendPollInput, aT as SendStickerInput, aU as SendVenueInput, aV as SendVideoInput, aW as SendVideoNoteInput, aX as SendVoiceInput, eX as SentWebAppMessage, aY as SetBusinessAccountBioInput, aZ as SetBusinessAccountGiftSettingsInput, a_ as SetBusinessAccountNameInput, a$ as SetBusinessAccountProfilePhotoInput, b0 as SetBusinessAccountUsernameInput, b1 as SetChatAdministratorCustomTitleInput, b2 as SetChatDescriptionInput, b3 as SetChatMenuButtonInput, b4 as SetChatPermissionsInput, b5 as SetChatPhotoInput, b6 as SetChatStickerSetInput, b7 as SetChatTitleInput, b8 as SetCustomEmojiStickerSetThumbnailInput, b9 as SetGameScoreInput, ba as SetMessageReactionInput, bb as SetMyCommandsInput, bc as SetMyDefaultAdministratorRightsInput, bd as SetMyDescriptionInput, be as SetMyNameInput, bf as SetMyShortDescriptionInput, bg as SetPassportDataErrorsInput, bh as SetStickerEmojiListInput, bi as SetStickerKeywordsInput, bj as SetStickerMaskPositionInput, bk as SetStickerPositionInSetInput, bl as SetStickerSetThumbnailInput, bm as SetStickerSetTitleInput, bn as SetUserEmojiStatusInput, bo as SetWebhookInput, eY as SharedUser, eZ as ShippingAddress, e_ as ShippingOption, e$ as ShippingQuery, f0 as StarAmount, f1 as StarTransaction, f2 as StarTransactions, f3 as Sticker, f4 as StickerSet, bp as StopMessageLiveLocationInput, bq as StopPollInput, f5 as Story, f6 as StoryArea, f7 as StoryAreaPosition, f8 as StoryAreaType, f9 as StoryAreaTypeLink, fa as StoryAreaTypeLocation, fb as StoryAreaTypeSuggestedReaction, fc as StoryAreaTypeUniqueGift, fd as StoryAreaTypeWeather, fe as SuccessfulPayment, ff as SwitchInlineQueryChosenChat, fg as TextQuote, b as TgBotApiBaseUrl, fh as TransactionPartner, fi as TransactionPartnerAffiliateProgram, fj as TransactionPartnerChat, fk as TransactionPartnerFragment, fl as TransactionPartnerOther, fm as TransactionPartnerTelegramAds, fn as TransactionPartnerTelegramApi, fo as TransactionPartnerUser, br as TransferBusinessAccountStarsInput, bs as TransferGiftInput, bt as UnbanChatMemberInput, bu as UnbanChatSenderChatInput, bv as UnhideGeneralForumTopicInput, fp as UniqueGift, fq as UniqueGiftBackdrop, fr as UniqueGiftBackdropColors, fs as UniqueGiftInfo, ft as UniqueGiftModel, fu as UniqueGiftSymbol, bw as UnpinAllChatMessagesInput, bx as UnpinAllForumTopicMessagesInput, by as UnpinAllGeneralForumTopicMessagesInput, bz as UnpinChatMessageInput, bA as UpgradeGiftInput, bB as UploadStickerFileInput, fv as User, fw as UserChatBoosts, fx as UserProfilePhotos, fy as UsersShared, fz as Venue, bC as VerifyChatInput, bD as VerifyUserInput, fA as Video, fB as VideoChatEnded, fC as VideoChatParticipantsInvited, fD as VideoChatScheduled, fE as VideoChatStarted, fF as VideoNote, fG as Voice, fH as WebAppData, fI as WebAppInfo, fJ as WebhookInfo, fK as WriteAccessAllowed } from './config-BZUAEyeb.js';
|
|
4
4
|
import 'effect/Cause';
|
|
5
5
|
import 'effect/Types';
|
|
6
6
|
import 'effect/Context';
|
|
@@ -23,14 +23,14 @@ declare const getFileBytes: (fileId: string) => Micro.Micro<{
|
|
|
23
23
|
file_name: string;
|
|
24
24
|
}, TgBotClientError, TgBotApiToken>;
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
interface TgBotClient {
|
|
27
|
+
readonly execute: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Promise<ReturnType<Api[M]>>;
|
|
28
|
+
readonly getFile: (input: GetFile) => Promise<File>;
|
|
29
|
+
}
|
|
27
30
|
type MakeTgClient = {
|
|
28
31
|
bot_token: string;
|
|
29
32
|
};
|
|
30
|
-
declare
|
|
31
|
-
execute: <M extends keyof Api>(method: M, input: Parameters<Api[M]>[0]) => Promise<ReturnType<Api[M]>>;
|
|
32
|
-
getFile: (input: GetFile) => Promise<File>;
|
|
33
|
-
};
|
|
33
|
+
declare function makeTgBotClient(config: MakeTgClient): TgBotClient;
|
|
34
34
|
|
|
35
35
|
type FileContent = {
|
|
36
36
|
file_content: Uint8Array;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.create;var g=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var I=(e,o)=>{for(var t in o)g(e,t,{get:o[t],enumerable:!0})},_=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of $(o))!O.call(e,r)&&r!==t&&g(e,r,{get:()=>o[r],enumerable:!(n=v(o,r))||n.enumerable});return e};var l=(e,o,t)=>(t=e!=null?P(j(e)):{},_(o||!e||!e.__esModule?g(t,"default",{value:e,enumerable:!0}):t,e)),D=e=>_(g({},"__esModule",{value:!0}),e);var q={};I(q,{MESSAGE_EFFECTS:()=>C,TG_BOT_API_URL:()=>F,TgBotApiBaseUrl:()=>d,TgBotApiToken:()=>f,TgBotClientError:()=>p,executeTgBotMethod:()=>u,getFile:()=>B,getFileAsBase64String:()=>H,getFileBytes:()=>A,isFileContent:()=>T,isMessageEffect:()=>L,isTgBotApiResponse:()=>k,isTgBotApiUpdate:()=>N,makeTgBotClient:()=>V,messageEffectIdCodes:()=>J});module.exports=D(q);var R=l(require("effect/String")),c=l(require("effect/Micro"));var E=l(require("effect/Data")),p=class e extends E.TaggedError("TgBotClientError"){static missingSuccess=new e({cause:{type:"ClientInternalError",cause:"Expected 'success' to be defined"}})};var T=e=>typeof e=="object"&&e!=null&&"file_content"in e&&e.file_content instanceof Uint8Array&&"file_name"in e&&typeof e.file_name=="string",k=e=>typeof e=="object"&&e!=null&&"ok"in e&&typeof e.ok=="boolean",N=e=>typeof e=="object"&&e!=null&&"update_id"in e&&typeof e.update_id=="number";var x=l(require("effect/Context"));var F="https://api.telegram.org",C={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},J=Object.keys(C),L=e=>typeof e=="string"&&e in C;var d=class extends x.Reference()("TgBotApiBaseUrl",{defaultValue:()=>F}){},f=class extends x.Tag("TgBotApiToken")(){};var h=e=>{let o=Object.entries(e);if(o.length==0)return;let t=new FormData;for(let[n,r]of o)r&&(typeof r!="object"?t.append(n,`${r}`):T(r)?t.append(n,new Blob([r.file_content]),r.file_name):t.append(n,JSON.stringify(r)));return t};var u=(e,o)=>c.gen(function*(){let t=yield*c.service(f),n=yield*c.service(d),r=yield*c.tryPromise({try:()=>fetch(`${n}/bot${t}/${R.snakeToCamel(e)}`,{body:h(o)??null,method:"POST"}),catch:m=>new p({cause:{type:"ClientInternalError",cause:m}})}),a=yield*c.tryPromise({try:()=>r.json(),catch:()=>new p({cause:{type:"NotJsonResponse",response:r}})});return k(a)?r.ok?a.result:yield*c.fail(new p({cause:{type:"NotOkResponse",...a.error_code?{errorCode:a.error_code}:void 0,...a.description?{details:a.description}:void 0}})):yield*c.fail(new p({cause:{type:"UnexpectedResponse",response:a}}))});var s=l(require("effect/Micro"));var B=({fileId:e,type:o})=>A(e).pipe(s.andThen(({content:t,file_name:n})=>new File([t],n,{...o?{type:o}:void 0}))),H=({fileId:e,type:o})=>A(e).pipe(s.andThen(({content:t,file_name:n})=>{let r=Buffer.from(t).toString("base64");return{encoded:`data:${o};base64,${r}`,file_name:n}})),A=e=>s.gen(function*(){let t=(yield*u("get_file",{file_id:e})).file_path;if(!t||t.length==0)return yield*s.fail(new p({cause:{type:"UnableToGetFile",cause:"File path not defined"}}));let n=t.replaceAll("/","-"),r=yield*s.service(d),a=yield*s.service(f),m=`${r}/file/bot${a}/${t}`;return{content:yield*s.tryPromise({try:()=>fetch(m).then(M=>M.arrayBuffer()),catch:M=>new p({cause:{type:"UnableToGetFile",cause:M}})}),file_name:n}});var i=l(require("effect/Micro")),G=l(require("effect/Context"));var S=l(require("effect/Micro")),w=l(require("effect/Context"));var y=class extends w.Tag("ClientFileService")(){},U=S.gen(function*(){return{getFile:B}});function V(e){return i.gen(function*(){let t=yield*i.service(y),n=G.make(f,e.bot_token);return{execute:(m,b)=>u(m,b).pipe(i.provideContext(n),i.runPromise),getFile:m=>t.getFile(m).pipe(i.provideContext(n),i.runPromise)}}).pipe(i.provideServiceEffect(y,U),i.runSync)}0&&(module.exports={MESSAGE_EFFECTS,TG_BOT_API_URL,TgBotApiBaseUrl,TgBotApiToken,TgBotClientError,executeTgBotMethod,getFile,getFileAsBase64String,getFileBytes,isFileContent,isMessageEffect,isTgBotApiResponse,isTgBotApiUpdate,makeTgBotClient,messageEffectIdCodes});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as A from"effect/String";import*as p from"effect/Micro";import*as M from"effect/Data";var a=class e extends M.TaggedError("TgBotClientError"){static missingSuccess=new e({cause:{type:"ClientInternalError",cause:"Expected 'success' to be defined"}})};var T=e=>typeof e=="object"&&e!=null&&"file_content"in e&&e.file_content instanceof Uint8Array&&"file_name"in e&&typeof e.file_name=="string",k=e=>typeof e=="object"&&e!=null&&"ok"in e&&typeof e.ok=="boolean",U=e=>typeof e=="object"&&e!=null&&"update_id"in e&&typeof e.update_id=="number";import*as u from"effect/Context";var F="https://api.telegram.org",C={"\u{1F525}":"5104841245755180586","\u{1F44D}":"5107584321108051014","\u{1F44E}":"5104858069142078462","\u2764\uFE0F":"5159385139981059251","\u{1F389}":"5046509860389126442","\u{1F4A9}":"5046589136895476101"},P=Object.keys(C),v=e=>typeof e=="string"&&e in C;var m=class extends u.Reference()("TgBotApiBaseUrl",{defaultValue:()=>F}){},l=class extends u.Tag("TgBotApiToken")(){};var B=e=>{let s=Object.entries(e);if(s.length==0)return;let t=new FormData;for(let[r,o]of s)o&&(typeof o!="object"?t.append(r,`${o}`):T(o)?t.append(r,new Blob([o.file_content]),o.file_name):t.append(r,JSON.stringify(o)));return t};var y=(e,s)=>p.gen(function*(){let t=yield*p.service(l),r=yield*p.service(m),o=yield*p.tryPromise({try:()=>fetch(`${r}/bot${t}/${A.snakeToCamel(e)}`,{body:B(s)??null,method:"POST"}),catch:f=>new a({cause:{type:"ClientInternalError",cause:f}})}),c=yield*p.tryPromise({try:()=>o.json(),catch:()=>new a({cause:{type:"NotJsonResponse",response:o}})});return k(c)?o.ok?c.result:yield*p.fail(new a({cause:{type:"NotOkResponse",...c.error_code?{errorCode:c.error_code}:void 0,...c.description?{details:c.description}:void 0}})):yield*p.fail(new a({cause:{type:"UnexpectedResponse",response:c}}))});import*as i from"effect/Micro";var b=({fileId:e,type:s})=>_(e).pipe(i.andThen(({content:t,file_name:r})=>new File([t],r,{...s?{type:s}:void 0}))),Q=({fileId:e,type:s})=>_(e).pipe(i.andThen(({content:t,file_name:r})=>{let o=Buffer.from(t).toString("base64");return{encoded:`data:${s};base64,${o}`,file_name:r}})),_=e=>i.gen(function*(){let t=(yield*y("get_file",{file_id:e})).file_path;if(!t||t.length==0)return yield*i.fail(new a({cause:{type:"UnableToGetFile",cause:"File path not defined"}}));let r=t.replaceAll("/","-"),o=yield*i.service(m),c=yield*i.service(l),f=`${o}/file/bot${c}/${t}`;return{content:yield*i.tryPromise({try:()=>fetch(f).then(g=>g.arrayBuffer()),catch:g=>new a({cause:{type:"UnableToGetFile",cause:g}})}),file_name:r}});import*as n from"effect/Micro";import*as S from"effect/Context";import*as E from"effect/Micro";import*as h from"effect/Context";var d=class extends h.Tag("ClientFileService")(){},R=E.gen(function*(){return{getFile:b}});function re(e){return n.gen(function*(){let t=yield*n.service(d),r=S.make(l,e.bot_token);return{execute:(f,x)=>y(f,x).pipe(n.provideContext(r),n.runPromise),getFile:f=>t.getFile(f).pipe(n.provideContext(r),n.runPromise)}}).pipe(n.provideServiceEffect(d,R),n.runSync)}export{C as MESSAGE_EFFECTS,F as TG_BOT_API_URL,m as TgBotApiBaseUrl,l as TgBotApiToken,a as TgBotClientError,y as executeTgBotMethod,b as getFile,Q as getFileAsBase64String,_ as getFileBytes,T as isFileContent,v as isMessageEffect,k as isTgBotApiResponse,U as isTgBotApiUpdate,re as makeTgBotClient,P as messageEffectIdCodes};
|