automated note taking

The telegra.ph service has been around for many years, but for some reason there is not a lot of information on how to use its api, meanwhile, large telegram channels have slowly begun industrial development. The tool is quite a good alternative to creating web pages, in addition, a convenient library has appeared that allows you to automate the process.

How it all started:

I accidentally drew attention to the “View” button, which appeared on some telegram channels (“Earlier than all, well, almost”, and “RT in Russian”)

If you press the button, an article appears, apparently on telegra.ph, which is interesting, in the post itself there is a link to the site, and on the computer it leads there, but in the mobile version, there is such a view. I haven’t figured out the details of just such an implementation yet, but I immediately wanted to do auto-posting to the telegraph, and this will be the subject of a conversation.

Array of Node or the main snag of the Telegraph API and its resolution

In general, there is nothing complicated in the Telegraph API, the main problem was that you need to transfer the page content in the form Array of Node, up to 64 KB… Those. just write “Hello world” will not work (you need to write [“Hello world”]), but passing some markup is not easy at all, for example “Hello world “:

[
  {
  "tag": "b",
  "children": ["Hello world"]
  }
]

However, there is a solution, it is a library TelegraphHowever, I will try to tell you how to work without it. Let’s get started.

Create an account and get a token

Everything works through requests to https://api.telegra.ph/ after which the method is indicated and, if necessary, the path. You can do this as you like: curl from the command line, or requests.get () in python, or wherever you want. I will give an example of how it works in python.

To create a new account, you just need to make a request to https://api.telegra.ph/ with method indication createAccount:

import requests
#создаем параметры для создания профиля
data={
    'short_name':'', # ОБЯЗАТЕЛЬНЫЙ ПАРАМЕТР, имя учетной записи, помогает пользователям с несколькими учетными записями запомнить, какая сейчас используются. Отображается пользователю над кнопкой «Изменить / Опубликовать» на Telegra.ph, другие пользователи не видят это имя.
    'author_name':'', # Не обязательно. Указывает автора в заголовке странцы
    'author_url':'' # Не обязательно. Ссылка открывается, когда пользователи нажимают на имя автора под заголовком. Это может быть любая ссылка, не обязательно на профиль или канал Telegram.
}
#отправляем запрос ответ понадобится, запишем в переменную:
result=requests.get("https://api.telegra.ph/createAccount?", params=data)

From bash it will be like this:

curl https://api.telegra.ph/createAccount?short_name=Sandbox&author_name=Anonymous

With the telegraph library: you need to install it (pip install telegraph), and then everything is simple:

import requests
from telegraph import Telegraph

telegraph = Telegraph()

result=telegraph.create_account(short_name="1337")

In response, json comes with a token and so on. The token must be saved, I will save the received data to the graph_bot.json file

with open('graph_bot.json', 'w', encoding='utf-8') as f:
    json.dump(graph_bot, f, ensure_ascii=False, indent=4) # сохраняю в файл graph_bot

Result.json () output

{
    "ok":true,
    "result":
    {
        "short_name":"", #тут будет имя
        "author_name":"",
        "author_url":"",
        "access_token":"", #тут токен
        "auth_url":""
    }
}

Interestingly, I did not find a method for deleting a profile and pages. Account names are not unique, you can create as many profiles with the same name, the only difference will be in tokens.

Create a page (createPage)

We get the token from the saved json and send the request to create the page:

with open('graph_bot.json') as f:
    graph_bot = json.load(f)
#создание страницы
data={
    'access_token':graph_bot["access_token"],
    'title':'article_head', # Заголовок, обязательный параметр
    'author_name':graph_bot["author_name"], # это поле можно не заполнять
    'content': content_json,# Текст (массив Node), обязательный параметр
    'return_content':'false' # если стоит true в ответе придет и то, что размещено, если false, то поле не вернется
}
page=requests.get("https://api.telegra.ph/createPage?", params=data)

If everything goes well, the response will be something like this:

{
    'ok': True, 
    'result': 
    {
        'path': 'article-head-11-04-2', 
        'url': 'https://telegra.ph/article-head-11-04-2', 
        'title': 'article_head', 
        'description': '', 
        'author_name': 'Bot', 
        'views': 0, 
        'can_edit': True
    }
}

If there is an error in the sent data, a message about it is returned:

{
    'ok': False, 
    'error': 'CONTENT_FORMAT_INVALID' # передан не array of node
}

As I said above, the main problem here is the correct format of the transmitted text, a working parser html to node implemented in the telegraph library… Everything is simple here, you can save all the HTML in a string variable and safely pass it in the form of a corresponding field:

from telegraph import Telegraph

telegraph = Telegraph("access_token") # передаём токен доступ к страницам аккаунта
response = telegraph.create_page(
    'Hey', # заголовок страницы
    html_content="<p>Hello, world!</p>" # ставим параметр html_content, добавляем текст страницы
)

print('https://telegra.ph/{}'.format(response['path'])) # распечатываем адрес страницы

We get the page: https://telegra.ph/Hey-11-04-22

The library has a rather impressive list of prohibited tags, but telegra.ph is enough for a minimal layout

Modifying the page (editPage)

To change a page, you need to know its address, it comes after ph / for the page https://telegra.ph/Hey-11-04-22 the path parameter will be “Hey-11-04-22”. And of course, the access token. We send a request with the method and parameters to https://api.telegra.ph/editPage

data={
    'path':'Hey-11-04-22', #путь к странице он содержится в url после https://telegra.ph/
    'access_token':'your_token',  # токен
    'title':'article_head', #заголовок, обязательный параметр, если не меняется, всё равно надо прописывать
    'author_name':None,  
    'content': content_json,  #содержание страницы должен быть  Array of Node
    'return_content':'false' 
}
#редактирование страницы
requests.get("https://api.telegra.ph/editPage?", params=data)

Again, there is a problem in the format of the data, which should be an Array of Node. Let’s use a ready-made solution:

from telegraph import Telegraph

telegraph = Telegraph('access_token') # чтобы получить доступ к вашим страницам

telegraph.edit_page(
    path="", # обязательный параметр
    title="", # обязательный параметр
    html_content="",  #измененное содержание страницы, тут можно передать хоть строку с тегами, хоть руками написать что надо
    author_name="", # можно пропустить
    author_url="", # можно пропустить
    return_content=False    
)

In case of an error, the message {‘ok’: False, ‘error’: ‘error description’} is received. If all is well, the ‘ok’ status will be True.

What else is possible:

In general, it is enough to create and edit pages, I think the principle of operation is clear. You can also:

  • view and change account information,

  • revoke the token,

  • view your pages and

  • the number of views on them (doing analytics).

For example, profile information:

data={
    'access_token': "access_token",
    'fields':'["short_name","page_count"]'    
}
account_info=requests.get("https://api.telegra.ph/getAccountInfo?", params=data)
print(account_info.json())

Everything can be read in the documentation:

Telegraph API Documentation

Telegraph Python documentation Telegraph API wrapper

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *