def login(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None:
    sender = message.get_sender_contact()
    with session_scope() as session:
        acc = session.query(Account).filter_by(addr=sender.addr).first()  # noqa
        if acc:
            replies.add(text="❌ You are already logged in.")
            return

    args = payload.split(maxsplit=2)
    if len(args) == 3:
        client = wf.client(host=args[0], user=args[1], password=args[2])
    else:
        client = wf.client(host=args[0], token=args[1])

    acc = Account(addr=sender.addr, host=client.host, token=client.token)
    for blog in client.get_collections():
        group = bot.create_group(f"📝 {blog['title'] or blog['alias']}", [sender])
        acc.blogs.append(Blog(chat_id=group.id, alias=blog["alias"]))
        replies.add(
            text="All messages sent here will be published to blog:\n"
            f"Alias: {blog['alias']}\nDescription: {blog['description']}",
            chat=group,
        )
    with session_scope() as session:
        session.add(acc)  # noqa
    replies.add(text="✔️Logged in")
示例#2
0
def wf_logout(message: Message, replies: Replies) -> None:
    """Logout from your WriteFreely instance.

    Example: `/wf_logout`
    """
    addr = message.get_sender_contact().addr
    acc = db.get_account(addr)
    if acc:
        db.del_account(addr)
        wf.client(host=acc['host'], token=acc['token']).logout()
        replies.add(text='✔️Logged out')
    else:
        replies.add(text='❌ You are not logged in.')
def logout(bot: DeltaBot, message: Message, replies: Replies) -> None:
    addr = message.get_sender_contact().addr
    try:
        with session_scope() as session:
            acc = session.query(Account).filter_by(addr=addr).one()  # noqa
            host, token = acc.host, acc.token
            chats = [blog.chat_id for blog in acc.blogs]
            session.delete(acc)  # noqa
        wf.client(host=host, token=token).logout()
        for chat_id in chats:
            try:
                bot.get_chat(chat_id).remove_contact(bot.self_contact)
            except ValueError as ex:
                bot.logger.exception(ex)
        replies.add(text="✔️Logged out")
    except NoResultFound:
        replies.add(text="❌ You are not logged in.")
示例#4
0
def cmd_login(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None:
    """Login to your WriteFreely instance.

    Example: `/wf_login https://write.as YourUser YourPassword` or
    `/wf_login https://write.as YourToken`
    """
    sender = message.get_sender_contact()
    args = payload.split(maxsplit=2)
    if len(args) == 3:
        client = wf.client(host=args[0], user=args[1], password=args[2])
    else:
        client = wf.client(host=args[0], token=args[1])
    db.add_account(sender.addr, client.host, client.token)
    for blog in client.get_collections():
        g = bot.create_group(
            '{} [WF]'.format(blog['title'] or blog['alias']), [sender])
        db.add_chat(g.id, blog['alias'], sender.addr)
        replies.add(text='All messages sent here will be published to'
                    ' blog:\nAlias: {}\nDescription: {}'.format(
                        blog['alias'], blog['description']), chat=g)
    replies.add(text='✔️Logged in')
示例#5
0
def test_collections(requests_mock) -> None:
    client = wf.client(token="test-token")

    requests_mock.post("https://write.as/api/collections",
                       json={"data": "test-data1"})
    assert client.create_collection(alias="test-alias") == "test-data1"

    requests_mock.get("https://write.as/api/collections/test-alias",
                      json={"data": "test-data2"})
    assert client.get_collection(alias="test-alias") == "test-data2"

    requests_mock.get("https://write.as/api/me/collections",
                      json={"data": "test-data3"})
    assert client.get_collections() == "test-data3"
示例#6
0
def test_account(requests_mock) -> None:
    client = wf.client(token="test-token1")
    assert client.token == "test-token1"

    client = wf.client()
    assert client.host == "https://write.as"
    assert client.token is None
    assert not client.is_authenticated()
    requests_mock.post(
        "https://write.as/api/auth/login",
        json={"data": {
            "access_token": "test-token2"
        }},
    )
    client.login("test-user2", "test-password2")
    assert client.token == "test-token2"
    assert client.is_authenticated()

    requests_mock.post(
        "https://example.com/api/auth/login",
        json={"data": {
            "access_token": "test-token3"
        }},
    )
    client = wf.client(host="https://example.com",
                       user="******",
                       password="******")
    assert client.host == "https://example.com"
    assert client.token == "test-token3"

    requests_mock.get("https://example.com/api/me", json={"data": "test-data"})
    assert client.me() == "test-data"

    requests_mock.delete("https://example.com/api/auth/me")
    client.logout()
    assert client.token is None
    assert not client.is_authenticated()
示例#7
0
def test_posts(requests_mock) -> None:
    client = wf.client(token="test-token")

    requests_mock.post("https://write.as/api/posts",
                       json={"data": "test-data1"})
    post = client.create_post(title="Hello World!", body="test body")
    assert post == "test-data1"

    requests_mock.get("https://write.as/api/posts/1234",
                      json={"data": "test-data2"})
    post = client.get_post("1234")
    assert post == "test-data2"

    requests_mock.get("https://write.as/api/me/posts",
                      json={"data": "test-data3"})
    assert client.get_posts() == "test-data3"
def filter_messages(message: Message, replies: Replies) -> None:
    """All messages sent in a WriteFreely blog group will be published to the respective blog."""
    with session_scope() as session:
        blog = session.query(Blog).filter_by(chat_id=message.chat.id).first()  # noqa
        if blog:
            host, token = blog.account.host, blog.account.token
            alias = blog.alias
        else:
            return

    if message.text.startswith("# "):
        args = message.text.split("\n", maxsplit=1)
        title = args.pop(0)[2:] if len(args) == 2 else None
        body = args.pop(0).strip()
    else:
        title, body = None, message.text

    client = wf.client(host=host, token=token)
    post = client.create_post(collection=alias, title=title, body=body)
    replies.add(text=post["collection"]["url"] + post["slug"], quote=message)
示例#9
0
def wf_bridge(payload: str, message: Message, replies: Replies) -> None:
    """Bridge chat with a WriteFreely blog.

    Example: `/wf_bridge myblog`
    """
    addr = message.get_sender_contact().addr
    acc = db.get_account(addr)
    if not acc:
        replies.add(text='❌ You are not logged in.')
        return

    client = wf.client(host=acc['host'], token=acc['token'])
    blogs = [blog['alias'] for blog in client.get_collections()]
    if payload not in blogs:
        replies.add(
            text='❌ Invalid blog name, your blogs:\n{}'.format(
                '\n'.join(blogs)))
        return
    db.add_chat(message.chat.id, payload, addr)
    text = '✔️All messages sent here will be published in {}/{}'
    replies.add(text=text.format(acc['host'], payload))
示例#10
0
def filter_messages(message: Message, replies: Replies) -> None:
    """Process messages sent to WriteFreely groups.
    """
    chat = db.get_chat(message.chat.id)
    if not chat or not message.text:
        return

    if message.text.startswith('# '):
        args = message.text.split('\n', maxsplit=1)
        title = args.pop(0)[2:] if len(args) == 2 else None
        body = args.pop(0).strip()
    else:
        title, body = None, message.text

    acc = db.get_account(chat['account'])
    assert acc
    client = wf.client(host=acc['host'], token=acc['token'])
    post = client.create_post(
        collection=chat['blog'], title=title, body=body)
    replies.add(
        text=post['collection']['url'] + post['slug'], quote=message)
示例#11
0
def getAll(alias):
    c = writefreely.client('write.house')

    list = []

    # I assume 100 posts is more than generous!
    for i in range(1, 100):
        # Iterate through the pages...
        cposts = c.retrieveCPosts(alias, i)
        posts = cposts['posts']
        # If the posts are not an empty list, take each post and put it in a list!
        # That way it catches pages that don't have 10 posts
        if posts != []:
            for post in posts:
                # Append to the list of posts
                list.append(post)

        else:
            break

    return list
示例#12
0
import writefreely as wf

c = wf.client(token="XXXXXXX")

# creating a collection
c.create_collection(alias="my-blog", title="My Blog")

# getting one collection
blog = c.get_collection("my-blog")
print("Title: {}\nDescription: {}\nURL:{}".format(blog["title"],
                                                  blog["description"],
                                                  blog["url"]))

# getting all collections
for b in c.get_collections():
    print("{} has {} views and {} posts.".format(b["title"], b["views"],
                                                 b["total_posts"]))

# updating a collection
c.update_collection(
    "my-blog",
    title="New title",
    visibility=1,  # make blog public
)

# deleting a collection
c.delete_collection("my-blog")
示例#13
0
import writefreely as wf

# default WriteFreely instance is 'https://write.as'
c = wf.client(user="******", password="******")

# create a post
post = c.create_post(title="Hello World!", body="Hello from **Python**")

print("See your post at: {}/{}".format(c.host, post["slug"]))

# discard current session, invalidate authentication token
c.logout()
示例#14
0
# WRITEFREELY VALUES
# Domain of the WriteFreely instance - ex: write.house/bix -> 'write.house'
domain = ''
# The WriteFreely slug for the blog = ex: write.house/bix -> 'bix'
wfcollection = ''

# Instanciate Write.as Client
c = writeas.client()

# Log in with Write.as
user = c.login(username, password)
c.setToken(user['access_token'])

# Instantiate WriteFreely client
wf = writefreely.client(domain)

list = []

# I assume 500 posts is more than generous!
for i in range(1, 50):
    # Iterate through the pages...
    cposts = wf.retrieveCPosts(wfcollection, i)
    posts = cposts['posts']
    # If the posts are not an empty list, take each post and put it in a list!
    # That way it catches pages that don't have 10 posts
    if posts != []:
        for post in posts:
            # Append to the list of posts
            list.append(post)
示例#15
0
import writefreely as wf

c = wf.client(host="qua.name", user="******", password="******")

# saving token to avoid login each time:
with open("my_token.txt", "w") as fd:
    fd.write(c.token)

# create an authenticated post
post = c.create_post(title="Cool Post", body="Awesome content!")
print("See your post at: {}/{}".format(c.host, post["slug"]))

# next time, load token from file:
with open("my_token.txt") as fd:
    c = wf.client(host="qua.name", token=fd.read())

print("User Name:", c.me()["username"])  # User Name: foo

c.logout()
# The access token isn't valid anymore

assert not c.is_authenticated()

# create an anonymous post (not allowed by all instances)
post = c.create_post(title="Anonymous Post", body="Guess who am I?")
print("See your post at: {}/{}".format(c.host, post["slug"]))

c.me()  # raises an error because that request can't be done unauthenticated
示例#16
0
import writefreely as wf

# default WriteFreely instance is 'https://write.as'
c = wf.client(user='******', password='******')

# create a post
post = c.create_post(title='Hello World!', body='Hello from **Python**')

print('See your post at: {}/{}'.format(c.host, post['slug']))

# discard current session, invalidate authentication token
c.logout()
示例#17
0
import writefreely as wf

c = wf.client(token='XXXXXXX')

# create draft post
draft = c.create_post(title='Cool Post', body='Awesome content!')

# publish draft in collection/blog "my-blog"
post = c.move_post(draft['id'], collection='my-blog')
print('See your post at: {}/my-blog/{}'.format(c.host, post['slug']))

assert c.get_post(draft['id'])['slug'] == post['slug']

# publish a post directly to a collection
post = c.create_post(collection='my-blog',
                     title='Another Post',
                     body='Still **Awesome**')
print('See your post at: {}/my-blog/{}'.format(c.host, post['slug']))

# getting a post by slug from a collection
post2 = c.get_post(post['slug'], collection='my-blog')
print('{}: {}'.format(post2['title'], post2['body']))

assert post['id'] == post2['id']

# getting all posts that are draft (not published to a collection)
drafts = [post for post in c.get_posts() if not post['slug']]
print(drafts)

# updating a post
updated_post = c.update_post(post['id'],
示例#18
0
import writefreely as wf

c = wf.client(host='qua.name', user='******', password='******')

# saving token to avoid login each time:
with open('my_token.txt', 'w') as fd:
    fd.write(c.token)

# create an authenticated post
post = c.create_post(title='Cool Post', body='Awesome content!')
print('See your post at: {}/{}'.format(c.host, post['slug']))

# next time, load token from file:
with open('my_token.txt') as fd:
    c = wf.client(host='qua.name', token=fd.read())

print('User Name:', c.me()['username'])  # User Name: foo

c.logout()
# The access token isn't valid anymore

assert not c.is_authenticated()

# create an anonymous post (not allowed by all instances)
post = c.create_post(title='Anonymous Post', body='Guess who am I?')
print('See your post at: {}/{}'.format(c.host, post['slug']))

c.me()  # raises an error because that request can't be done unauthenticated
示例#19
0
import writefreely as wf

c = wf.client(token='XXXXXXX')

# creating a collection
c.create_collection(alias='my-blog', title='My Blog')

# getting one collection
blog = c.get_collection('my-blog')
print('Title: {}\nDescription: {}\nURL:{}'.format(
    blog['title'], blog['description'], blog['url']))

# getting all collections
for b in c.get_collections():
    print('{} has {} views and {} posts.'.format(
        b['title'], b['views'], b['total_posts']))

# updating a collection
c.update_collection(
    'my-blog',
    title='New title',
    visibility=1,  # make blog public
)

# deleting a collection
c.delete_collection('my-blog')