169 похожих чатов

Hey I am from India I want to help to

development a telegram bot who download Google drive url to file plz help me

My code it's not working

// Configuration
var apiToken = "********";
var appUrl = "***************";
var apiUrl = "https://api.telegram.org/bot"+apiToken;
var command = {
"/start": "Hello! I am your Google Drive downloader bot. Send me a Google Drive link to download the file. Join for Updates @anonymous_robos",
"/help": "Send me a Google Drive link and I will download the file and send it to you",
"what is your name?": "My name is Gdrive2File Bot"
}

// Function to set webhook
function setWebhook(){
var url = apiUrl + "/setwebhook?url="+appUrl;
var res = UrlFetchApp.fetch(url).getContentText();
Logger.log(res);
}

// Function to extract the file ID from a Google Drive link
function extractFileIdFromDriveLink(link) {
var fileIdMatch = link.match(/\/file\/d\/([^\/]+)\//);
return fileIdMatch ? fileIdMatch[1] : null;
}

// Function to download file from Google Drive
function downloadFileFromDrive(fileId) {
try {
var file = DriveApp.getFileById(fileId);
var content = file.getBlob().getBytes();
var contentType = file.getMimeType();
var fileName = file.getName();

var response = {
content: content,
contentType: contentType,
fileName: fileName
};

return response;
} catch (error) {
Logger.log("Error downloading file:", error);
return null;
}
}

// Handle webhook
function doPost(e){
try {
var webhookData = JSON.parse(e.postData.contents);
var from = webhookData.message.from.id;
var text = webhookData.message.text;
var chatId = webhookData.message.chat.id;
var messageId = webhookData.message.message_id;

if (typeof command[text] == 'undefined') {
var sendText = encodeURIComponent("command not found");
} else {
var sendText = encodeURIComponent(command[text]);
}

// Check if the message contains a Google Drive link
var driveFileId = extractFileIdFromDriveLink(text);

if (driveFileId) {
// Send processing message
var processingMsg = "Processing... Please wait.";
var processingUrl = apiUrl + "/sendMessage?chat_id=" + chatId + "&text=" + encodeURIComponent(processingMsg);
UrlFetchApp.fetch(processingUrl, { muteHttpExceptions: true });

var driveResponse = downloadFileFromDrive(driveFileId);

if (driveResponse) {
// Send the file to the user
var url = apiUrl + "/sendDocument?chat_id=" + chatId;
var formData = {
document: {
fileName: driveResponse.fileName,
mimeType: driveResponse.contentType,
content: driveResponse.content,
}
};
var options = {
method: "post",
payload: formData,
muteHttpExceptions: true
};
UrlFetchApp.fetch(url, options);

// Edit the processing message with the file
var editUrl = apiUrl + "/editMessageText?chat_id=" + chatId + "&message_id=" + messageId + "&text=" + encodeURIComponent("File sent successfully!");
UrlFetchApp.fetch(editUrl, { muteHttpExceptions: true });
} else {
throw new Error("Error downloading file from Google Drive");
}
} else {
var url = apiUrl+"/sendmessage?parse_mode=HTML&chat_id="+from+"&text="+sendText;
var opts = {"muteHttpExceptions": true}
UrlFetchApp.fetch(url, opts).getContentText();
}
} catch (error) {
Logger.log("Error in doPost:", error);
var errorMsg = encodeURIComponent("An error occurred. Please try again later.");
var url = apiUrl+"/sendmessage?parse_mode=HTML&chat_id="+from+"&text="+errorMsg;
var opts = {"muteHttpExceptions": true}
UrlFetchApp.fetch(url, opts).getContentText();
}
}

// Handle GET request
function doGet(e){
return ContentService.createTextOutput("Method GET not allowed");
}

20 ответов

61 просмотр

Hi! You have to create a separate Apps Script project for sharing the code for us

༺Dark Devil༻- Автор вопроса
Alexander Ivanov
Hi! You have to create a separate Apps Script proj...

https://script.google.com/d/1pAyNlLKSTacnQPc6cLH4RvJwnu8n3u0VWwSenwqu8Z05Ss6NAoqtb_Tw/edit?usp=sharing

༺Dark Devil༻- Автор вопроса
Alexander Ivanov
I can watch this later

Just see your wish sir I have just started learning coding and programming Please help this child a little 🥹

This code should not work. Because, in my opinion, it's done using GPT and you even didn't try to understand what's wrong. For start, I'd recommend you use console.log in different parts of the code, so you can understand where is the problem.

༺Dark Devil༻- Автор вопроса
Dmitry
This code should not work. Because, in my opinion,...

It's Google script I try like javascript console.log but it not show console.log message

༺Dark Devil༻
Hmm I delete them

Can u try to start script and after send screenshot of result?

Сергей
Can u try to start script and after send screensho...

Это doPost, не вводите в заблуждение, толку от запуска не будет.

༺Dark Devil༻- Автор вопроса
Роман Игнатов
Hm, you needn't help?

Sir script live again https://script.google.com/d/10KzH-IHNkx5BkJUBEG339MuFaiPjH_WqcrdQJpcarpdN_t0JOHctUb27/edit?usp=sharing

༺Dark Devil༻- Автор вопроса
Роман Игнатов
You didn't answer - what does bot send you when yo...

A file that contains a gdrive url Ex- when I send to bot a gdrive link(it's. A pdf) then bot send me that pdf file https://drive.google.com/file/d/1Z16edv7U8OKJyQH8ynvIdLxpEBbXUSoc/view?pli=1

༺Dark Devil༻
A file that contains a gdrive url Ex- when I send ...

You wrote that it doesn't work, now you write that it works. Bingo? It started working?

༺Dark Devil༻- Автор вопроса
Роман Игнатов
You wrote that it doesn't work, now you write that...

No code work but I not received file in bot some error in my code

༺Dark Devil༻
screenshot No code work but I not received file in bot some e...

Try to write function that send document without doPost, and without mutehttpExceptions:true. And run it to check errors. So you can get error from urlfetchapp. Then change code to make to work it.

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
Чёт не понял, я ж правильной функцией воспользовался чтобы вывести отладочную информацию? но что-то она не ловится
notme
18
У меня есть функция где происходит это: write_bit(buffer, 1); write_bit(buffer, 0); write_bit(buffer, 1); write_bit(buffer, 1); write_bit(buffer, 1); w...
~
14
Добрый день! Скажите пожалуйста, а какие программы вы бы рекомендовали написать для того, чтобы научиться управлять памятью? Можно написать динамический массив, можно связный ...
Филипп
7
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
Ребят в СИ можно реализовать ООП?
Николай
33
https://github.com/erlang/otp/blob/OTP-27.1/lib/kernel/src/logger_h_common.erl#L174 https://github.com/erlang/otp/blob/OTP-27.1/lib/kernel/src/logger_olp.erl#L76 15 лет назад...
Maksim Lapshin
20
Карта сайта