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 ответов

25 просмотров

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

༺Dark Devil༻- Автор вопроса
Александр Иванов
Hi! You have to create a separate Apps Script proj...

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

༺Dark Devil༻- Автор вопроса
Александр Иванов
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༻- Автор вопроса
༺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༻
Sir script live again https://script.google.com/d/...

You didn't answer - what does bot send you when you send link?

༺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.

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

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

@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Подобного рода ;Следующие три строки это директивы ассемблера, ;которые можно не задавать, т.к.работаем в Visual Studio. ;Символ ";" - это начало однострочного комментария ...
Егор Анелькин
3
Привет всем. появился вопрос. Разрабатываю сайт, в данный момент он запущен. Хостинг beget. Добавляю на сайт яндекс метрику с помощью полей client-settings (взято отсюда http...
Andrew
2
еще вопрос, допустим мы создадим char массив из 10 элементов и присвоим ему через сканф 10 символов. и выведем все символы. Хотел спросить последний элемент /0 будет включать...
Anthem
10
Подскажите, где смотреть результат выполнения программы? Код: ;.686 ;Система команд процессора 686 ;.MODEL FLAT,stdcall ;Модель памяти плоская, станда...
Егор Анелькин
5
открыть папку в проводнике: 1 - ShellExecute 2 - ExecuteProcess 3 - OpenDocument что лучше выбрать?
Alexey Kulakov
12
Изменение типа с SomeException на String и правда удобней @cheese_hs . А вот такой вариант насколько некрасив еще? loadConfigDB :: IO (Either String ConfigDataBase) loadConfi...
Camara
7
Где в Астане можно купить мясо для шашлыков?
Dancing Іңұқәһүғө
21
Карта сайта