Hey everyone! I’m working on a Python-based Telegram bot and I’m stuck on how to upload photos from my computer. I know I need to use multipart/form-data, but I’m having trouble figuring it out.
I’ve tried searching online and checking the Telegram docs, but I’m still confused. Here’s what I’ve attempted so far:
chat_info = {'chat_id': recipient_id}
image_file = {'image': open(f'./pictures/{user_id}.png', 'rb')}
response = requests.post('https://api.telegram.org/bot{API_KEY}/sendPhoto', data=chat_info, files=image_file)
This didn’t work though. Can anyone point me in the right direction? I’d really appreciate some guidance on how to properly send photos from my local machine using my Telegram bot. Thanks in advance!
I’ve gone through this exact issue while building my own Telegram bot. The key is to use the ‘photo’ parameter correctly and ensure you’re closing the file after sending. Here’s what worked for me:
import requests
with open(f'./pictures/{user_id}.png', 'rb') as photo:
files = {'photo': photo}
data = {'chat_id': recipient_id}
response = requests.post(f'https://api.telegram.org/bot{API_KEY}/sendPhoto', files=files, data=data)
if response.status_code == 200:
print('Photo sent successfully')
else:
print(f'Failed to send photo. Error: {response.text}')
This approach ensures the file is properly closed after sending. Also, double-check your API_KEY and make sure you have the necessary permissions for the bot. Let me know if you run into any other issues!
I encountered a similar issue when developing a Telegram bot for my company’s internal communication. The solution lies in proper file handling and correct parameter naming. Here’s what worked for me:
import requests
API_KEY = ‘your_api_key_here’
chat_id = ‘recipient_chat_id’
file_path = f’./pictures/{user_id}.png’
with open(file_path, ‘rb’) as photo_file:
files = {‘photo’: (‘image.png’, photo_file, ‘image/png’)}
data = {‘chat_id’: chat_id}
url = f’https://api.telegram.org/bot{API_KEY}/sendPhoto’
response = requests.post(url, files=files, data=data)
print(f’Status Code: {response.status_code}‘)
print(f’Response: {response.json()}’)
This approach ensures proper file closure and specifies the content type. Remember to replace the placeholder values with your actual API key and chat ID. If you’re still facing issues, check your bot’s permissions and the file path.
hey, i’ve dealt with this before. try using the ‘photo’ key instead of ‘image’ in your files dictionary. like this:
files = {'photo': open(f'./pictures/{user_id}.png', 'rb')}
also make sure your API_KEY is correct. hope this helps!