how to send image from url using telethon - python

I want to know how to send image or media from a URL link,
file = BOT.upload_file('/user/home/photo.jpg')
BOT.send_file(chat , file)
I know that using this method we can send image from path, but I want to know if its possible to send it from a URL link. but I am trying to run the code on Heruku so uploading it from the patch will not be possible so if there is a way to send it using a URL link please tell me how to do that.
can anyone help me figure this out please.

you don't have to explicitly upload a file, telethon does it internally, so:
BOT.send_file(chat , '/user/home/photo.jpg')
is enough (unless you're willing to resend something pre-uploaded multiple times)
likewise, you can pass a URL to send_file, Telegram servers will fetch it and send by itself (note there are limits for file size, 5MB for images, 20 MB for documents)
BOT.send_file(chat , url)

Related

Send video from kik bot

I am trying to write a simple kik bot to send videos from youtube.
Started with https://github.com/kikinteractive/kik-bot-python-example
Modified it this way:
messages_to_send.append(
VideoMessage(
to=message.from_user,
chat_id=message.chat_id,
video_url="https://www.youtube.com/watch?v=WHATEVER"
))
But when try, i get an error like:
kik.error.KikError: {"message":"Error sending video message:
text/html; charset=utf-8 is not a supported
Content-Type","error":"BadRequest"}
Dont know from where is taking "text/html; charset=utf-8" because i ve defined is a VideoMessage(
Sorry if it is a silly question, i am noob with kik and python
Thanks in advance
I think the video_url parameter expects an URL that points to a video file. In the example from their docs the URL is "http://example.kik.com/video.mp4", meaning (in my opinion) that it should be a video file. In your example, "https://www.youtube.com/watch?v=WHATEVER" would point to an HTML file (i.e. not a video file).
Maybe you'll have to find (a) if YouTube provides a URL that returns a video mimetype (I bet they don't), or (b) use something as youtube-dl to download the MP4 file, uplaod it somewhere else and use this somewhere-else's URL in yourt code snipet. Or… (c) just send a text message with the YouTube URL : )
Does that make sense?

Storing user images on AWS

I'm implementing a simple app using ionic2, which calls an API built using Flask. When setting up the profile, I give the option to the users to upload their own images.
I thought of storing them in an S3 bucket and serving them through CloudFront.
After some research I can only find information about:
Uploading images from the local storage using python.
Uploading images from a HTML file selector using javascript.
I can't find anything about how to deal with blobs/files when you have a front end interacting with an API. When I started researching the options I had thought of were:
Post the file to Amazon on the client side and return the
CloudFront url directly to the back end. I am not too keen on this
one because it would involve having some kind of secret on the
client side (maybe is not that dangerous, but I would rather have it
on the back end).
Upload the image to the server and somehow tell the back end about
which file we want the back end to choose. I am not too keen on
this approach either because the client would need to have knowledge
about the server itself (not only the API).
Encode the image (I have tought of base64, but with the lack of
examples I think that it is plain wrong) and post it to back end,
which will handle all the S3 upload/store CloudFront URL.
I feel like all these approaches are plain wrong, but I can't think (or find) what is the right way of doing it.
How should I approach it?
Have the server generate a pre-signed URL for the client to upload the image to. That means the server is in control of what the URLs will look like and it doesn't expose any secrets, yet the client can upload the image directly to S3.
Generating a pre-signed URL in Python using boto3 looks something like this:
s3 = boto3.client('s3', aws_access_key_id=..., aws_secret_access_key=...)
params = dict(Bucket='my-bucket', Key='myfile.jpg', ContentType='image/jpeg')
url = s3.generate_presigned_url('put_object', Params=params, ExpiresIn=600)
The ContentType is optional, and the client will have to set the same Content-Type HTTP header during upload to url; I find it handy to limit the allowable file types if known.

telegram bot image from url - undesired cache

I am working on a telegram bot that displays images from several webcams upon request. I fetch the images from urls and then send to the user (using bot.sendPhoto() ) My problem is that for any given webcam the filename does not change and it seems that the photo is sent from telegram's cache. So it will display the image from the first time that image was requested.
I have thought about downloading the image from the url, saving with a variable name (like a name with a timestamp in it) then sending it to the chat, this seems like an inelegant solution and was hoping for something better. Like forcing the image not to be cached on the telegram server.
I am using the python-telegram-bot wrapper, but I am not sure that it's specific to that.
Any ideas? I have tried searching but so far am turning up little.
Thanks in advance.
I had the same problem too, but i've found the simplest solution.
When you call the image, you have to add a parameter with timestamp to the image link.
Example:
http://www.example.com/img/img.jpg?a=TIMESTAMP
Where TIMESTAMP is the timestamp function based on the language you are using.
Simple but tricky ;)
I think the best way is to do the same as we do in React where also, same URL calls are first checked in the cache.
If you are using Python the best way is:
timestamp = datetime.datetime.now().isoformat()
# Above statement returns like: '2013-11-18T08:18:31.809000'
pic_url = '{0}?a={1}'.format(img_url, timestamp)
Hope that helps!
I had the same problem. I wanted to create a bot which sends an image taken by a webcam of a ski slope (webcam.example.com/image.jpg). Unfortunately, the filename and so the url never updates and telegram always sends the cached image. So I decided to alter the url passed to the api. In order to achieve this, I wrote a simple php site (example.com/photo.php) which redirects to the original url of the photo. After that, I created a folder (example.com/getphoto/) on my webspace with a .htaccess file inside. The .htaccess redirects all request in this folder to the photo.php site which redirects to the image (webcam.example.com/image.jpg). So you could add everything to the url of the folder and still get the picture (e. g. example.com/getphoto/42 or example.com/getphoto/hrte8437g). The telegram api seems to cache photos by url, so if you add always another ending to the url passed to the api, telegram doesnt use the cached version and sends the current image instead. The easiest way to always change the url is by adding the current date to it.
example.com/photo.php
<?php
header("Location: http://webcam.example.com/image.jpg");
die();
?>
example.com/getphoto/.htaccess
RewriteEngine on
RewriteRule ^(.*)$ http://example.com/photo.php
in python:
bot.sendPhoto(chat_id, 'example.com/getphoto/' + strftime("%Y-%m-%d_%H-%M-%S", gmtime()))
This workaround should also work in other languages like java or php. You just need to change the way to get the current date.

Python Facebook upload video from external link

I'm trying to upload a video to facebook from an external url. But I got error when I post it. I tried with local videos, and all works fine.
My simple code is :
answer = graph.post(
path="597739293577402/videos",
source='https://d3ldtt2c6t0t08.cloudfront.net/files/rhn4phpt3rh4u/2015/06/17/Z7EO2GVADLFBG6WVMKSD5IBOFI/main_OUTPUT.tmp.mp4',
)
and my error is allways the same :
FacebookError: [6000] There was a problem uploading your video file. Please try again with another file.
I looked into the docs and found the parameter file_url but it still the same issue.
The format of the video is .mp4 so it should work.
Any idea ?
Apparently this error message is very confusing. It's the same message when you've an access_token who doesn't work. For example, I've this error message when I'm trying with my user access token and not if I use the Page access token.
I've never used source, I'm pretty sure that's for reading video data off their API. Instead, I use file_url in my payload when passing video file URLs to Facebook Graph API.
Refer to their API doc for clarity on that...
It's also possible that the tmp.mp4 file extension is causing you problems. I've had issues with valid video URLs with non-typical file extensions similar to that. Is it possible to alter that at the source so that the URL doesn't have the tmp ?
A typical payload pass using Requests module to their API that works for me might look something like this:
fburl = 'https://graph-video.facebook.com/v2.3/156588/videos?access_token='+str(access)
payload = {'name': '%s' %(videoName), 'description': '%s' %(videoDescription), 'file_url': '%s' %(videoUrl)}
flag = requests.post(fburl, data=payload).text
print flag
fb_res = json.loads(flag)
I would also highly recommend that you obtain a permanent page access token. It's the best way to mitigate the complexities of Facebook's oAuth process.
facebook: permanent Page Access Token?

What's a Django/Python solution for providing a one-time url for people to download files?

I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy person downloading the file won't be able to download the file more than once. It would be nice to host the file on Amazon S3 to save on bandwidth where our server is co-located.
My thought for the codes would be to pre-generate the unique codes that will get printed on the cards and store those in a database that could also have a field that stores the number of times the file was downloaded. This way we could set how many attempts we would allow the user for downloading the file.
The part that I need direction on is how do I hide/mask the original file location so people can't steal that url and then download the file as many times as they want. I've done Google searches and I'm either not searching using the right keywords or there aren't very many libraries or snippets out there already for this type of thing.
I'm guessing that I might be able to rig something up using django.views.static.serve that acts as a sort of proxy between the actual file and the user downloading the file. The only drawback to this method I would think is that I would need to use the actual web server and wouldn't be able to store the file on Amazon S3.
Any suggestions or thoughts are greatly appreciated.
Neat idea. However, I would warn against the single-download method, because there is no guarantee that their first download attempt will be successful. Perhaps use a time-expiration method instead?
But it is certainly possible to do this with Django. Here is an outline of the basic approach:
Set up a django url for serving these files
Use a GET parameter which is a unique string to identify which file to get.
Keep a database table which has a FileField for the file to download. This table maps the unique strings to the location of the file on the file system.
To serve the file as a download, set the response headers in the view like this:
(path is the location of the file to serve)
with open(path, 'rb') as f:
response = HttpResponse(f.read())
response['Content-Type'] = 'application/octet-stream';
response['Content-Disposition'] = 'attachment; filename="%s"' % 'insert_filename_here'
return response
Since we are using this Django page to serve the file, the user cannot find out the original file location.
You can just use something simple such as mod_xsendfile. This functionality is also available in other popular webservers such lighttpd or nginx.
It works like this: when enabled your application (e.g. a trivial PHP script) can send a special response header, causing the webserver to serve a static file.
If you want it to work with S3 you will need to handle each and every request this way, meaning the traffic will go through your site, from there to AWS, back to your site and back to the client. Does S3 support symbolic links / aliases? If so you might just redirect a valid user to one of the symbolic URLs and delete that symlink after a couple of hours.

Categories

Resources