first commit

main
Astra 2024-09-06 02:11:55 +01:00
commit 5896a3db3f
1 changed files with 117 additions and 0 deletions

117
cli.ts 100644
View File

@ -0,0 +1,117 @@
import { parseArgs } from "jsr:@std/cli/parse-args";
const botToken = Deno.env.get("BOT_TOKEN");
if (!botToken) {
console.error("BOT_TOKEN environment variable must be set.");
Deno.exit(1);
}
async function makeTelegramRequest(
command: string,
additionalParam: typeof args,
) {
const url =
`https://api.telegram.org/bot${botToken}/${command}?chat_id=${additionalParam.chat_id}`;
const formData = new FormData();
switch (command) {
case "sendMessage": {
formData.append("text", additionalParam.text);
break;
}
case "sendMediaGroup": {
const jsonData = [];
for (let i = 0; i < additionalParam.files.length; i++) {
const file = await Deno.readFile(additionalParam.files[i]);
formData.append(
`file${i}`,
new Blob([file]),
additionalParam.files[i],
);
if (i == 0) {
jsonData.push({
"parse_mode": additionalParam.parse_mode,
"caption": additionalParam.caption,
"type": "photo",
"media": `attach://file${i}`,
});
} else {
jsonData.push({
"type": "photo",
"media": `attach://file${i}`,
});
}
}
formData.append("media", JSON.stringify(jsonData));
break;
}
case "sendPhoto": {
const file = await Deno.readFile(additionalParam.file);
formData.append(
"photo",
new Blob([file]),
additionalParam.file,
);
if (additionalParam.caption) {
formData.append("caption", additionalParam.caption);
}
break;
}
case "deleteMessage": {
formData.append("message_id", additionalParam.message_id);
break;
}
default: {
console.log("Unknown command");
return;
}
}
if (additionalParam.parse_mode && command != "sendMediaGroup") {
formData.append("parse_mode", additionalParam.parse_mode);
}
const response = await fetch(url, {
method: "POST",
body: formData,
});
const data = await response.json();
console.info(data);
}
const args = parseArgs(Deno.args, {
string: [
"chat_id",
"caption",
"text",
"file",
"files",
"message_id",
"parse_mode",
],
default: {
chat_id: "0",
caption: "",
text: "",
file: "",
files: [],
message_id: "0",
parse_mode: "MarkdownV2",
},
});
const command = String(args._[0]);
if (!command) {
console.error("Missing arguments. Usage: <command> <additional_arguments>");
console.error("Supported commands:");
console.error(" sendMessage: Sends a text message");
console.error(" sendPhoto: Sends a photo");
console.error(" sendMediaGroup: Sends a media group");
console.error(" deleteMessage: Deletes a message");
Deno.exit(1);
}
await makeTelegramRequest(command, args);