Send drive file to python telegram bot - python-3.x

I am trying to get my telegram bot to download a pdf document that is on google drive, but I can't get it to work.
I made the following code to be able to get it to work but there was no case in this:
url = bot.get_File(link='link of google drive') down = url.download() bot.sendDocument(chat_id=ChatId, document=open(down,'rb'), filename="Lista de precios.pdf")
I don't put the google drive link for privacy reasons, but obviously it would go there.
I don't know if it is possible to download a file from drive just like that.

Looks like you are using the wrong method, get_file is used to download a file from Telegram.
When sending a file via Telegram bot you can use the full URL if this points to a file (ie file.pdf)
bot.send_document(chat_id=Chat_id, document='https://github.com/user/project/raw/master/data/pdf/07-03-2020.pdf'
In case of Google Drive you have a URL that streams the file so you need to 1) download and save the file locally 2) open the local file and send it as file type
r = requests.get('googleDriveUrl', allow_redirects=True)
open('file.ppt', 'wb').write(r.content)
bot.send_document(chat_id=Chat_id, document=open('file.ppt', 'rb'), filename="file.pptx")

Related

I'm looking for an example of writing to a file from a Chrome Extension [duplicate]

I'm currently creating an extension for google chrome which can save all images or links to images on the harddrive.
The problem is I don't know how to save file on disk with JS or with Google Chrome Extension API.
Have you got an idea ?
You can use HTML5 FileSystem features to write to disk using the Download API. That is the only way to download files to disk and it is limited.
You could take a look at NPAPI plugin. Another way to do what you need is simply send a request to an external website via XHR POST and then another GET request to retrieve the file back which will appear as a save file dialog.
For example, for my browser extension My Hangouts I created a utility to download a photo from HTML5 Canvas directly to disk. You can take a look at the code here capture_gallery_downloader.js the code that does that is:
var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');
If you would like the implementation of converting a URI to a Blob in HTML5 here is how I did it:
/**
* Converts the Data Image URI to a Blob.
*
* #param {string} dataURI base64 data image URI.
* #param {string} mimetype the image mimetype.
*/
var dataURIToBlob = function(dataURI, mimetype) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
var bb = new this.BlobBuilder();
bb.append(uInt8Array.buffer);
return bb.getBlob(mimetype);
};
Then after the user clicks on the download button, it will use the "download" HTML5 File API to download the blob URI into a file.
I had long been wishing to make a chrome extension for myself to batch download images. Yet every time I got frustrated because the only seemingly applicable option is NPAPI, which both chrome and firefox seem to have not desire in supporting any longer.
I suggest those who still wanted to implement 'save-file-on-disk' functionality to have a look at this Stackoverflow post, the comment below this post help me a lot.
Now since chrome 31+, the chrome.downloads API became stable. We can use it to programmatically download file. If the user didn't set the ask me before every download advance option in chrome setting, we can save file without prompting user to confirm!
Here is what I use (at extension's background page):
// remember to add "permissions": ["downloads"] to manifest.json
// this snippet is inside a onMessage() listener function
var imgurl = "https://www.google.com.hk/images/srpr/logo11w.png";
chrome.downloads.download({url:imgurl},function(downloadId){
console.log("download begin, the downId is:" + downloadId);
});
Though it's a pity that chrome still doesn't provide an Event when the download completes.chrome.downloads.download's callback function is called when the download begin successfully (not on completed)
The Official documentation about chrome.downloadsis here.
It's not my original idea about the solution, but I posted here hoping that it may be of some use to someone.
There's no way that I know of to silently save files to the user's drive, which is what it seems like you're hoping to do. I think you can ASK for files to be saved one at a time (prompting the user each time) using something like:
function saveAsMe (filename)
{
document.execCommand('SaveAs',null,filename)
}
If you wanted to only prompt the user once, you could grab all the images silently, zip them up in a bundle, then have the user download that. This might mean doing XmlHttpRequest on all the files, zipping them in Javascript, UPLOADING them to a staging area, and then asking the user if they would like to download the zip file. Sounds absurd, I know.
There are local storage options in the browser, but they are only for the developer's use, within the sandbox, as far as I know. (e.g. Gmail offline caching.) See recent announcements from Google like this one.
Google Webstore
Github
I made an extension that does something like this, if anyone here is still interested.
It uses an XMLHTTPRequest to grab the object, which in this case is presumed to be an image, then makes an ObjectURL to it, a link to that ObjectUrl, and clicks on the imaginary link.
Consider using the HTML5 FileSystem features that make writing to files possible using Javascript.
Looks like reading and writing files from browsers has become possible. Some newer Chromium based browsers can use the "Native File System API". This 2020 blog post shows code examples of reading from and writing to the local file system with JavaScript.
https://blog.merzlabs.com/posts/native-file-system/
This link shows which browsers support the Native File System API.
https://caniuse.com/native-filesystem-api
Since Javascript hitch-hikes to your computer with webpages from just about anywhere, it would be dangerous to give it the ability to write to your disk.
It's not allowed. Are you thinking that the Chrome extension will require user interaction? Otherwise it might fall into the same category.

Can we upload media files using URL in MediaFileUpload?

Basically all I want to know is, I am working on Youtube API to upload videos on my channel. Whenever I try to upload video from my local file, it works without any issue. But if I want to upload some videos which are already hosted on S3, it gives me error related to OS i.e. OSError: File not found at that location.
So is there any way to upload video using youtube API from already hosted URLs ?
P.S. I am following the documentation of youtube API and using MediaFileUpload to upload the video files.
Edit 1: I tried a minor hack around this particular issue and works fine for me. Just leaving it here for future developers.
import requests
from six import BytesIO
url = "" # The video url you want to upload (I use S3 urls, not sure if it will work with youtube urls)
res = requests.get(url)
file = BytesIO(res.content)
media = MediaIoBaseUpload(file, mimetype="application/octet-stream")

Download File from OneDrive using REST API

I am trying to find a way out using node js to fetch the list of files (xlsx and CSV files are of my interest) from User's Microsoft OneDrive. From the list, choose the file and then download it into the local system.
I can see Microsoft documentation about using OneDrive REST API here. But, since I am new at this, I am not really able to work this around. Any help will be appreciated.
I want to do something similar to what we can do with Google Drive where I could get a list of files along with their names and unique id and when the user chooses one file, by use of the unique id, I was able to download the required file. I am wondering if a similar thing can be done with OneDrive.
My progress so far:
I am able to ask users to provide their consent and get code in return to redirect Uri (localhost in my case).
The link that does this- https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={my_client_id}&scope=User.Read%20offline_access%20Files.ReadWrite.all%20Files.ReadWrite&response_type=code&response_mode=query&redirect_uri=https://localhost:3400
After getting the code, I exchanged it for refresh token.
To do this exchange, I used Postman for the POST request. The URL for that is https://login.microsoftonline.com/common/oauth2/v2.0/token?grant_type=authorization_code&client_id=your_app_client_id&code=use_the_code_returned_on_previous_step
Now that I have a refresh token, I want to do operations like listing the files on my OneDrive and select anyone to download.
I suggest looking into the Graph API as follows, and using the same auth_token received above. Instead of /me you can substitute a user ID as well.
Get information about the user's drive:
GET https://graph.microsoft.com/v1.0/me/drive
Get the root folder of the drive:
GET https://graph.microsoft.com/v1.0/me/drive/root/
Note: the documentation and the paths in the JSON results say "root:" but I haven't been able to get it work work with the colon.
Embedded in the result you should see:
"folder": {
"childCount": {whatever the count is}
},
To see the files that are in the folder:
GET https://graph.microsoft.com/v1.0/me/drive/root/children
Files will have an id and a name, both of which can be used to retrieve them:
"createdDateTime": "2020-07-05T18:08:37Z",
"eTag": "\"{29C06DFA-92AE-48D5-AF3D-149EF959030F},1\"",
"id": "01EC2X7VP2NXACTLUS2VEK6PIUT34VSAYP",
"lastModifiedDateTime": "2020-07-05T18:08:37Z",
"name": "wizard of wor.png",
To download a file by ID:
https://graph.microsoft.com/v1.0/me/drive/items/01EC2X7VP2NXACTLUS2VEK6PIUT34VSAYP/content
Or by path (in example below Wizard of Wor.png is the file name):
https://graph.microsoft.com/v1.0/me/drive/root/children/Wizard%20of%20Wor.png/content
Documentation sources:
https://learn.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0&tabs=http
https://learn.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=http

Unable to send pdf file from bot to user in ms teams

NodeJS BotBuilder SDK version: 3.15.0
My code:
var pdf = {
name: '<file_name>.pdf',
contentType: 'application/pdf',
contentUrl: '<https url to public pdf file>'
};
var reply = new builder.Message(session).addAttachment(pdf);
session.send(reply);
This code is the same in few online examples. The issue I have is that I always get error:
Error: POST to 'https://smba.trafficmanager.net/emea/v3/conversations/a%3A1TwHmhoGuZP2Mf9P0TTnjv8HkcaXzEHryv0sYCvDDUI-qrMitJtHRlAnIcedcDH_v3IfMBXtg_zo5MDVcS0-8hDCQ4sJzpJhrewBPK8uWJXYeShgmd-s7uh5o8kW4ebAP/activities/1543588440246' failed: [400] Bad Request
For image/png this code works fine.
What I want to achieve is this: (image is taken from Bot Framework Emulator)
File from the web sent from bot to user
The file is sent from bot without uploading it to users's one drive.
This works also when I tested the feature in test section of https://dev.botframework.com/bots. It doesn't work only in ms teams.
The behaviour for sending files can differ per channel. Microsoft Teams doesn't support the direct upload method, like the WebChat / Emulator does. This is due to compliance reasons, as Bill Bliss stated.
You can post messages with card attachments referencing existing SharePoint files using the Microsoft Graph APIs for OneDrive and SharePoint. Using the Graph APIs requires obtaining access to a user's OneDrive folder (for personal and groupchat files) or the files in a team's channels (for channel files) through the standard OAuth2 authorization flow. This method works in all Teams contexts.
Have a look at Send and receive files through your bot
for the full documentation and how to implement.
An alternative option would be to use an AdaptiveCard where you can use an image thumbnail of the document combined with a button to directly download the PDF file from your public accessible URL.

Sharepoint Site Download a file Using Microsoft Graph 1.0

What is wrong with this:
https://graph.microsoft.com/v1.0/sites/insuriasa.sharepoint.com:/Sites/IFS:/drive/root/children
At the end of the day I want to be able to download this:
https://graph.microsoft.com/v1.0/sites/insuriasa.sharepoint.com:/Sites/IFS:/drive/root:/Std Forms/Discovery Invest/Servicing/change_of_contribution_form_retirement_annuity_plan.pdf
If you want to download the file content in a web application you should do a GET call on the item with ?select=#content.downloadUrl parameter. In the response you will get a pre-authenticated url in the property '#microsoft.graph.downloadUrl' on that you can do a get call without passing any extra authentication header to download the file.
If you are using in native clients then this Download Endpoint should work fine.

Resources