I'm encountering an error code: 400 when trying to post a video file.
Error:
400 Bad Request
b'{
"ok":false,
"error_code":400,
"description":"Bad Request: there is no video in the request"
}'
please advice what's wrong (the video file works and exist in the mentioned path)
def sendVideo(bot_token,bot_chatID):
url = "https://api.telegram.org/bot"+ bot_token +"/sendVideo";
files = {'file': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
data = {'chat_id' : bot_chatID}
r = requests.post(url, files=files)
print(r.status_code, r.reason, r.content)
Just change this
files = {'file': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
to that
files = {'video': open('C:/Users/myUser/Desktop/telegram/t_video.mp4', 'rb')}
Because Bot API needs that video parameter name to determine the type of media.
And you forgot to add data=data (or params=data) to requests.post() to pass chat_id.
Related
I'm currently struggling with a really simple problem, but cant spot the problem in detail.
I want to upload a file via requests.post, the current approach looks kinda like:
fin = open(f"{path_dtl}{filename}.dtl", "rb")
files = {"file": fin}
headers = CaseInsensitiveDict()
headers["Authorization"] = f"Bearer {auth_token}"
headers["Content-Type"] = "application/octet-stream"
headers["Content-Disposition"] = f"form-data;filename ='{filename}.dtl'"
upload_dtl = requests.post(url, headers=headers, files=files)
The result is a {'error': 'Invalid Media Type/Mime Type'} response. Is there a need to open a .dtl file in different manner? The usage of a request with this configuration via Postman works fine so I guess I missed a silly mistake. Thanks in advance.
UPDATE
Alright... for anyone interested. The cause of the issue was the default key-value "file" in files = {"file": fin} is different for my API. Following workaround fixed my issue.
with open(f"{path_dtl}{filename}.dtl", "rb") as f: files = f.read()
...
upload_dtl = requests.post(url, headers=headers, files=files)
Have you tried specifying a type? You can do so like this:
files = {'file': ('aaa.csv', open('aaa.csv', 'rb'),'text/csv')}
I need to submit an image to the site https://zxing.org/w/decode.jspx, and read the result page : https://zxing.org/w/decode.
I tried this, but it does not work :
def decode_qrcode(path):
s = requests.Session()
url = "https://zxing.org/w/decode.jspx"
files = {'file': open(path, 'rb')}
s.post(url, files=files)
return s.get("https://zxing.org/w/decode").text
I know that there are librairies to read QR code, but I did not find any that works for the kind of QR codes that I work with (they might have an error rate not supported).
You have to use the allow_redirects argument when making the POST request
import requests
def decode_qrcode(path):
s = requests.Session()
url = "https://zxing.org/w/decode.jspx"
files = {'file': open(path, 'rb')}
s.post(url, files=files, allow_redirects = True)
return s.get("https://zxing.org/w/decode").text
I want to send a file with the post method, but I don't know what's wrong with my code
I have chat_id, file_id, and every requirement parameters
this is a sample code for sending voice via POST Request
import requests
my_data = {'chat_id': '72600457' ,'file_id': 'AwADBAADPAYAAvFWCVFZFfPyZdGLfhYE'}
my_url = 'https://api.telegram.org/bot<MY TOKEN>/sendVoice'
request.post(url=my_url, data=my_data)
when I run the code, no error happens. But nothing is shown from the bot;
This file_id works with GET METHOD and I could send text with POST METHOD, But for files it seems it doesn't work.
Check documentation for sendVoice - it doesn't use name file_id but voice
data = {'chat_id': '72600457', 'voice': 'AwADBAADPAYAAvFWCVFZFfPyZdGLfhYE'}
If you use file ID then you can use POST but also GET
And you should get response from server to see information about wrong request
import requests
token = '<MY TOKEN>'
data = {'chat_id': '72600457', 'voice': 'AwADBAADPAYAAvFWCVFZFfPyZdGLfhYE'}
url = f'https://api.telegram.org/bot{token}/sendVoice'
#response = requests.post(url, data=data)
response = requests.get(url, params=data)
print(response.json())
By the way: there is module python-telegram-bot. GitHub: python-telegram-bot
I am using python to try and get an image from one API, and then post it to a separate API.
So far I have this code:
def create_item(token, user_id):
url = '<api_url_to_post_to>'
headers = {"Authorization": "Token {0}".format(token)}
image_url = '<some_random_image_url>'
image_obj = requests.get(image_url)
data = {
"image": image_obj.content
}
r = requests.post(url, headers=headers, files=data)
response = r.json()
print(response)
return response
The issue is that when I try to post it to the second API, I get a "File extension '' is not allowed." error. This is obviously a custom error message, but it signifies that there is something wrong with the file that I am posting.
Any suggestions on what I may be doing wrong?
Try specifying the file type, just image_obj.content is the raw binary image:
r = requests.post(
url,
headers=headers,
files={'image': ('my_image.jpg', image_obj.content, 'image/jpg')})
This should add the correct headers to the multipart boundary for the image.
If you don't know for sure the content type, you might actually get it from the headers of your previous response: image_obj.headers['Content-Type'] should be "image/jpg" but for a different image it might be "image/png".
It wants a file extension, I'd hazard a guess that image should be image.<SOME_FORMAT>.
I have an application I wrote that downloads a file from a database service I use and then I convert the file to another format and re-upload. The issue is with the upload. I am using a patch request and it completes without errors but the file is never actually uploaded.
Here is my code:
for person in r['records']:
try:
# Get Voicemail and handle conversion if necessary
vm = person['fields']['Voicemail'][0]['url']
if '.m4a' in vm:
vm_name = person['fields']['Voicemail'][0]['filename'].replace('.m4a', '').replace(' ', '')
# Download file to local machine and convert to .mp3
r = requests.get(vm, allow_redirects=True)
open('{}.m4a'.format(vm_name), 'wb').write(r.content)
bash = 'ffmpeg {0}.mp3 -i {0}.m4a -codec:a libmp3lame -qscale:a 1'.format(vm_name)
os.system(bash)
s = requests.Session()
s.mount('file://', FileAdapter())
cwd = os.getcwd()
# url = s.get('file:///{}/{}.mp3'.format(cwd, vm_name))
# Upload/delete files to server
r = requests.patch('https://api.airtable.com/v0/{}/People/{}'.format(base_id, person['id']),
json={"fields": {"Voicemail": [{"url": 'file:///{}/{}.mp3'.format(cwd, vm_name)}]}},
headers={"Authorization": "Bearer {}".format(at_auth), "Content-type": "application/Json"})
print(r.text)
# Delete temporary local files
os.remove('{}.mp3'.format(vm_name))
os.remove('{}.m4a'.format(vm_name))
...And the response of r.text:
{"id":"recnlJBNEWFMLwYNh","fields":{"Name":"Matthew Sewell","Phone":["reciInRjmNpyTabUS"],"Voicemail":[{"id":"att7YiG4s0Epa3V6o","url":"file:////Users/test/Dropbox/python/projects/business/testing123.mp3","filename":"testing123.mp3"}]},"createdTime":"2018-08-09T00:59:35.000Z"}
I am not super familiar with patch requests so any help is appreciated.
Shamelessly copy pasted from another answer (i flagged the question). This is how you can upload data using requests. It doesnt matter if you use GET, POST, PATCH or whatever:
If upload_file is meant to be the file, use:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.
The original so post is here