Telegram Bot SendDocument pdf - python

I am having a real headache with the way of sending a pdf file to a Telegram Bot.
Apparently I am following the documentation but never get it sent.
I am using the url: https://api.telegram.org/botBOTID/sendDocument?chat_id=CHATID&document=/home/lix/Downloads/2.pdf
It is a pdf file storaged locally, but I think it is just the way I am presenting it.
The error getting is:
{"ok":false,"error_code":400,"description":"Bad Request: URL host is empty"}
Does anybody knows how to send a pdf local file?
Many thanks

You should send a POST request, with the PDF as a payload, using the Python Requests library, your code should look something like this:
import requests
# Url with bot token + user id
url = "https://api.telegram.org/bot<MY-BOT-TOKEN>/sendDocument?chat_id=<MY_CHAT_ID>"
# Create payload with PDF file
payload = {}
files = [
('document', open('/home/lix/Downloads/2.pdf','rb'))
]
headers= {}
# Request
response = requests.request("POST", url, headers=headers, data = payload, files = files)
# Log reponse as UTF-8
print(response.text.encode('utf8'))

Related

Send Request with API WSDL in Python

Basically, I have to send a request to a API.
The url is this one https://testws.punto-web.com/wcfadproc/srvproceso.svc?wsdl
Information for the requests is like this, which is formatted in xml
The code I've tried is the following, but I get a 415 error and response is empty, so I think I mistook in request. Also, researching about this problem I've noticed that exists a module named 'zeep' that can be used for SOAP and WSDL, but not sure if it's necessary or my problem can be solved only with 'requests' module.
import requests
url = 'https://testws.punto-web.com/wcfadproc/srvproceso.svc?wsdl'
headers = {'content-type': 'text/xml'}
body = """
<Anulacion>
<Comercio>1234567</Comercio>
<IdTxn>12345</IdTxn>
<CodAutorizacion>123456</CodAutorizacion>
<NumPedido>123456</NumPedido>
<Moneda>PEN</Moneda>
<Monto>100.00</Monto>
<FechaTxn>20211206</FechaTxn>
<HoraTxn>121212</HoraTxn>
</Anulacion>
"""
anulacion = requests.request('POST',
url,
data= body,
headers = headers
)

python making a post file request

Hi guys I'm developing a Python 3 quart asyncio application and I'm trying to setup a test framework around my http API.
Quart has methods to build json, form and raw requests but no files request. I believe I need build the request packet myself and post a "raw" request.
Using postman I can see that the requests need to look like this:
----------------------------298121837148774387758621\r\n
Content-Disposition: form-data; name="firmware"; filename="image.bin"\r\n
Content-Type: application/octet-stream\r\n
\r\n
\x00#\x00\x10\x91\xa0\t\x08+\xaa\t\x08/\xaa\t\x083\xaa\t\x087\xaa\t\x08;\xaa\t\x08\x00\x00\x00\
....
\xff\xff\xff\xff\xff\xff\xff\xa5\t\tZ\x0c\x00Rotea MLU Main V0.12\x00\x00k%\xea\x06\r\n
----------------------------298121837148774387758621--\r\n
I'd prefer not to encode this myself if there is a method that exists.
Is there an module in Python where I can build the raw packet data and send it with the Quart API?
I have tried using quart requests:
import requests
from .web_server import app as quart_app
test_client = quart_app.test_client()
firmware_image = 'test.bin'
with open(firmware_image, 'rb') as f:
data = f.read()
files = {'firmware': (firmware_image, data , 'application/octet-stream')}
firmware_req = requests.Request('POST', 'http://localhost:5000/firmware_update', files=files).prepare()
response = await test_client.post('/firmware_update',
data=firmware_req.body,
headers={'Content-type': 'multipart/form-data'})
Any suggestions would be greatly appreciated.
Cheers. Mitch.
Python's requests module provides a prepare function that you can use to get the raw data it would send for the request.
import requests
url = 'http://localhost:8080/'
files = {'file' : open('z', 'rb'),
'file2': open('zz', 'rb')}
req = requests.Request('POST',url, files=files)
r = req.prepare()
print(r.headers)
print(r.body)

How do I send an attachment through REST response using Python Flask

I'm building a REST API, and it has to send a file in the response. I do not want to include the file content in the response body. Can we attach files to response ?
If I understood you right, you want to send a file with Content-Disposition header set to 'attachment'. Which instructs the browser to download/save the file, instead of displaying its contents inline on the page.
If that's what you want, then you'll have to do something like this:
from flask import make_response
#app.route('/txt')
def attachment():
resp = make_response('my text file')
resp.headers['Content-Type'] = 'text/plain;charset=UTF-8'
resp.headers['Content-Disposition'] = 'attachment;filename=SmartFileName.txt'
return resp

Python's Requests library adds tags to PDF, which breaks API

I am using Python's Requests library to POST a PDF to a document store, the uploaded PDF is thereafter used in a signature process. However when uploading the PDF using Python (in stead of CURL) the signing environment doesnt work. On comparing different files, I found out that Requests adds some data to the PDF:
--ca9a0d04edf64b3395e62c72c7c143a5
Content-Disposition: form-data; name="LoI.pdf"; filename="LoI.pdf"
%%Original PDF goes here%%
--ca9a0d04edf64b3395e62c72c7c143a5--
This data is accepted perfectly fine by different PDF readers, but not by the Signature API. Is there a way to prevent Requests from adding this data to the PDF? I used the following code:
myfile = request.FILES['myfile']
url = %%documentstoreURL%%
resp = requests.request('post', url, files={myfile.name:myfile}, headers={'Content-Type':'application/pdf'}, auth=(%%auth details%%))
Thanks!
You're sending the file as binary data with curl, but attaching it in requests.
I read over the source code, and I believe resp = requests.request('post', url, data={myfile.name:myfile}, headers={'Content-Type':'application/pdf'}, auth=(%%auth details%%)) (data instead of files) will avoid the multipart encoding.
At the very least, it should be differently broken.
Being guided in the right direction, I found a working solution based on Python requests - POST data from a file
In the end I did it as follows:
myfile = request.FILES['myfile']
payload = request.FILES['myfile'].read()
headers = {'content-type': 'application/pdf'}
url = "%%DocumentServiceURL"
r = requests.post(url, auth=(%%auth_details%%), data=payload, verify=False, headers=headers)

How to Send post response as image from python requests

i am trying to get my image hosted online and for that i am using python
import requests
url = 'http://imgup.net/'
data = {'image[image][]':'http://www.webhost-resources.com/wp-content/uploads/2015/01/dedicated-hosting-server.jpg'}
r = requests.post(url, files=data)
i am not able to get the response url of the hosted image from the response .
Please help !
The files parameter of requests.post needs a:
Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.
There's more data you'll need to send than just the file, most importantly the "authenticity token". If you look at the source code of the page, it'll show you all other parameters as <input type="hidden"> tags.
The upload URL is http://imgup.net/upload, as you can see from the action attribute of <form>.
So what you need to do is:
Download the image you want to upload (I'll call it dhs.jpg).
Do a GET request of the main page, extracting the authenticity_token.
Once you have that, send the request with files= and data=:
‌
url = "http://imgup.net/upload"
data = {'utf8': '✓', 'authenticity_token': '<put your scraped token here>', '_method': 'put'}
f = open("dhs.jpg", "rb") # open in binary mode
files = {'image[image][]': f}
r = requests.post(url, files=files, data=data)
f.close()
print(r.json()["image_link"]
Final note: While I couldn't find any rule against this behaviour in their T&C, the presence of an authenticity token makes it seem likely that imgup doesn't really want you to do this automatically.

Categories

Resources