|
1 | 1 | // deno-lint-ignore-file no-explicit-any |
2 | 2 | // The authors disclaim copyright to this source code (they are ashamed to |
3 | 3 | // admit they wrote it) |
| 4 | +import { encodeBase64 } from "jsr:@std/encoding"; |
4 | 5 |
|
5 | 6 | export const BOT_TOKEN = Deno.env.get("TG_BOT_TOKEN"); |
6 | 7 | export const MAIN_CHAT_ID = parseInt(Deno.env.get("TG_MAIN_CHAT_ID")!); |
@@ -104,3 +105,77 @@ export async function tgCall( |
104 | 105 | } |
105 | 106 | return req; |
106 | 107 | } |
| 108 | + |
| 109 | +export async function řekniTomovi( |
| 110 | + sender: string, |
| 111 | + message: string, |
| 112 | + image: string = "", |
| 113 | + chat_id: number = MAIN_CHAT_ID, |
| 114 | +) { |
| 115 | + if (sender) { |
| 116 | + message = `${sender} říká: ${message}`; |
| 117 | + } |
| 118 | + |
| 119 | + const response = await fetch("https://printomat.slama.dev/submit", { |
| 120 | + headers: { |
| 121 | + "Content-Type": "application/x-www-form-urlencoded", |
| 122 | + }, |
| 123 | + body: new URLSearchParams({ |
| 124 | + message: message, |
| 125 | + image: image, |
| 126 | + token: PRINTER_TOKEN, |
| 127 | + }).toString(), |
| 128 | + method: "POST", |
| 129 | + }); |
| 130 | + const txt = await response.text(); |
| 131 | + if (chat_id) { |
| 132 | + await tgCall({ |
| 133 | + chat_id: chat_id, |
| 134 | + reply_to_message_id: chat_id, |
| 135 | + text: `Tom říká (${response.status}): ${ |
| 136 | + /<p>(.*?)<\/p>/.exec(txt)?.[1] ?? txt |
| 137 | + }`, |
| 138 | + }); |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +export async function getFileBase64(message: any, maxSize = Infinity) { |
| 143 | + function* files() { |
| 144 | + yield message.sticker?.thumb; |
| 145 | + yield message.sticker?.thumbnail; |
| 146 | + yield message.sticker; |
| 147 | + yield message.video_note?.thumb; |
| 148 | + yield message.video_note?.thumbnail; |
| 149 | + yield message.video_note; |
| 150 | + yield message.video?.thumb; |
| 151 | + yield message.video?.thumbnail; |
| 152 | + yield message.video; |
| 153 | + yield message.document; |
| 154 | + if (message.photo) { |
| 155 | + yield* message.photo; |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + let bestCandidate = undefined; |
| 160 | + for (const file of files()) { |
| 161 | + if ( |
| 162 | + !file || file.file_size > maxSize || |
| 163 | + file.file_size < bestCandidate?.file_size |
| 164 | + ) continue; |
| 165 | + bestCandidate = file; |
| 166 | + } |
| 167 | + |
| 168 | + if (!bestCandidate) { |
| 169 | + return; |
| 170 | + } |
| 171 | + |
| 172 | + const fileData = await tgCall( |
| 173 | + { file_id: bestCandidate.file_id }, |
| 174 | + "getFile", |
| 175 | + ); |
| 176 | + const response = await fetch( |
| 177 | + `https://api.telegram.org/file/bot${BOT_TOKEN}/${fileData.result.file_path}`, |
| 178 | + ); |
| 179 | + const fileContent = new Uint8Array(await response.arrayBuffer()); |
| 180 | + return encodeBase64(fileContent); |
| 181 | +} |
0 commit comments