0

I'm trying to upload a file which is an image to a Telegraph page via its API. Everything works fine if I send a link, an url to a file which is already uploaded to web.

url_telegraph_API = 'https://api.telegra.ph/'

short_name = 'forecast_bot_help'
access_token = 'my_token'
path = 'Kak-byl-poluchen-prognoz-kursa-12-06-9'
just_image_url = 'https://www.import.io/wp-content/uploads/2021/02/manuel-t-xf1nszrKH_s- 
unsplash-scaled.jpg'

content_update = \
    [
    {'tag': 'strong', 'id': 'Node', 'children': ['''Конечно, никакого сигнала из Космоса не 
    было. 
    Да и ИИ, искуственный интеллект, - всего лишь генератор случайных чисел.'''], },
    {'tag': 'br'},
    {'tag': 'figure', 'children': [
    {'tag': 'img', 'attrs': {'src': just_image_url}},
    {'tag': 'figcaption'}
    ]},
    {"tag":"p","children":["test"]},
    {'tag': 'i', 'children':['''Но точность многих предсказаний курсов имееет такую же 
    ценность.''', 
     {'tag': 'i', 'children': [' В чем не сложно убедиться.']}]},
    {'tag': 'br'},
    {'tag': 'p', 'children': ['Поэтому улыбнитесь и двигайтесь дальше.']}
    ]

cont = json.dumps(content_update)
command = 'editPage?'
params = {
    'access_token': access_token,
    'path': path,
    'title': title,
    'author_name': author_name,
    'auth_url': auth_url,
    'content': cont, 
    'return_content': True
}
url = f'{url_telegraph_API}{command}'
create_page = requests.post(url, json=params)

My question is does it exist any method to

  • upload a local file to Telegraph via API;
  • get its url.

I've been trying to apply

def telegraph_file_upload(file):
    
    url_telegraph_API = 'https://api.telegra.ph/'
    command = 'upload'
    params = {'file': file}
    url = f'{url_telegraph_API}{command}'
    response = requests.get(url, params=params)
    
    return response

with open('test_image.jpg', 'rb') as f:
    file = f.read()

r = telegraph_file_upload(file)
print(r.content())

But with NO success so far. Any idea?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Sergey Solod
  • 695
  • 7
  • 15

1 Answers1

1

Eventually it works

def telegraph_file_upload(path_to_file):
    '''
    Sends a file to telegra.ph storage and returns its url
    Works ONLY with 'gif', 'jpeg', 'jpg', 'png', 'mp4' 
    
    Parameters
    ---------------
    path_to_file -> str, path to a local file
    
    Return
    ---------------
    telegraph_url -> str, url of the file uploaded

    >>>telegraph_file_upload('test_image.jpg')
    https://telegra.ph/file/16016bafcf4eca0ce3e2b.jpg    
    >>>telegraph_file_upload('untitled.txt')
    error, txt-file can not be processed
    '''
    file_types = {'gif': 'image/gif', 'jpeg': 'image/jpeg', 'jpg': 'image/jpg', 'png': 'image/png', 'mp4': 'video/mp4'}
    file_ext = path_to_file.split('.')[-1]
    
    if file_ext in file_types:
        file_type = file_types[file_ext]
    else:
        return f'error, {file_ext}-file can not be proccessed' 
      
    with open(path_to_file, 'rb') as f:
        url = 'https://telegra.ph/upload'
        response = requests.post(url, files={'file': ('file', f, file_type)}, timeout=1)
    
    telegraph_url = json.loads(response.content)
    telegraph_url = telegraph_url[0]['src']
    telegraph_url = f'https://telegra.ph{telegraph_url}'
    
    return telegraph_url

Sending via API api.telagra.ph was my mistake.

telagra.ph should be used instead.

Sergey Solod
  • 695
  • 7
  • 15