@effect/chat-telegram 0.0.0 → 4.1.6

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.
Files changed (157) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +122 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/TelegramBotApi.d.ts +153 -0
  88. package/dist/TelegramBotApi.d.ts.map +1 -0
  89. package/dist/TelegramBotApi.js +219 -0
  90. package/dist/TelegramBotApi.js.map +1 -0
  91. package/dist/TelegramChat.d.ts +390 -0
  92. package/dist/TelegramChat.d.ts.map +1 -0
  93. package/dist/TelegramChat.js +359 -0
  94. package/dist/TelegramChat.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +88 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +309 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +26 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/commands.d.ts +2 -0
  112. package/dist/internal/commands.d.ts.map +1 -0
  113. package/dist/internal/commands.js +30 -0
  114. package/dist/internal/commands.js.map +1 -0
  115. package/dist/internal/errors.d.ts +2 -0
  116. package/dist/internal/errors.d.ts.map +1 -0
  117. package/dist/internal/errors.js +136 -0
  118. package/dist/internal/errors.js.map +1 -0
  119. package/dist/internal/markdown.d.ts +9 -0
  120. package/dist/internal/markdown.d.ts.map +1 -0
  121. package/dist/internal/markdown.js +708 -0
  122. package/dist/internal/markdown.js.map +1 -0
  123. package/dist/internal/normalize.d.ts +2 -0
  124. package/dist/internal/normalize.d.ts.map +1 -0
  125. package/dist/internal/normalize.js +276 -0
  126. package/dist/internal/normalize.js.map +1 -0
  127. package/dist/internal/options.d.ts +2 -0
  128. package/dist/internal/options.d.ts.map +1 -0
  129. package/dist/internal/options.js +6 -0
  130. package/dist/internal/options.js.map +1 -0
  131. package/dist/internal/polling.d.ts +2 -0
  132. package/dist/internal/polling.d.ts.map +1 -0
  133. package/dist/internal/polling.js +68 -0
  134. package/dist/internal/polling.js.map +1 -0
  135. package/dist/internal/receive.d.ts +2 -0
  136. package/dist/internal/receive.d.ts.map +1 -0
  137. package/dist/internal/receive.js +183 -0
  138. package/dist/internal/receive.js.map +1 -0
  139. package/dist/internal/webhook.d.ts +2 -0
  140. package/dist/internal/webhook.d.ts.map +1 -0
  141. package/dist/internal/webhook.js +61 -0
  142. package/dist/internal/webhook.js.map +1 -0
  143. package/package.json +65 -1
  144. package/src/TelegramBotApi.ts +282 -0
  145. package/src/TelegramChat.ts +542 -0
  146. package/src/index.ts +18 -0
  147. package/src/internal/actions.ts +95 -0
  148. package/src/internal/adapter.ts +319 -0
  149. package/src/internal/address.ts +33 -0
  150. package/src/internal/commands.ts +37 -0
  151. package/src/internal/errors.ts +148 -0
  152. package/src/internal/markdown.ts +805 -0
  153. package/src/internal/normalize.ts +283 -0
  154. package/src/internal/options.ts +12 -0
  155. package/src/internal/polling.ts +86 -0
  156. package/src/internal/receive.ts +268 -0
  157. package/src/internal/webhook.ts +85 -0
@@ -0,0 +1,319 @@
1
+ import {
2
+ type ChatAdapter,
3
+ checkMessageLength,
4
+ type Descriptor,
5
+ type File,
6
+ type Posted,
7
+ type ThreadInfo
8
+ } from "effect/chat/ChatAdapter"
9
+ import { type Capability, type ChatError, interactionExpired } from "effect/chat/ChatError"
10
+ import type * as ChatInteraction from "effect/chat/ChatInteraction"
11
+ import type { ChatThread } from "effect/chat/ChatThread"
12
+ import type * as ChatUi from "effect/chat/ChatUi"
13
+ import * as DateTime from "effect/DateTime"
14
+ import * as Duration from "effect/Duration"
15
+ import * as Effect from "effect/Effect"
16
+ import * as Option from "effect/Option"
17
+ import * as Stream from "effect/Stream"
18
+ import type { TelegramBotApi } from "../TelegramBotApi.ts"
19
+ import * as Actions from "./actions.ts"
20
+ import * as Address from "./address.ts"
21
+ import * as Errors from "./errors.ts"
22
+ import * as Markdown from "./markdown.ts"
23
+ import { displayName, fullName, integer, messageOf, object, string } from "./normalize.ts"
24
+ import { CurrentPostOptions, type PostOptions } from "./options.ts"
25
+
26
+ /** Capabilities that are built but not yet confirmed against Telegram. @internal */
27
+ export interface Unverified {
28
+ readonly files?: boolean | undefined
29
+ readonly buttons?: boolean | undefined
30
+ readonly commands?: boolean | undefined
31
+ }
32
+
33
+ /** @internal */
34
+ export const capabilitiesOf = (unverified: Unverified): ReadonlySet<Capability> => {
35
+ const set = new Set<Capability>(["edit", "delete", "replyTo", "download", "getThread", "getUser"])
36
+ if (unverified.files === true) set.add("files")
37
+ if (unverified.buttons === true) set.add("buttons")
38
+ if (unverified.commands === true) set.add("commands")
39
+ return set
40
+ }
41
+
42
+ /** How long Telegram takes an answer to a command, from the command's `date`. @internal */
43
+ export const followUpAge = Duration.seconds(15)
44
+
45
+ /** The largest file the cloud Bot API server hands out. @internal */
46
+ export const downloadLimit = 20 * 1024 * 1024
47
+
48
+ /** @internal */
49
+ export const descriptorOf = (capabilities: ReadonlySet<Capability>): Descriptor => ({
50
+ platform: Address.platform,
51
+ capabilities,
52
+ measure: (markdown) => Markdown.measure(markdown),
53
+ limits: {
54
+ messageLength: Markdown.messageLength,
55
+ filesPerMessage: capabilities.has("files") ? Markdown.filesPerMessage : 0,
56
+ uploadBytes: 50 * 1024 * 1024,
57
+ minWriteInterval: Duration.seconds(3),
58
+ ...(capabilities.has("buttons")
59
+ ? { actionsPerMessage: Actions.actionsPerMessage, actionDataLength: Actions.actionDataLength }
60
+ : {}),
61
+ ...(capabilities.has("commands") ? { followUpAge } : {})
62
+ }
63
+ })
64
+
65
+ /** Where a command's answer goes: the chat it came from, and the message to reply to, if any. @internal */
66
+ export interface Origin {
67
+ readonly thread: ChatThread
68
+ readonly replyTo?: number | undefined
69
+ /** The command's `date`, in seconds. */
70
+ readonly date: number
71
+ }
72
+
73
+ /**
74
+ * Where a command's answers go. A reply to an ephemeral command would have
75
+ * to be ephemeral itself, and a reply would quote the private prompt, so
76
+ * a public answer to one is a new post.
77
+ *
78
+ * @internal
79
+ */
80
+ export const originOf = (command: ChatInteraction.CommandInvoked): Origin | undefined => {
81
+ const message = messageOf(command.raw)
82
+ const id = integer(message, "message_id")
83
+ const date = integer(message, "date")
84
+ if (id === undefined || date === undefined) return undefined
85
+ return { thread: command.thread, ...(id === 0 ? {} : { replyTo: id }), date }
86
+ }
87
+
88
+ /** @internal */
89
+ export const make = (options: {
90
+ readonly api: TelegramBotApi["Service"]
91
+ readonly capabilities: ReadonlySet<Capability>
92
+ }) => {
93
+ const { api, capabilities } = options
94
+ const descriptor = descriptorOf(capabilities)
95
+
96
+ const unsupported = (op: string, capability: Capability) => Errors.fail(op, Errors.unsupported(capability))
97
+
98
+ const resolve = (op: string, thread: ChatThread): Effect.Effect<Address.Parts, ChatError> => {
99
+ const parts = Address.parts(thread)
100
+ return Option.isNone(parts) ? Errors.fail(op, Errors.invalidRequest("invalid_thread")) : Effect.succeed(parts.value)
101
+ }
102
+
103
+ const target = (parts: Address.Parts) => ({
104
+ chat_id: Number(parts.chatId),
105
+ ...(parts.messageThreadId === undefined ? {} : { message_thread_id: Number(parts.messageThreadId) })
106
+ })
107
+
108
+ /** A message id Telegram can act on, or `NotFound` without a call: a private answer's label reaches nothing. */
109
+ const messageId = (op: string, id: string): Effect.Effect<number, ChatError> => {
110
+ const n = Address.numericId(id)
111
+ return n === undefined ? Errors.fail(op, Errors.notFound("message_not_found")) : Effect.succeed(n)
112
+ }
113
+
114
+ const markup = (op: string, actions: ReadonlyArray<ChatUi.Action>) => {
115
+ if (actions.length === 0) return Effect.succeed(undefined)
116
+ if (actions.some((action) => action._tag === "Select")) return unsupported(op, "selects")
117
+ if (!capabilities.has("buttons")) return unsupported(op, "buttons")
118
+ const keyboard = Actions.keyboard(actions)
119
+ return "inline_keyboard" in keyboard ? Effect.succeed(keyboard) : Errors.fail(op, keyboard)
120
+ }
121
+
122
+ const checkFiles = (op: string, files: ReadonlyArray<File>) => {
123
+ if (files.length === 0) return Effect.void
124
+ if (!capabilities.has("files")) return unsupported(op, "files")
125
+ const refused = files.length > descriptor.limits.filesPerMessage ||
126
+ files.some((file) => file.content.length > descriptor.limits.uploadBytes)
127
+ return refused ? Errors.fail(op, Errors.refusedFile) : Effect.void
128
+ }
129
+
130
+ const richMessage = (markdown: string, files: number, postOptions: PostOptions) => ({
131
+ markdown: Markdown.render(markdown, { mentions: new Set(postOptions.notify?.users ?? []), files }),
132
+ skip_entity_detection: true,
133
+ ...(files === 0 ? {} : {
134
+ media: Array.from({ length: files }, (_, i) => ({
135
+ id: `f${i + 1}`,
136
+ media: { type: "document", media: `attach://f${i + 1}` }
137
+ }))
138
+ })
139
+ })
140
+
141
+ const posted = (op: string, thread: ChatThread, answer: unknown): Effect.Effect<Posted, ChatError> => {
142
+ const id = integer(answer, "message_id")
143
+ const date = integer(answer, "date")
144
+ if (id === undefined || id === 0) return Errors.fail(op, Errors.invalidResponse(true, "missing_message_id"))
145
+ return Effect.map(
146
+ date === undefined ? DateTime.now : Effect.succeed(DateTime.makeUnsafe(date * 1000)),
147
+ (timestamp) => ({ id: String(id), thread, timestamp })
148
+ )
149
+ }
150
+
151
+ /** One `sendRichMessage`. `retry` false for answers, which are never retried. */
152
+ const send = Effect.fnUntraced(function*(op: string, thread: ChatThread, content: {
153
+ readonly markdown: string
154
+ readonly actions?: ReadonlyArray<ChatUi.Action> | undefined
155
+ readonly files?: ReadonlyArray<File> | undefined
156
+ readonly replyTo?: number | undefined
157
+ readonly retry?: boolean | undefined
158
+ }) {
159
+ const parts = yield* resolve(op, thread)
160
+ const actions = content.actions ?? []
161
+ const files = content.files ?? []
162
+ const replyMarkup = yield* markup(op, actions)
163
+ yield* checkFiles(op, files)
164
+ yield* checkMessageLength(descriptor, op, content.markdown, actions)
165
+ if (content.markdown.trim() === "" && files.length === 0) {
166
+ return yield* Errors.fail(op, Errors.invalidRequest("empty_message"))
167
+ }
168
+ const postOptions = yield* CurrentPostOptions
169
+ const answer = yield* api.call("sendRichMessage", {
170
+ ...target(parts),
171
+ rich_message: richMessage(content.markdown, files.length, postOptions),
172
+ ...(content.replyTo === undefined
173
+ ? {}
174
+ : { reply_parameters: { message_id: content.replyTo, allow_sending_without_reply: false } }),
175
+ ...(replyMarkup === undefined ? {} : { reply_markup: replyMarkup }),
176
+ ...(postOptions.silent === true ? { disable_notification: true } : {})
177
+ }, {
178
+ write: true,
179
+ retry: content.retry,
180
+ files: files.map((file, i) => ({ field: `f${i + 1}`, file }))
181
+ }).pipe(Effect.mapError(Errors.withOp(op)))
182
+ return yield* posted(op, thread, answer)
183
+ })
184
+
185
+ const post: ChatAdapter["post"] = Effect.fnUntraced(function*(thread, content) {
186
+ const replyTo = content.replyTo === undefined ? undefined : yield* messageId("post", content.replyTo.messageId)
187
+ return yield* send("post", thread, { ...content, replyTo })
188
+ })
189
+
190
+ const edit: ChatAdapter["edit"] = Effect.fnUntraced(function*(thread, id, content) {
191
+ const op = "edit"
192
+ const parts = yield* resolve(op, thread)
193
+ const message = yield* messageId(op, id)
194
+ const actions = content.actions ?? []
195
+ const replyMarkup = yield* markup(op, actions)
196
+ yield* checkMessageLength(descriptor, op, content.markdown, actions)
197
+ if (content.markdown.trim() === "") return yield* Errors.fail(op, Errors.invalidRequest("empty_message"))
198
+ yield* api.call("editMessageText", {
199
+ chat_id: Number(parts.chatId),
200
+ message_id: message,
201
+ rich_message: richMessage(content.markdown, 0, yield* CurrentPostOptions),
202
+ // An edit replaces the whole message: no actions removes the keyboard.
203
+ reply_markup: replyMarkup ?? { inline_keyboard: [] }
204
+ }, { write: true }).pipe(
205
+ Effect.catchIf(
206
+ (error) => error.reason._tag === "InvalidRequest" && error.reason.detail === "not_modified",
207
+ () => Effect.void
208
+ ),
209
+ Effect.mapError(Errors.withOp(op))
210
+ )
211
+ })
212
+
213
+ const deleteMessage: ChatAdapter["delete"] = Effect.fnUntraced(function*(thread, id) {
214
+ const op = "delete"
215
+ const parts = yield* resolve(op, thread)
216
+ const message = yield* messageId(op, id)
217
+ yield* api.call("deleteMessage", { chat_id: Number(parts.chatId), message_id: message }, { write: true }).pipe(
218
+ Effect.mapError(Errors.withOp(op))
219
+ )
220
+ })
221
+
222
+ const download: ChatAdapter["download"] = (thread, attachment, { maxBytes }) =>
223
+ Stream.unwrap(Effect.gen(function*() {
224
+ const op = "download"
225
+ yield* resolve(op, thread)
226
+ const limit = Math.min(maxBytes, downloadLimit)
227
+ const tooLarge = Errors.tooLarge("files", "max_bytes")
228
+ if (attachment.size !== undefined && attachment.size > limit) return yield* Errors.fail(op, tooLarge)
229
+ const answer = yield* api.call("getFile", { file_id: attachment.id }).pipe(Effect.mapError(Errors.withOp(op)))
230
+ const path = string(answer, "file_path")
231
+ const size = integer(answer, "file_size")
232
+ if (size !== undefined && size > limit) return yield* Errors.fail(op, tooLarge)
233
+ if (path === undefined) return yield* Errors.fail(op, Errors.invalidResponse(false, "missing_file_path"))
234
+ return api.file(path, { maxBytes: limit })
235
+ }))
236
+
237
+ const getThread: ChatAdapter["getThread"] = Effect.fnUntraced(function*(thread) {
238
+ const op = "getThread"
239
+ const parts = yield* resolve(op, thread)
240
+ const answer = yield* api.call("getChat", { chat_id: Number(parts.chatId) }).pipe(
241
+ Effect.mapError(Errors.withOp(op))
242
+ )
243
+ if (parts.messageThreadId !== undefined) {
244
+ return { thread, kind: "thread", parent: Address.thread(parts.chatId), raw: answer } satisfies ThreadInfo
245
+ }
246
+ const name = string(answer, "title") ?? (fullName(answer) || undefined)
247
+ const topic = string(answer, "description")
248
+ return {
249
+ thread,
250
+ kind: string(answer, "type") === "private" ? "direct" : "channel",
251
+ ...(name === undefined ? {} : { name }),
252
+ ...(topic === undefined ? {} : { topic }),
253
+ raw: answer
254
+ } satisfies ThreadInfo
255
+ })
256
+
257
+ const getUser: ChatAdapter["getUser"] = Effect.fnUntraced(function*(id, userOptions) {
258
+ const op = "getUser"
259
+ if (userOptions?.in === undefined) return yield* Errors.fail(op, Errors.invalidRequest("in_required"))
260
+ const parts = yield* resolve(op, userOptions.in)
261
+ const userId = Address.numericId(id)
262
+ if (userId === undefined) return yield* Errors.fail(op, Errors.notFound("user_not_found"))
263
+ const answer = yield* api.call("getChatMember", { chat_id: Number(parts.chatId), user_id: userId }).pipe(
264
+ Effect.mapError(Errors.withOp(op))
265
+ )
266
+ const user = object(answer, "user")
267
+ if (user === undefined || String(integer(user, "id")) !== id) {
268
+ return yield* Errors.fail(op, Errors.invalidResponse(false, "missing_user"))
269
+ }
270
+ return {
271
+ id,
272
+ name: displayName(user) ?? id,
273
+ isBot: user.is_bot === true,
274
+ isSelf: id === api.botId,
275
+ raw: answer
276
+ }
277
+ })
278
+
279
+ /** A public answer to a command. Never retried, so a timeout can't post it twice. @internal */
280
+ const answer = (op: string, origin: Origin, content: {
281
+ readonly markdown: string
282
+ readonly actions?: ReadonlyArray<ChatUi.Action> | undefined
283
+ }): Effect.Effect<Posted, ChatError> =>
284
+ send(op, origin.thread, { ...content, replyTo: origin.replyTo, retry: false }).pipe(
285
+ Effect.provideService(CurrentPostOptions, {})
286
+ )
287
+
288
+ const followUp: ChatAdapter["followUp"] = Effect.fnUntraced(function*(deferred, content) {
289
+ const op = "followUp"
290
+ if (!capabilities.has("commands")) return yield* unsupported(op, "commands")
291
+ if (deferred.visibility === "ephemeral") return yield* unsupported(op, "ephemeral")
292
+ const origin = originOf(deferred.command)
293
+ if (origin === undefined) return yield* Errors.fail(op, Errors.invalidRequest("invalid_command"))
294
+ const now = yield* DateTime.now
295
+ const deadline = (origin.date + 1) * 1000 + Duration.toMillis(followUpAge)
296
+ if (DateTime.toEpochMillis(now) > deadline) return yield* Errors.fail(op, Errors.notFound(interactionExpired))
297
+ yield* answer(op, origin, content)
298
+ })
299
+
300
+ const adapter: ChatAdapter = {
301
+ descriptor,
302
+ post,
303
+ edit,
304
+ delete: deleteMessage,
305
+ fetchMessage: () => unsupported("fetchMessage", "fetchMessage"),
306
+ history: () => Stream.fail(Errors.chatError("history", Errors.unsupported("history"))),
307
+ download,
308
+ startThread: () => unsupported("startThread", "startThread"),
309
+ getThread,
310
+ opener: () => unsupported("opener", "opener"),
311
+ getUser,
312
+ followUp
313
+ }
314
+
315
+ return { adapter, answer }
316
+ }
317
+
318
+ /** @internal */
319
+ export type Made = ReturnType<typeof make>
@@ -0,0 +1,33 @@
1
+ import * as ChatThread from "effect/chat/ChatThread"
2
+ import * as Option from "effect/Option"
3
+
4
+ /** @internal */
5
+ export const platform = "telegram"
6
+
7
+ const chatId = /^-?[1-9]\d{0,15}$/
8
+ const topicId = /^[1-9]\d{0,9}$/
9
+
10
+ /** The address of a chat, or of a topic in it. @internal */
11
+ export const thread = (chat: string | number, messageThreadId?: string | number | undefined): ChatThread.ChatThread =>
12
+ ChatThread.make(platform, messageThreadId === undefined ? String(chat) : `${chat}/${messageThreadId}`)
13
+
14
+ /** The parts of an address. @internal */
15
+ export interface Parts {
16
+ readonly chatId: string
17
+ readonly messageThreadId?: string | undefined
18
+ }
19
+
20
+ /** @internal */
21
+ export const parts = (address: ChatThread.ChatThread): Option.Option<Parts> => {
22
+ if (address.platform !== platform) return Option.none()
23
+ const [chat, topic, ...rest] = address.id.split("/")
24
+ if (rest.length > 0 || !chatId.test(chat)) return Option.none()
25
+ if (topic === undefined) return Option.some({ chatId: chat })
26
+ return topicId.test(topic) ? Option.some({ chatId: chat, messageThreadId: topic }) : Option.none()
27
+ }
28
+
29
+ /** The prefix of the label a private answer's message id gets: `e{ephemeral_message_id}.{date}`. @internal */
30
+ export const ephemeralPrefix = "e"
31
+
32
+ /** A message or user id as Telegram takes it, or undefined. @internal */
33
+ export const numericId = (id: string): number | undefined => /^[1-9]\d{0,15}$/.test(id) ? Number(id) : undefined
@@ -0,0 +1,37 @@
1
+ import type * as ChatInteraction from "effect/chat/ChatInteraction"
2
+
3
+ /** @internal */
4
+ export interface BotCommand {
5
+ readonly command: string
6
+ readonly description: string
7
+ }
8
+
9
+ /**
10
+ * The `commands` of `setMyCommands` for a group's command definitions, or
11
+ * the ids Telegram can't take: its names are `[a-z0-9_]{1,32}`. A
12
+ * command's `argument` has no Telegram counterpart and is appended to its
13
+ * description, cut to 256 characters.
14
+ *
15
+ * @internal
16
+ */
17
+ export const botCommands = (
18
+ group: ChatInteraction.Group<any>
19
+ ): { readonly commands: ReadonlyArray<BotCommand> } | { readonly invalid: ReadonlyArray<string> } => {
20
+ const commands: Array<BotCommand> = []
21
+ const invalid: Array<string> = []
22
+ for (const definition of (group.definitions as ReadonlyMap<string, ChatInteraction.Definition>).values()) {
23
+ if (definition.kind !== "command") continue
24
+ if (!/^[a-z0-9_]{1,32}$/.test(definition.id)) {
25
+ invalid.push(definition.id)
26
+ continue
27
+ }
28
+ const argument = definition.argument === undefined
29
+ ? ""
30
+ : ` <${definition.argument.name}${definition.argument.required ? "" : "?"}>: ${definition.argument.description}`
31
+ commands.push({
32
+ command: definition.id,
33
+ description: Array.from(definition.description + argument).slice(0, 256).join("")
34
+ })
35
+ }
36
+ return invalid.length > 0 ? { invalid } : { commands }
37
+ }
@@ -0,0 +1,148 @@
1
+ import {
2
+ type Capability,
3
+ ChatError,
4
+ type ChatErrorReason,
5
+ fileRefused,
6
+ Forbidden,
7
+ InvalidRequest,
8
+ InvalidResponse,
9
+ NotFound,
10
+ PlatformUnavailable,
11
+ RateLimited,
12
+ TooLarge,
13
+ Transport,
14
+ Unauthenticated,
15
+ Unknown,
16
+ Unsupported
17
+ } from "effect/chat/ChatError"
18
+ import * as Duration from "effect/Duration"
19
+ import * as Effect from "effect/Effect"
20
+ import { isObject } from "effect/Predicate"
21
+ import { platform } from "./address.ts"
22
+
23
+ /** @internal */
24
+ export const chatError = (op: string, reason: ChatErrorReason): ChatError => new ChatError({ platform, op, reason })
25
+
26
+ /** @internal */
27
+ export const fail = (op: string, reason: ChatErrorReason): Effect.Effect<never, ChatError> =>
28
+ Effect.fail(chatError(op, reason))
29
+
30
+ /** @internal */
31
+ export const withOp = (op: string) => (error: ChatError): ChatError => chatError(op, error.reason)
32
+
33
+ /** @internal */
34
+ export const unsupported = (capability: Capability): ChatErrorReason => new Unsupported({ capability })
35
+
36
+ /** @internal */
37
+ export const invalidRequest = (detail: string): ChatErrorReason => new InvalidRequest({ detail })
38
+
39
+ /** @internal */
40
+ export const notFound = (detail: string): ChatErrorReason => new NotFound({ detail })
41
+
42
+ /** @internal */
43
+ export const tooLarge = (subject: "text" | "files" | undefined, detail: string): ChatErrorReason =>
44
+ new TooLarge({ ...(subject === undefined ? {} : { subject }), detail })
45
+
46
+ /** @internal */
47
+ export const unauthenticatedToken: ChatErrorReason = new Unauthenticated({ detail: "invalid_token" })
48
+
49
+ /** @internal */
50
+ export const refusedFile: ChatErrorReason = new TooLarge({ subject: "files", detail: fileRefused })
51
+
52
+ /** The error Telegram answers with, without its description. @internal */
53
+ export interface ApiError {
54
+ readonly code: number
55
+ readonly description: string
56
+ readonly retryAfter?: number | undefined
57
+ readonly migrateTo?: number | undefined
58
+ }
59
+
60
+ /** The error in a body that says `ok: false`, or undefined. @internal */
61
+ export const apiError = (body: unknown, status: number): ApiError | undefined => {
62
+ if (!isObject(body) || body.ok !== false) return undefined
63
+ const parameters = isObject(body.parameters) ? body.parameters : {}
64
+ return {
65
+ code: typeof body.error_code === "number" ? body.error_code : status,
66
+ description: typeof body.description === "string" ? body.description.toLowerCase() : "",
67
+ ...(typeof parameters.retry_after === "number" ? { retryAfter: parameters.retry_after } : {}),
68
+ ...(typeof parameters.migrate_to_chat_id === "number" ? { migrateTo: parameters.migrate_to_chat_id } : {})
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Descriptions that refine a 400 or a 403, matched as substrings. Each gives
74
+ * a fixed detail: a description can quote the message, so it never goes
75
+ * into an error. The table grows from captured answers (live check 10).
76
+ */
77
+ const refinements: ReadonlyArray<readonly [string, (detail: string) => ChatErrorReason, string]> = [
78
+ ["message is not modified", invalidRequest, "not_modified"],
79
+ ["message to edit not found", notFound, "message_not_found"],
80
+ ["message to delete not found", notFound, "message_not_found"],
81
+ ["message to be replied not found", notFound, "reply_target_not_found"],
82
+ ["message not found", notFound, "message_not_found"],
83
+ ["chat not found", notFound, "chat_not_found"],
84
+ ["thread not found", notFound, "thread_not_found"],
85
+ ["user not found", notFound, "user_not_found"],
86
+ ["participant_id_invalid", notFound, "user_not_found"],
87
+ ["message can't be deleted", (detail) => new Forbidden({ detail }), "cannot_delete"],
88
+ ["message can't be edited", (detail) => new Forbidden({ detail }), "cannot_edit"],
89
+ ["not enough rights", (detail) => new Forbidden({ detail }), "not_enough_rights"],
90
+ ["have no rights", (detail) => new Forbidden({ detail }), "not_enough_rights"],
91
+ ["bot was blocked", (detail) => new Forbidden({ detail }), "blocked"],
92
+ ["bot was kicked", (detail) => new Forbidden({ detail }), "kicked"],
93
+ ["bot is not a member", (detail) => new Forbidden({ detail }), "not_a_member"],
94
+ // A rich message's limits, as live check 3 found them.
95
+ ["rich_message_text_too_long", (detail) => tooLarge("text", detail), "message_too_long"],
96
+ ["rich_message_too_large", (detail) => tooLarge("text", detail), "message_too_large"],
97
+ ["rich_message_blocks_too_many", (detail) => tooLarge("text", detail), "too_many_blocks"],
98
+ ["rich_message_depth_invalid", invalidRequest, "too_deep"],
99
+ ["rich_message_table_cols_too_many", invalidRequest, "too_many_columns"],
100
+ ["rich_message_empty", invalidRequest, "empty_message"],
101
+ ["rich_message_markdown_invalid", invalidRequest, "invalid_markdown"],
102
+ ["too long", (detail) => tooLarge("text", detail), "message_too_long"],
103
+ ["file is too big", () => refusedFile, fileRefused],
104
+ ["wrong file", () => refusedFile, fileRefused]
105
+ ]
106
+
107
+ /** The detail of a chat that became a supergroup. @internal */
108
+ export const chatMigrated = "chat_migrated"
109
+
110
+ /**
111
+ * Maps one Telegram error. `cause` is attached as given: the caller passes
112
+ * nothing that holds a URL or message text.
113
+ *
114
+ * @internal
115
+ */
116
+ export const reasonForApiError = (
117
+ error: ApiError,
118
+ options: { readonly write: boolean; readonly cause?: unknown }
119
+ ): ChatErrorReason => {
120
+ const cause = options.cause === undefined ? {} : { cause: options.cause }
121
+ if (error.code === 429) {
122
+ return new RateLimited({
123
+ detail: "telegram_429",
124
+ ...(error.retryAfter === undefined ? {} : { retryAfter: Duration.seconds(error.retryAfter) })
125
+ })
126
+ }
127
+ if (error.migrateTo !== undefined) return new NotFound({ detail: chatMigrated, ...cause })
128
+ if (error.code === 401 || error.code === 404) return new Unauthenticated({ detail: `telegram_${error.code}` })
129
+ if (error.code >= 500) {
130
+ return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", detail: `telegram_${error.code}` })
131
+ }
132
+ if (error.code === 409) return invalidRequest("conflict")
133
+ if (error.code === 400 || error.code === 403) {
134
+ for (const [needle, make, detail] of refinements) {
135
+ if (error.description.includes(needle)) return make(detail)
136
+ }
137
+ return error.code === 403 ? new Forbidden({ detail: "telegram_403" }) : invalidRequest("telegram_400")
138
+ }
139
+ return invalidRequest(`telegram_${error.code}`)
140
+ }
141
+
142
+ /** A request that failed before an answer came. A write may have landed. No cause: it would hold the URL. @internal */
143
+ export const transport = (write: boolean, detail: string): ChatErrorReason =>
144
+ new Transport({ retry: write ? "uncertain" : "retry", detail })
145
+
146
+ /** An answer the adapter cannot read. A write may have landed. @internal */
147
+ export const invalidResponse = (write: boolean, detail: string): ChatErrorReason =>
148
+ write ? new Unknown({ detail }) : new InvalidResponse({ detail })