Exemplo n.º 1
0
def authorize(args):
    if args.from_file:
        consumer_key, consumer_secret = __get_credentials_cache().values()[:2]
    else:
        consumer_key, consumer_secret = args.client
    if args.token:
        access_token, access_token_secret = args.token
    else:
        authorizer = TwitterAuthorizer(consumer_key, consumer_secret)
        print("Please access to this url: " + authorizer.get_authorization_url())
        pin = input("And input pin code: ")
        access_token, access_token_secret = authorizer.get_token(pin)
    session = TwitterSession(consumer_key,
                             consumer_secret,
                             access_token,
                             access_token_secret)
    user_obj = session.account_verify_credentials()
    user_id = user_obj["id_str"]
    screen_name = user_obj["screen_name"]
    credentials = __get_credentials_cache(get_all=True, ignore=True)
    if credentials is not None:
        user_id_lst = [x["user_id"] for x in credentials]
    if credentials is None or user_id not in user_id_lst:
        __write_credentials_cache(consumer_key,
                                  consumer_secret,
                                  access_token,
                                  access_token_secret,
                                  user_id,
                                  screen_name)
    else:
        index = user_id_lst.index(user_id)
        credentials[index]["consumer_key"]        = consumer_key
        credentials[index]["consumer_secret"]     = consumer_secret
        credentials[index]["access_token"]        = access_token
        credentials[index]["access_token_secret"] = access_token_secret
        credentials[index]["screen_name"]         = screen_name
        __overwrite_credentials_cache(credentials)
    print("Authorization successful!")
Exemplo n.º 2
0
def shell_message(args):
    credentials = __get_credentials_cache(screen_name=args.account_name)
    session = TwitterSession(credentials["consumer_key"],
                             credentials["consumer_secret"],
                             credentials["access_token"],
                             credentials["access_token_secret"])
    if bool(args.file_path):
        for p in args.file_path:
            with open(p, "br") as f:
                file_data = b"".join(x for x in f)
            encoded_data = mybase64.byte_encode(file_data)
            session.direct_message_new(p + " encoded base64", args.screen_name, args.user_id)
            print(len(encoded_data))
            for split_data in [encoded_data[i: i+10000] for i in range(0, len(encoded_data), 10000)]:
                session.direct_message_new(split_data, args.screen_name, args.user_id)
    session.direct_message_new(args.text, args.screen_name, args.user_id)
    print("Message successful!")
Exemplo n.º 3
0
def shell_tweet(args):
    credentials = __get_credentials_cache(screen_name=args.account_name)
    session = TwitterSession(credentials["consumer_key"],
                             credentials["consumer_secret"],
                             credentials["access_token"],
                             credentials["access_token_secret"])
    if bool(args.screen_name):
        args.text = " ".join("@" + x for x in args.screen_name) + " " + args.text
    if bool(args.file_path):
        if len(args.file_path) > 4:
            print("Media upload limit is 4 by once!", file=sys.stderr)
            sys.exit(1)
        media_ids = [session.media_upload(x) for x in args.file_path]
        session.status_update(args.text, media_ids)
    else:
        session.status_update(args.text)
    print("Tweet successful!")
Exemplo n.º 4
0
*   Creates a Markdown file that summarises the text of the thread

"""

import datetime as dt
import json
import os
import sys
from urllib.parse import urlparse

from twitter_oauth import TwitterSession, save_tweet

BACKUP_ROOT = ".twitter"

if __name__ == '__main__':
    sess = TwitterSession(backup_root=BACKUP_ROOT)

    try:
        url = sys.argv[1]
    except IndexError:
        sys.exit(f"Usage: {__file__} <URL>")

    parts = urlparse(url)
    assert parts.netloc == "twitter.com"

    _, username, status, tweet_id, *_ = parts.path.split("/")
    assert status == "status"

    thread = []
    while True:
        print(f"Saving {tweet_id}")
Exemplo n.º 5
0
HTML dumps, which are expected to be more "pure".

"""

import json
import os

import bs4
import requests

import sys
sys.path.append("..")

from twitter_oauth import TwitterSession, DEFAULT_BACKUP_ROOT

sess = TwitterSession()

users_by_id = {}

for f in os.listdir("backlog"):
    if f.startswith((".", "_")):
        continue

    # I'd like to come back and do these eventually, but I want an example of
    # what a real group DM conversation API response looks like first.
    if f.startswith("group_"):
        continue

    print(f)

    path = os.path.join("backlog", f)
Exemplo n.º 6
0
#!/usr/bin/env python
# -*- encoding: utf-8

import sys

from backup_dms import save_individual_dm
from twitter_oauth import TwitterSession

if __name__ == '__main__':
    try:
        direct_message_id = sys.argv[1]
    except IndexError:
        sys.exit(f"Usage: {__file__} <DM_ID>")

    sess = TwitterSession()
    event = sess.show_dm_event(event_id=direct_message_id)

    save_individual_dm(event=event, sess=sess)
Exemplo n.º 7
0
#!/usr/bin/env python
# -*- encoding: utf-8

from twitter_oauth import TwitterSession, save_user_info


if __name__ == "__main__":
    sess = TwitterSession()

    followers = sess.list_followers()
    save_user_info(followers, dirname="followers")
Exemplo n.º 8
0
    recipient_id = event["message_create"]["target"]["recipient_id"]
    user_ids = [sender_id, recipient_id]

    users = sess.lookup_users(user_ids)

    # Discard me!
    conversation_id = "__".join(
        sorted(u["screen_name"] for u in users.values()
               if u["screen_name"] != "alexwlchan"))

    out_dir = os.path.join(DEFAULT_BACKUP_ROOT, "direct_messages",
                           conversation_id)
    os.makedirs(out_dir, exist_ok=True)

    dm_id = event["id"]

    out_path = os.path.join(out_dir, f"{dm_id}.json")
    if os.path.exists(out_path):
        print(".", end="")
    else:
        print(dm_id)
        with open(out_path, "w") as outfile:
            outfile.write(json.dumps(event, indent=2, sort_keys=True))


if __name__ == '__main__':
    sess = TwitterSession()

    for event in sess.list_dm_events():
        save_individual_dm(event=event, sess=sess)
Exemplo n.º 9
0
def save_single_tweet_by_id(tweet_id, dirname):
    print(f"Saving {tweet_id} to {dirname}")
    sess = TwitterSession()
    tweet = sess.lookup_status(tweet_id)
    save_tweet(tweet, dirname=dirname)
Exemplo n.º 10
0
#!/usr/bin/env python
# -*- encoding: utf-8

from twitter_oauth import TwitterSession, save_tweet


if __name__ == '__main__':
    sess = TwitterSession()

    for tweet in sess.user_timeline():
        save_tweet(tweet, dirname="user_timeline")
Exemplo n.º 11
0
#!/usr/bin/env python
# -*- encoding: utf-8

from twitter_oauth import TwitterSession, save_user_info


if __name__ == "__main__":
    sess = TwitterSession()

    friends = sess.list_friends()
    save_user_info(friends, dirname="friends")
Exemplo n.º 12
0
#!/usr/bin/env python
# -*- encoding: utf-8

from twitter_oauth import TwitterSession, save_tweet

if __name__ == '__main__':
    sess = TwitterSession()

    for tweet in sess.mentions_timeline():
        save_tweet(tweet, dirname="mentions")
Exemplo n.º 13
0
#!/usr/bin/env python
# -*- encoding: utf-8

from twitter_oauth import TwitterSession, save_tweet

if __name__ == '__main__':
    sess = TwitterSession()

    for tweet in sess.list_favorites():
        save_tweet(tweet, dirname="favorites")