GithubHelp home page GithubHelp logo

pych's Introduction

PyCh

Codecov Travis (.com) Checked with mypy GitHub issues by-label GitHub stars

          _____                _____                    _____                    _____          
         /\    \              |\    \                  /\    \                  /\    \         
        /::\    \             |:\____\                /::\    \                /::\____\        
       /::::\    \            |::|   |               /::::\    \              /:::/    /        
      /::::::\    \           |::|   |              /::::::\    \            /:::/    /         
     /:::/\:::\    \          |::|   |             /:::/\:::\    \          /:::/    /          
    /:::/__\:::\    \         |::|   |            /:::/  \:::\    \        /:::/____/           
   /::::\   \:::\    \        |::|   |           /:::/    \:::\    \      /::::\    \           
  /::::::\   \:::\    \       |::|___|______    /:::/    / \:::\    \    /::::::\    \   _____  
 /:::/\:::\   \:::\____\      /::::::::\    \  /:::/    /   \:::\    \  /:::/\:::\    \ /\    \ 
/:::/  \:::\   \:::|    |    /::::::::::\____\/:::/____/     \:::\____\/:::/  \:::\    /::\____\
\::/    \:::\  /:::|____|   /:::/~~~~/~~      \:::\    \      \::/    /\::/    \:::\  /:::/    /
 \/_____/\:::\/:::/    /   /:::/    /          \:::\    \      \/____/  \/____/ \:::\/:::/    / 
          \::::::/    /   /:::/    /            \:::\    \                       \::::::/    /  
           \::::/    /   /:::/    /              \:::\    \                       \::::/    /   
            \::/____/    \::/    /                \:::\    \                      /:::/    /    
             ~~           \/____/                  \:::\    \                    /:::/    /     
                                                    \:::\    \                  /:::/    /      
                                                     \:::\____\                /:::/    /       
                                                      \::/    /                \::/    /        
                                                       \/____/                  \/____/         

Usage

Download pych:

$ pip install pych

First import:

>>> from pych.catalog import Catalog

Get threads list:

>>> catalog = Catalog('b')
>>> catalog.threads
[<Thread board="b" #200000001 "Тема треда">...]

Get thread info:

>>> thread = catalog.threads.pop()  # Get last thread
 
>>> thread.subject
'%%Тема треда%%'

Get thread post:

>>> thread.posts
[<Post #201306703>, <Post #201306882>, <Post #201308883>]

>>> OP = thread.posts[0]
>>> OP.comment
'Даже у него есть тян'

Get post files:

>>> OP.files

Docs

class pych.catalog.Catalog(board: str)

Threads catalog class. Accepts the name of the board.

Catalog.board

type: str

The board short name.

Catalog.threads

type: Threads[]

Threads list in specified board. (Lazy property, loads only when called.)

class pych.file.File(**kwargs)

Attachment file in post.

File.displayname

type: str

Cropped attachment display name.

File.fullname

type: str

Full attachment display name.

File.height

type: int

Height of attachment in pixels.

File.md5

type: str

MD5 hash sum of attachment.

File.name

type: str

Server file name.

File.nsfw

type: int

...

File.path

type: str

Full URL to file.

File.size

type: int

Size of attachment in bytes.

File.thumbnail

type: str

Full URL to attachment thumbnail.

File.tn_height

type: int

The attachment thumbnail height.

File.tn_width

type: int

The attachment thumbnail width.

File.type

type: int

The attachment type.

  1. jpg
  2. png
  3. webm
  4. mp4/mov

File.width

type: int

The attachment file width.

File.download(destination: str) -> None

Download and save file to specified destination.

class pych.post.Post(**kwargs)

Post.board

type: str

Post board name.

Post.banned

type: int

...

Post.closed

type: int

...

Post.comment

type: str

Post text with markdown tags.

Post.date

type: str

Datetime posted.

Post.email

type: str

Post author email.

Post.endless

type: int

...

Post.files

type: File[]

List of File instances.

Post.lasthit

type: int

...

Post.name

type: str

Post author name.

Post.num

type: int

Global post id.

Post.number

type: int

Post id regarding thread.

Post.op

type: int

Flag OP.

Post.parent

type: str

Parent thread post.

Post.sticky

type: int

...

Post.subject

type: str

Thread post subject.

Post.timestamp

type: int

Timestamp when posted.

Post.trip

type: str

...

class pych.thread.Thread(**kwargs)

Thread.board

type: str

Thread board name.

Thread.comment

type: str

Thread OP text with markdown.

Thread.lasthit

type: int

...

Thread.num

type: str

Thread OP id.

Thread.posts_count

type: int

Count of posts inside thread.

Thread.score

type: float

Score of the thread.

Thread.subject

type: str

Thread subject.

Thread.timestamp

type: int

Thread created timestamp.

Thread.views

type: int

Count of views of thread.

Thread.url

type: str

Thread full URL.

Thread.posts

type: Post[]

Get thread posts list.

def pych.info.boards() -> Dict[str, str]

returns: Dict[str, str]

Get boards. Returns dict where key is a board id and value is a board name.

For example: { "b": "Бред" }.

pych's People

Contributors

ya7on avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

pych's Issues

Добавить возможность постинга в треде

Нужно добавить метод .post(*args, **kwargs) у класса pych.thread.Thread(), который позволит отправить пост в тред, к которому привязан класс

Принимать должен все параметры, которые принимает эндпоинт и на которые может влиять пользователь. То есть, давать возможность изменять параметр thread или json не надо.

Нормальной документации у Двача нет, есть только короткий текст про ридонли эндпоинты в /api/.

Но можно найти старые треды, где упоминается эндпоинт https://2ch.hk/makaba/posting.fcgi, который обсуждался здесь.

Также есть Github gist, в котором на JS описан алгоритм создания нового треда, который отличается от постинга в тред одним параметром thread (0 - новый тред, айди OP для ответа в тред)
Вот собственно сам гист

Add boards info

Create module with dict, that will contain information about known boards

Перенести README из md в rst

Нужно оставить только один README вместо имеющихся сейчас двух (md и rst).

  1. Markdown формат не поддерживается в PyPi, поэтому его оставлять не очень хочется.
  2. reStructuredText поддерживается PyPi и GitHub, и имеет подстветку синтаксиса для питона, поэтому останавливаемся на нём.

Сейчас вся имеющаяся документация находится в README.md. Можно попробовать использовать автоматические конвертеры из markdown в restructuredtext, если таковые имеются.

Пускать запросы к API через прокси

Нужно добавить глобальную настройку, которая будет пускать все запросы к API через пользовательские прокси.
Нужны предложения как это будет выглядеть.

Добавить возможность создания новых тредов

Нужно создать медод .create(*args, **kwargs) у класса pych.catalog.Catalog(), который будет отвечать за создание нового треда. Отправлять запрос он должен на тот же эндпоинт, который отвечает за постинг сообщений в тред, поэтому можно подглядеть в предыдущий ишью, в котором я описал принцип работы отправки сообщений в тред.
Здесь будет то же самое, только атрибут thread будет равен 0, а не айдишнику родительского треда.

Предыдущий ишью, в котором больше информации #12

Write README

Add docs, example of using and guide for developers

Добавить возможность скачивания файла

Нужно добавить метод .download(destination: str) -> None: для класса pych.file.File().
Метод принимает один аргумент destination, который является путём к месту, куда необходимо сохранить файл. URL файла есть в атрибутах класса. Пользоваться надо только библиотекой requests, которая уже находится в зависимостя.

Добавить фильтрацию тредов

Значение Catalog().threads теперь должно возвращать новый класс, наследуемый от типа list. Этот класс будет:

  • содержать все треды, которые есть в этом каталоге;
  • называться, например, ThreadsList;
  • иметь методы .find, который будет возвращать один найденый по указанным критериям, и .filter, который будет возвращать ThreadsList с отфильтрованными тредами.
    Эти методы должны принимать 1 аргумент с лямбда-функцией для фильтрации (как build-in функции filter, map и т.д.).

Примерно должно выглядеть как QuerySet в django.

Пример использования:

>>> threads = Catalog('test').threads
>>> threads.filter(lambda thread: 'webm' in thread.comment)
<ThreadsList [список отфильтрованных тредов]>

Перевести README на русский язык

Вряд ли кому-то англоговорящему понадобится эта библиотека, поэтому лучше сразу всю документацию перевести на великий и могучий.

Добавить возможность перевода файла в байты

Нужно добавить метод .tobytes() -> bytes у класса pych.file.File(), который будет получать файл по URL и возвращать тип данных bytes.
У типа requests.Response есть атрибут .content, который вернет байткод файла.

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.