Giter Site home page Giter Site logo

telegraph's People

Contributors

blue-bird1 avatar looyun avatar paradox70 avatar python273 avatar spechide avatar weakish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegraph's Issues

upload_file Error

File "/usr/local/lib/python3.8/site-packages/telegraph/upload.py", line 13, in upload_file
r = TelegraphApi().upload_file(f)
File "/usr/local/lib/python3.8/site-packages/telegraph/api.py", line 56, in upload_file
response = self.session.post(
File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 975, in json
RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Can we make configurable requests?

Hi, I am using your package to generate telegraph automatically. I need to set the timeout for requests to avoid the process hanging/freezing. As I notice that you are using requests and it's configurable, can you expose some of the requests's APIs so that I make configured requests? Something like telegraph.create_page(url, **kwagrs) would be good. Thanks a lot!

How to upload files (images, etc.)

It's not an issue, I just want to share this code

from telegraph import Telegraph, upload

telegraph = Telegraph()
telegraph.create_account(short_name='LetsTry')

def post(title, content):
	response = telegraph.create_page(title,
									 html_content = content)
	return 'https://telegra.ph/{}'.format(response['path'])

files = '/Users/vovkapultik/Downloads/52920087_159420908268041_6560105268061929472_n.jpg'

imgpath = upload.upload_file(files)

print(imgpath)

#['/file/02a1613fc106b225b2b74.jpg']

postlink = post('Title', '<img src="/file/02a1613fc106b225b2b74.jpg">')

print(postlink)

New functions

Hi. I think you can add a photo/video function to this library. It will be very usefull :)

No InstantView?

When I create Telegraph articles using this wrapper and post to the mobile app, they do not get converted to Instant View.

Anyone know why?

hide link preview

Hi!
It's me again :)

Not a real issue, so feel free to close/ban the issue even if no answer is available.

I recently played with telegram bots and in the bot API there is a keyword, 'disable_web_page_preview' used to hide the preview.
I wanted to know if there exist such a way to hide instant view article preview, showing only the button, since if I use that keyword, content is not previewed and whenever I click the link, my external Android browser fires up (which is bad because I want preview)
Hope I've been clear,
Thanks.

TelegraphException: CONTENT_TOO_BIG

I found the max langth is about 10917 * 6.
If i use Chinese character the num will be 10917.
But i can put more than 20000 Chinese character in web telegra.ph.
Is there some reason for this difference?

from telegraph import Telegraph

telegraph = Telegraph()

telegraph.create_account(short_name="1337")


# this will success

telegraph.create_page('page_title', html_content='<p>{}</p>'.format("从"*10917))
# or 
telegraph.create_page('page_title', html_content='<p>{}</p>'.format("a"*10917 * 6))

# but this will failed 
# TelegraphException: CONTENT_TOO_BIG

telegraph.create_page('page_title', html_content='<p>{}</p>'.format("从"*10918))
# or 
telegraph.create_page('page_title', html_content='<p>{}</p>'.format("a"*10918 * 6))

error install windows 10 -python3.7

C:\Users\guilh>pip install telegraph
Collecting telegraph
Using cached telegraph-1.4.1.tar.gz (6.1 kB)
ERROR: Command errored out with exit status 1:
command: 'c:\users\guilh\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\guilh\AppData\Local\Temp\pip-install-meatektr\telegraph\setup.py'"'"'; file='"'"'C:\Users\guilh\AppData\Local\Temp\pip-install-meatektr\telegraph\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\guilh\AppData\Local\Temp\pip-pip-egg-info-vmcv64wz'
cwd: C:\Users\guilh\AppData\Local\Temp\pip-install-meatektr\telegraph
Complete output (28 lines):
Traceback (most recent call last):
File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\pkg_resources_init_.py", line 2866, in get_entry_map
ep_map = self.ep_map
File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\pkg_resources_init
.py", line 2824, in getattr
raise AttributeError(attr)
AttributeError: _ep_map

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\guilh\AppData\Local\Temp\pip-install-meatektr\telegraph\setup.py", line 58, in <module>
    'Programming Language :: Python :: Implementation :: CPython',
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 164, in setup
    _install_setup_requires(attrs)
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 154, in _install_setup_requires
    dist = MinimalDistribution(attrs)
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 146, in __init__
    distutils.core.Distribution.__init__(self, filtered)
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\setuptools\dist.py", line 427, in __init__
    for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\pkg_resources\__init__.py", line 655, in <genexpr>
    for entry in dist.get_entry_map(group).values()
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\pkg_resources\__init__.py", line 2869, in get_entry_map
    self._get_metadata('entry_points.txt'), self
  File "c:\users\guilh\appdata\local\programs\python\python37\lib\site-packages\pkg_resources\__init__.py", line 2549, in parse_map
    raise ValueError("Entry points must be listed in groups")
ValueError: Entry points must be listed in groups
----------------------------------------

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Error importing

the example script gives error importinga ( already made pip install telegraph)

python /home/scripts/telegraph.py
Traceback (most recent call last):
File "/home/scripts/telegraph.py", line 1, in
from telegraph import Telegraph
File "/home/scripts/telegraph.py", line 1, in
from telegraph import Telegraph
ImportError: cannot import name Telegraph

Significantly reduce size of payload

When creating telegraph page, by default requests.post is sending data with
'Content-type': 'application/x-www-form-urlencoded'

It's huge, because json payload is percent-encoded, for example this dict (43 bytes):
{"key": "value with non-ascii: абвгд"}
looks like this when sending request (97 bytes):
%7B%22key%22%3A%20%22value%20with%20non-ascii%3A%20%5Cu0430%5Cu0431%5Cu0432%5Cu0433%5Cu0434%22%7D

Telegra.ph accepts 'Content-Type': 'application/json' header and you can use this feature instead to avoid percent-encoding.

  1. Use 'Content-Type': 'application/json' instead of default percent-encoding
  2. Use json.dumps(data, ensure_ascii=False). Telegra.ph accepts utf-8 and no need to escape into \uXXXX for non-ascii characters.
  3. Use separators without spaces json.dumps(data, ensure_ascii=False, separators=(',', ':'))
  4. Also you don't need to separately convert content property to string, it can be sent like regular json

Unfortunately, this will not help to put more than 64 kb on a page, it helps only for reducing network overhead.

page html_content

Hi all ,
i'm trying to create a page it is possibile usage the following method
new_page = t.create_page(title="xxxxxxx", html_content=content)
where content is assigned in this way content = codecs.open("file.html","r")

'Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')

response = telegraph.create_page(search, author_name=searchresult[0]['artists'][0]['name'], author_url=f"https://music.youtube.com/channel/{searchresult[0]['artists'][0]['id']}", html_content=l['lyrics'].replace("\n", "<br>"))

I met this error when I am trying to create a page on telegra.ph using this module

Traceback (most recent call last):
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 449, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 444, in _make_request
    httplib_response = conn.getresponse()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 1348, in getresponse
    response.begin()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 316, in begin
    version, status, reason = self._read_status()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 277, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
ConnectionResetError: [Errno 104] Connection reset by peer
 
During handling of the above exception, another exception occurred:
 
Traceback (most recent call last):
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/requests/adapters.py", line 489, in send
    resp = conn.urlopen(
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 787, in urlopen
    retries = retries.increment(
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/util/retry.py", line 550, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/packages/six.py", line 769, in reraise
    raise value.with_traceback(tb)
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 449, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 444, in _make_request
    httplib_response = conn.getresponse()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 1348, in getresponse
    response.begin()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 316, in begin
    version, status, reason = self._read_status()
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/http/client.py", line 277, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
 
During handling of the above exception, another exception occurred:
 
Traceback (most recent call last):
  File "main.py", line 295, in searchlyrics
    response = telegraph.create_page(search, author_name=searchresult[0]['artists'][0]['name'], author_url=f"https://music.youtube.com/channel/{searchresult[0]['artists'][0]['id']}", html_content=l['lyrics'].replace("\n", "<br>"))
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/telegraph/api.py", line 183, in create_page
    return self._telegraph.method('createPage', values={
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/telegraph/api.py", line 32, in method
    response = self.session.post(
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/requests/sessions.py", line 635, in post
    return self.request("POST", url, data=data, json=json, **kwargs)
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/requests/sessions.py", line 587, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/requests/sessions.py", line 701, in send
    r = adapter.send(request, **kwargs)
  File "/home/runner/billy-telegram/venv/lib/python3.8/site-packages/requests/adapters.py", line 547, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

Any help or suggestion would be appreciated

Images are posted in the end

Hello

Every time I want to post something using this wrapper images are posted in the end of an article even though I put them somewhere else.

For instance, executing this code:

from telegraph import Telegraph

telegraph = Telegraph()

telegraph.create_account(short_name='test')

html = '''
<p>some text</p>
<img src='https://www.w3schools.com/css/img_fjords.jpg'/>
<p>more text</p>
'''

response = telegraph.create_page(
    'test',
    html_content=html)

print('http://telegra.ph/{}'.format(response['path']))

produces this article. It doesn't matter whether I add <figure><figcaption></figcaption></figure> or not, all images are always after the text in random order.

JSONDecodeError when edit page

Get error when simply try to edit page.

File "C:\Users\Soulbadguy\PycharmProjects\match_parsers\objects\telegraph.py", line 80, in _act_telegraph
  page = await func(**func_args)
File "C:\Users\Soulbadguy\PycharmProjects\match_parsers\.venv\lib\site-packages\telegraph\aio.py", line 209, in edit_page
  return (await self._telegraph.method('editPage', path=path, values={
File "C:\Users\Soulbadguy\PycharmProjects\match_parsers\.venv\lib\site-packages\telegraph\aio.py", line 32, in method
  response = (await self.session.post(
File "C:\Users\Soulbadguy\PycharmProjects\match_parsers\.venv\lib\site-packages\httpx\_models.py", line 742, in json
  return jsonlib.loads(self.content.decode(encoding), **kwargs)
File "C:\Users\Soulbadguy\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
  return _default_decoder.decode(s)
File "C:\Users\Soulbadguy\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
  obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Soulbadguy\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
  raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The args are right, the hltm content dont have any unclosed tags, but simply get this error...

The funniest thing consists in the fix for this problem. Just rerun and rerun the request without any changes. And at 5th or 6th try (ususally) the problem is fixed...

When i dont get error, i obviously get response.status 200 and json object as response. But sometimes i get 500 status with that NOT JSON body, that raise the exeption:

<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>

requests.exceptions.JSONDecodeError at Telegraph.create_page

I have a Telegram bot that creates Telegraph pages with some user stats.
Sometimes it raises requests.exceptions.JSONDecodeError at Telegraph.create_page:

File "/root/botty/main.py", line 474, in user_stats
    telegraph_response = telegraph.create_page(stats_page_title,
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/telegraph/api.py", line 183, in create_page
    return self._telegraph.method('createPage', values={
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/telegraph/api.py", line 35, in method
    ).json()
      ^^^^^^
  File "/usr/local/lib/python3.11/dist-packages/requests/models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What's strange is that if you try to call Telegraph.create_page again - it runs flawlessly.
So I ended up with "fuckit" strategy:

try:
    telegraph_response = telegraph.create_page(stats_page_title,
                                               html_content=stats_page_text,
                                               author_name=bot_name,
                                               author_url=bot_link)
except requests.exceptions.JSONDecodeError:  # fuck it
    telegraph_response = telegraph.create_page(stats_page_title,
                                               html_content=stats_page_text,
                                               author_name=bot_name,
                                               author_url=bot_link)

I suspect this could be fixed if we could pass in timeout argument to inner post request.

def create_page(self, title, content=None, html_content=None,
                author_name=None, author_url=None, return_content=False, timeout=0):
    ...

    return self._telegraph.method('createPage', values={
       'title': title,
       'author_name': author_name,
       'author_url': author_url,
       'content': content_json,
       'return_content': return_content
    }, timeout=timeout)
def method(self, method, values=None, path='', timeout=0):
    ...

    response = self.session.post(
        'https://api.{}/{}/{}'.format(self.domain, method, path),
        data=values, timeout=timeout
    ).json()

   ...

Can't install the package through pip

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. as i type "python3.7 -m pip install telegraph"

how insert &nbsp;?

Hello everyone. How i can insert &nbsp?
For example, if i sent text-1&nbsp;text2 everything OK
But if i try sent

<b>test-1</b>&nbsp;test-2

space don't show, text is stuck together
what i must to do?

not correctly:
image

Doesn't want to add content in the form of pictures

Everything works successfully until I try to add pictures to my telegraph page.
Looking through the source code of the telegram page, I realized that this code seems to be completely ignored.
Source codes of my application are below

content = "<p>" + artist + "<br>" + str(pages) + "</p>"
#this work ok
    for i in range(pages):
        urllib.request.urlretrieve(f"http://{config.STORE_SERVER}/content/{url}/img{str(i+1)}.jpg",
                                   f"img_temp{str(i+1)}.jpg")
        tmp_link = upload.upload_file(f"img_temp{str(i+1)}.jpg")
        content = content + f"<img src=\'{tmp_link[2:-2]}\'>"
        #this don't work`

JSON exception when uploading images

Hello, from a few days ago I'm getting below error when trying to upload images to Telegraph. It has been working like a charm for almos half a year now, so I don't know why now I'm having this issue. I'm not sure if it's a server side issue or something else. Any idea? Thanks in advance!

url = telegraph.upload.upload_file(image_name)
File "/telegraph/upload.py", line 18, in upload_file
files=files
File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/models.py", line 850, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.