示例#1
0
def test_oauth_uid():
    responses.add(
        responses.POST,
        url="https://api.twitter.com/oauth/request_token",
        json={
            "oauth_token": "uid-token",
            "oauth_token_secret": "oauth token secret",
            "oauth_callback_confirmed": True,
        },
    )
    api = Api(
        consumer_key="consumer key", consumer_secret="consumer secret", oauth_flow=True
    )
    assert api.get_authorize_url()
    # do authorize
    resp_url = "https://localhost/?oauth_token=oauth_token&oauth_token_secret=oauth_token_secret&oauth_verifier=oauth_verifier"

    responses.add(
        responses.POST,
        url="https://api.twitter.com/oauth/access_token",
        json={
            "oauth_token": "uid-token",
            "oauth_token_secret": "oauth token secret",
        },
    )

    token = api.generate_access_token(response=resp_url)

    assert token["oauth_token"] == "uid-token"
    assert api.auth_user_id == "uid"
示例#2
0
def test_invalidate_access_token():
    # test revoke bearer token
    api_bearer = Api(bearer_token="token")
    with pytest.raises(PyTwitterError):
        api_bearer.invalidate_access_token()

    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="uid-token",
        access_secret="access secret",
    )
    responses.add(
        responses.POST,
        url="https://api.twitter.com/1.1/oauth/invalidate_token",
        json={"access_token": "ACCESS_TOKEN"},
    )

    resp = api.invalidate_access_token()
    assert resp["access_token"] == "ACCESS_TOKEN"

    # test no auth
    api._auth = None
    with pytest.raises(PyTwitterError):
        api.invalidate_access_token()
示例#3
0
def test_block_and_unblock_user(helpers):
    user_id, target_user_id = "123456", "78910"

    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="access token",
        access_secret="access secret",
    )

    responses.add(
        responses.POST,
        url=f"https://api.twitter.com/2/users/{user_id}/blocking",
        json={"data": {
            "blocking": True
        }},
    )

    resp = api.block_user(user_id=user_id, target_user_id=target_user_id)
    assert resp["data"]["blocking"]

    responses.add(
        responses.DELETE,
        url=
        f"https://api.twitter.com/2/users/{user_id}/blocking/{target_user_id}",
        json={"data": {
            "blocking": False
        }},
    )

    resp = api.unblock_user(user_id=user_id, target_user_id=target_user_id)
    assert not resp["data"]["blocking"]
示例#4
0
    def notify(self, message = '', data = {}, listener = None):
        if self.isDisabled(): return

        api = Api(self.consumer_key, self.consumer_secret, self.conf('access_token_key'), self.conf('access_token_secret'))

        direct_message = self.conf('direct_message')
        direct_message_users = self.conf('screen_name')
        
        mention = self.conf('mention')
        if mention:
            if direct_message:
                direct_message_users = '%s %s' % (direct_message_users, mention)
                direct_message_users = direct_message_users.replace('@',' ')
                direct_message_users = direct_message_users.replace(',',' ')
            else:
                message = '%s @%s' % (message, mention.lstrip('@'))

        try:
            if direct_message:
                for user in direct_message_users.split():
                    api.PostDirectMessage(user, '[%s] %s' % (self.default_title, message))
            else:
                api.PostUpdate('[%s] %s' % (self.default_title, message))
        except Exception, e:
            log.error('Error sending tweet: %s', e)
            return False
示例#5
0
    def notify(self, message='', data={}):
        if self.isDisabled(): return

        api = Api(self.consumer_key, self.consumer_secret,
                  self.conf('username'), self.conf('password'))

        try:
            api.PostUpdate('[%s] %s' % (self.default_title, message))
        except Exception, e:
            log.error('Error sending tweet: %s' % e)
            return False
示例#6
0
def test_oauth2_flow():
    api = Api(client_id="You client id", oauth_flow=True)

    url, _, code_verifier = api.get_oauth2_authorize_url()
    assert url

    # do authorize

    resp_url = "https://localhost/?state=state&code=code"

    responses.add(
        responses.POST,
        url="https://api.twitter.com/2/oauth2/token",
        json={
            "token_type": "bearer",
            "expires_in": 7200,
            "access_token": "access_token",
            "scope": "users.read tweet.read",
            "expires_at": 1631766428,
        },
    )

    token = api.generate_oauth2_access_token(
        response=resp_url, code_verifier=code_verifier
    )

    assert token["access_token"] == "access_token"

    with pytest.raises(PyTwitterError):
        api = Api(
            consumer_key="consumer key",
            consumer_secret="consumer secret",
            oauth_flow=True,
        )
        api.get_oauth2_authorize_url(resp_url)
示例#7
0
def api_with_user():
    return Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="uid-token",
        access_secret="access secret",
    )
示例#8
0
def test_unhide_reply():
    tweet_id = "123456"

    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="access token",
        access_secret="access secret",
    )

    responses.add(
        responses.PUT,
        url=f"https://api.twitter.com/2/tweets/{tweet_id}/hidden",
        json={"data": {
            "hidden": False
        }},
    )
    hide_resp = api.hidden_reply(tweet_id=tweet_id, hidden=False)
    assert hide_resp["data"]["hidden"] == False
示例#9
0
def test_unfollow_user():
    user_id, target_user_id = "123456", "78910"

    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="access token",
        access_secret="access secret",
    )

    responses.add(
        responses.DELETE,
        url=
        f"https://api.twitter.com/2/users/{user_id}/following/{target_user_id}",
        json={"data": {
            "following": False
        }},
    )

    resp = api.unfollow_user(user_id=user_id, target_user_id=target_user_id)

    assert not resp["data"]["following"]
示例#10
0
    def notify(self, message='', data=None, listener=None):
        if not data: data = {}

        api = Api(self.consumer_key, self.consumer_secret,
                  self.conf('access_token_key'),
                  self.conf('access_token_secret'))

        direct_message = self.conf('direct_message')
        direct_message_users = self.conf('screen_name')

        mention = self.conf('mention')
        mention_tag = None
        if mention:
            if direct_message:
                direct_message_users = '%s %s' % (direct_message_users,
                                                  mention)
                direct_message_users = direct_message_users.replace('@', ' ')
                direct_message_users = direct_message_users.replace(',', ' ')
            else:
                mention_tag = '@%s' % mention.lstrip('@')
                message = '%s %s' % (message, mention_tag)

        try:
            if direct_message:
                for user in direct_message_users.split():
                    api.PostDirectMessage('[%s] %s' %
                                          (self.default_title, message),
                                          screen_name=user)
            else:
                update_message = '[%s] %s' % (self.default_title, message)
                if len(update_message) > 140:
                    if mention_tag:
                        api.PostUpdate(update_message[:135 -
                                                      len(mention_tag)] +
                                       ('%s 1/2 ' % mention_tag))
                        api.PostUpdate(update_message[135 -
                                                      len(mention_tag):] +
                                       ('%s 2/2 ' % mention_tag))
                    else:
                        api.PostUpdate(update_message[:135] + ' 1/2')
                        api.PostUpdate(update_message[135:] + ' 2/2')
                else:
                    api.PostUpdate(update_message)
        except Exception as e:
            log.error('Error sending tweet: %s', e)
            return False

        return True
示例#11
0
def test_user_auth():
    with pytest.raises(PyTwitterError):
        Api()

    # initial api
    api = Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        access_token="uid-token",
        access_secret="access secret",
    )

    # test for replace auth
    api._auth = None
    with pytest.raises(PyTwitterError):
        api.get_user(user_id="123456")
示例#12
0
def test_generate_bearer_token(api, helpers):
    token_data = helpers.load_json_data("testdata/apis/authflow/bearer_token.json")

    responses.add(
        responses.POST, url="https://api.twitter.com/oauth2/token", json=token_data
    )

    # test initial by app
    Api(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
        application_only_auth=True,
    )

    # test generate by hand
    resp = api.generate_bearer_token(
        consumer_key="consumer key",
        consumer_secret="consumer secret",
    )
    assert (
        resp["access_token"]
        == "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    )
示例#13
0
def api():
    return Api(bearer_token="access token")
示例#14
0
"""
    A demo for like tweet.
"""

from pytwitter import Api

consumer_key = "your app consumer key"
consumer_secret = "your app consumer secret"

api = Api(
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    oauth_flow=True,
)

authorize_url = api.get_authorize_url()
print(f"Click authorize url to do authorize: {authorize_url}")

resp = input("Response here: ")

token = api.generate_access_token(response=resp)
print(f"Get token: {token}")
# Get token: {'oauth_token': 'token', 'oauth_token_secret': 'token_secret', 'user_id': 'user_id', 'screen_name': 'name'}

tweet_id = input("Tweet id you want to like:")

resp = api.like_tweet(
    user_id=api.auth_user_id,
    tweet_id=tweet_id,
)
print(f"Resp: {resp}")