Beispiel #1
0
class Test1AccessTokenSecret(unittest.TestCase):
    def setUp(self):
        try:
            file = open('API.keys', 'r+')
        except IOError:
            print("You need to put key/secret in API.keys")
            raise
        except:
            print("Unexpected error:", sys.exc_info()[0])
        else:
            data = json.load(file)
            file.close()
            self.plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])

    def teardown(self):
        pass

    def test_invalid_access_key(self):
        self.plurk.authorize("foor", "bar")
        r = self.plurk.callAPI('/APP/Profile/getOwnProfile')
        self.assertIsNone(r)
        err = self.plurk.error()
        self.assertEqual(err['code'], "400")
        self.assertEqual(err['reason'], "BAD REQUEST")
        self.assertEqual(err['content']['error_text'],
                         "40106:invalid access token")
Beispiel #2
0
    def __init__(
        self,
        app_key: Optional[str] = None,
        app_secret: Optional[str] = None,
        access_token: Optional[str] = None,
        access_secret: Optional[str] = None,
        stats: Optional[PlurkerStats] = None,
    ) -> None:
        """
        Will try to fetch `PLURK_APP_KEY`, `PLURK_APP_SECRET`,
        `PLURK_USER_TOKEN`, `PLURK_USER_SECRET` from environment variables
        if `app_key`, `app_secret`, `access_token`, `access_secret` weren't provided.

        """
        APP_KEY = os.getenv('PLURK_APP_KEY', app_key)
        APP_SECRET = os.getenv('PLURK_APP_SECRET', app_secret)
        ACCESS_TOKEN = os.getenv('PLURK_USER_TOKEN', access_token)
        ACCESS_TOKEN_SECRET = os.getenv('PLURK_USER_SECRET', access_secret)

        self.plurk = PlurkAPI(key=APP_KEY,
                              secret=APP_SECRET,
                              access_token=ACCESS_TOKEN,
                              access_secret=ACCESS_TOKEN_SECRET)
        self._stats = stats or PlurkerStats()
        super().__init__()
Beispiel #3
0
 def __init__(self, my_account):
     self.my_account = my_account
     self.friend_list_now = []
     self.my_info_json = {}
     # replace them with your consumer key and secret
     CONSUMER_KEY = YOUR_CONSUMER_KEY
     CONSUMER_SECRET = YOUR_CONSUMER_SECRET
     self.plurk = PlurkAPI(CONSUMER_KEY, CONSUMER_SECRET)
Beispiel #4
0
 def __init__(self):
     self.startTime = datetime.now(gmt8)
     self.p = PlurkAPI()
     self.p.authorize()
     if self.p.is_authorized():
         print('%s, authorization completed' % now_str())
     else:
         raise RuntimeError('authorize fail')
 def __init__(self, file_name, my_account):
     self.file_name = file_name
     self.my_account = my_account
     self.deleted_friend = []
     self.friend_list_now = []
     # replace them with your consumer key and secret
     CONSUMER_KEY = YOUR_CONSUMER_KEY
     CONSUMER_SECRET = YOUR_CONSUMER_SECRET
     self.plurk = PlurkAPI(CONSUMER_KEY, CONSUMER_SECRET)
Beispiel #6
0
 def test_invalid_consumer_key(self):
     self.plurk = PlurkAPI("token", "secret")
     r = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                            {'user_id': 'clsung'})
     self.assertIsNone(r)
     err = self.plurk.error()
     self.assertEqual(err['code'], 400)
     self.assertEqual(err['reason'], "BAD REQUEST")
     self.assertEqual(err['content']['error_text'],
                      "40101:unknown application key")
Beispiel #7
0
 def test_invalid_access_key(self):
     self.plurk = PlurkAPI("key", "secret")
     self.plurk.authorize("foor", "bar")
     r = self.plurk.callAPI('/APP/Profile/getOwnProfile')
     self.assertIsNone(r)
     err = self.plurk.error()
     self.assertEqual(err['code'], 400)
     self.assertEqual(err['reason'], "BAD REQUEST")
     self.assertEqual(err['content']['error_text'],
                      "40106:invalid access token")
Beispiel #8
0
class Plurker(Publisher):
    def __init__(
        self,
        app_key: Optional[str] = None,
        app_secret: Optional[str] = None,
        access_token: Optional[str] = None,
        access_secret: Optional[str] = None,
        stats: Optional[PlurkerStats] = None,
    ) -> None:
        """
        Will try to fetch `PLURK_APP_KEY`, `PLURK_APP_SECRET`,
        `PLURK_USER_TOKEN`, `PLURK_USER_SECRET` from environment variables
        if `app_key`, `app_secret`, `access_token`, `access_secret` weren't provided.

        """
        APP_KEY = os.getenv('PLURK_APP_KEY', app_key)
        APP_SECRET = os.getenv('PLURK_APP_SECRET', app_secret)
        ACCESS_TOKEN = os.getenv('PLURK_USER_TOKEN', access_token)
        ACCESS_TOKEN_SECRET = os.getenv('PLURK_USER_SECRET', access_secret)

        self.plurk = PlurkAPI(key=APP_KEY,
                              secret=APP_SECRET,
                              access_token=ACCESS_TOKEN,
                              access_secret=ACCESS_TOKEN_SECRET)
        self._stats = stats or PlurkerStats()
        super().__init__()

    @property
    def stats(self):
        return self._stats

    def publish(self, *, content):
        """
        :raise PublishError: raise error when publish failed.
        """
        self.stats.start()
        response = self._publish(content)
        self.stats.finish()
        return response

    def _publish(self, content):
        response = self.plurk.callAPI("/APP/Timeline/plurkAdd",
                                      options=content)
        if response:
            self.stats.sending_success()
            return response
        else:
            self.stats.sending_failed()
            error = self.plurk.error()
            msg = error['reason']

            if 'error_text' in error['content']:
                msg = error['content']['error_text']

            raise PublishError(publisher=self, reason=msg, caused_by=content)
Beispiel #9
0
class TestAPIAuth(unittest.TestCase):
    '''
    Unit test for PlurkAPI auth part
    '''
    def setUp(self):
        self.mox = mox.Mox()
        self.api = PlurkAPI('CONSUMER_KEY', 'CONSUMER_SECRET')
        self.oauth_response = \
            'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR&oauth_callback_confirmed=true'  # NOQA
        self.verify_response = \
            'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR'
        self.golden_token = {
            'key': 'ReqXBFOswcyR',
            'secret': 'O7WqqqWHA61f4ZE5izQdTQmK',
        }
        self.golden_url = 'https://www.plurk.com/OAuth/authorize?oauth_token=ReqXBFOswcyR'
        self.mox.StubOutWithMock(PlurkOAuth, 'request')

    def tearDown(self):
        self.mox.UnsetStubs()

    def _200_request(self):
        return 200, self.oauth_response, ""

    def _200_verify(self):
        return 200, self.verify_response, ''

    def test_set_request_token(self):
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        token = self.api.get_request_token()
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()

    def test_get_request_token(self):
        self.api._oauth.request(mox.IgnoreArg()).AndReturn(self._200_request())
        self.mox.ReplayAll()
        token = self.api.get_request_token()
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()

    def test_get_verifier_url(self):
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        url = self.api.get_verifier_url()
        self.assertEqual(self.golden_url, url)
        self.mox.VerifyAll()

    def test_get_access_token(self):
        self.api._oauth.request(mox.IgnoreArg(),
                                mox.IgnoreArg()).AndReturn(self._200_verify())
        self.mox.ReplayAll()
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        token = self.api.get_access_token('VERIFIER')
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()
Beispiel #10
0
class TestAPIAuth(unittest.TestCase):
    '''
    Unit test for PlurkAPI auth part
    '''
    def setUp(self):
        self.mox = mox.Mox()
        self.api = PlurkAPI('CONSUMER_KEY', 'CONSUMER_SECRET')
        self.oauth_response = \
            'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR&oauth_callback_confirmed=true'  # NOQA
        self.verify_response = \
            'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR'
        self.golden_token = {
            'key': 'ReqXBFOswcyR',
            'secret': 'O7WqqqWHA61f4ZE5izQdTQmK',
        }
        self.golden_url = 'https://www.plurk.com/OAuth/authorize?oauth_token=ReqXBFOswcyR'
        self.mox.StubOutWithMock(PlurkOAuth, 'request')

    def tearDown(self):
        self.mox.UnsetStubs()

    def _200_request(self):
        return 200, self.oauth_response, ""

    def _200_verify(self):
        return 200, self.verify_response, ''

    def test_set_request_token(self):
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        token = self.api.get_request_token()
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()

    def test_get_request_token(self):
        self.api._oauth.request(mox.IgnoreArg()).AndReturn(self._200_request())
        self.mox.ReplayAll()
        token = self.api.get_request_token()
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()

    def test_get_verifier_url(self):
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        url = self.api.get_verifier_url()
        self.assertEqual(self.golden_url, url)
        self.mox.VerifyAll()

    def test_get_access_token(self):
        self.api._oauth.request(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(self._200_verify())
        self.mox.ReplayAll()
        self.api.set_request_token('ReqXBFOswcyR', 'O7WqqqWHA61f4ZE5izQdTQmK')
        token = self.api.get_access_token('VERIFIER')
        self.assertEqual(self.golden_token, token)
        self.mox.VerifyAll()
Beispiel #11
0
 def setUp(self):
     try:
         file = open('API.keys', 'r+')
     except IOError:
         print("You need to put key/secret in API.keys")
         raise
     except:
         print("Unexpected error:", sys.exc_info()[0])
     else:
         data = json.load(file)
         file.close()
         self.plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])
Beispiel #12
0
 def setUp(self):
     self.mox = mox.Mox()
     self.api = PlurkAPI('CONSUMER_KEY', 'CONSUMER_SECRET')
     self.oauth_response = \
         'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR&oauth_callback_confirmed=true'  # NOQA
     self.verify_response = \
         'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR'
     self.golden_token = {
         'key': 'ReqXBFOswcyR',
         'secret': 'O7WqqqWHA61f4ZE5izQdTQmK',
     }
     self.golden_url = 'https://www.plurk.com/OAuth/authorize?oauth_token=ReqXBFOswcyR'
     self.mox.StubOutWithMock(PlurkOAuth, 'request')
Beispiel #13
0
 def __init__(self,
             CONSUMER_SECRET,
             CONSUMER_KEY,
             ACCESS_TOKEN,
             ACCESS_TOKEN_SECRET):
     self.plurk=PlurkAPI(key=CONSUMER_KEY, secret=CONSUMER_SECRET,
                      access_token=ACCESS_TOKEN, access_secret=ACCESS_TOKEN_SECRET)
Beispiel #14
0
class TestTwoLeggedAPI(unittest.TestCase):
    def setUp(self):
        try:
            file = open('API.keys', 'r+')
        except IOError:
            print("You need to put key/secret in API.keys")
            raise
        except:
            print("Unexpected error:", sys.exc_info()[0])
        else:
            data = json.load(file)
            file.close()
            self.plurk = PlurkAPI(data["CONSUMER_KEY"],
                                  data["CONSUMER_SECRET"])

    def teardown(self):
        pass

    def test_get_public_profile(self):
        jdata = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                                   {'user_id': 'clsung'})
        self.assertIsInstance(jdata, dict, "Object should be a dict")
        self.assertGreater(jdata['user_info']['uid'], 0, "Self Uid > 0")
        self.assertEqual(jdata['user_info']['nick_name'], "clsung",
                         "Author's Name ;)")
Beispiel #15
0
class make_friend_file:
    def __init__(self, my_account):
        self.my_account = my_account
        self.friend_list_now = []
        self.my_info_json = {}
        # replace them with your consumer key and secret
        CONSUMER_KEY = YOUR_CONSUMER_KEY
        CONSUMER_SECRET = YOUR_CONSUMER_SECRET
        self.plurk = PlurkAPI(CONSUMER_KEY, CONSUMER_SECRET)

    def get_friend(self):
        self.my_info_json = self.plurk.callAPI(
            '/APP/Profile/getPublicProfile',
            options={'user_id': self.my_account})
        if self.my_info_json:
            friends_count = self.my_info_json['friends_count']
            # uid instead of id, quite strange :p
            self.my_id = self.my_info_json['user_info']['uid']
            # getFriendsByOffset can only get 100 friends every time
            for offset in range(0, friends_count + 100, 100):
                my_friend = self.plurk.callAPI(
                    '/APP/FriendsFans/getFriendsByOffset',
                    options={
                        'user_id': self.my_id,
                        'offset': offset,
                        'limit': 100
                    })
                for friend_json in my_friend:
                    self.friend_list_now.append(str(friend_json['id']))
                    self.friend_list_now.append(friend_json['nick_name'])
                    self.friend_list_now.append(friend_json['display_name'])
            threelines = range(0, len(self.friend_list_now), 3)
            friend_list_str = ""
            for i, s in enumerate(self.friend_list_now):
                if i in threelines:
                    if friend_list_str:
                        friend_list_str += '\n'
                    # every line has format: ID NICK_NAME DISPLAY_NAME
                    friend_list_str += " ".join(self.friend_list_now[i:i + 3])
            today = datetime.today()
            FILE = open(str(self.my_account) + '_friend_list_' +
                        str(today.year) + '_' + str(today.month) + '_' +
                        str(today.day) + '.txt',
                        'w+',
                        encoding='utf-8')
            FILE.write(friend_list_str)
Beispiel #16
0
class Test1AccessTokenSecret(unittest.TestCase):
    def setUp(self):
        pass

    def teardown(self):
        pass

    def test_invalid_access_key(self):
        self.plurk = PlurkAPI("key", "secret")
        self.plurk.authorize("foor", "bar")
        r = self.plurk.callAPI('/APP/Profile/getOwnProfile')
        self.assertIsNone(r)
        err = self.plurk.error()
        self.assertEqual(err['code'], 400)
        self.assertEqual(err['reason'], "BAD REQUEST")
        self.assertEqual(err['content']['error_text'],
                         "40106:invalid access token")
Beispiel #17
0
 def test_invalid_consumer_key(self):
     self.plurk = PlurkAPI("token", "secret")
     r = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                            {'user_id': 'clsung'})
     self.assertIsNone(r)
     err = self.plurk.error()
     self.assertEqual(err['code'], 400)
     self.assertEqual(err['reason'], "BAD REQUEST")
     self.assertEqual(err['content']['error_text'],
                      "40101:unknown application key")
Beispiel #18
0
 def __init__(self, app):
     super(ContentPoster, self).__init__(name='poster')
     self.app = app
     self.daemon = True
     self.queue = Queue()
     self.plurk = PlurkAPI.fromfile('plurk.json')
     self.cache = []
     try:
         with open('cache.txt', 'r') as f:
             self.cache = [line.strip() for line in f]
     except FileNotFoundError:
         logging.warning('No cache file present')
Beispiel #19
0
 def setUp(self):
     self.mox = mox.Mox()
     self.api = PlurkAPI('CONSUMER_KEY', 'CONSUMER_SECRET')
     self.oauth_response = \
         'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR&oauth_callback_confirmed=true'  # NOQA
     self.verify_response = \
         'oauth_token_secret=O7WqqqWHA61f4ZE5izQdTQmK&oauth_token=ReqXBFOswcyR'
     self.golden_token = {
         'key': 'ReqXBFOswcyR',
         'secret': 'O7WqqqWHA61f4ZE5izQdTQmK',
     }
     self.golden_url = 'https://www.plurk.com/OAuth/authorize?oauth_token=ReqXBFOswcyR'
     self.mox.StubOutWithMock(PlurkOAuth, 'request')
Beispiel #20
0
class Test0ConsumerTokenSecret(unittest.TestCase):
    def setUp(self):
        pass

    def teardown(self):
        pass

    def test_no_consumer_key(self):
        with self.assertRaises(ValueError):
            self.plurk = PlurkAPI()
            self.plurk.callAPI('/APP/Profile/getPublicProfile',
                               {'user_id': 'clsung'})

    def test_invalid_consumer_key(self):
        self.plurk = PlurkAPI("token", "secret")
        r = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                               {'user_id': 'clsung'})
        self.assertIsNone(r)
        err = self.plurk.error()
        self.assertEqual(err['code'], 400)
        self.assertEqual(err['reason'], "BAD REQUEST")
        self.assertEqual(err['content']['error_text'],
                         "40101:unknown application key")
Beispiel #21
0
class Test0ConsumerTokenSecret(unittest.TestCase):
    def setUp(self):
        pass

    def teardown(self):
        pass

    def test_no_consumer_key(self):
        with self.assertRaises(ValueError):
            self.plurk = PlurkAPI()
            self.plurk.callAPI('/APP/Profile/getPublicProfile',
                               {'user_id': 'clsung'})

    def test_invalid_consumer_key(self):
        self.plurk = PlurkAPI("token", "secret")
        r = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                               {'user_id': 'clsung'})
        self.assertIsNone(r)
        err = self.plurk.error()
        self.assertEqual(err['code'], 400)
        self.assertEqual(err['reason'], "BAD REQUEST")
        self.assertEqual(err['content']['error_text'],
                         "40101:unknown application key")
Beispiel #22
0
class TestTwoLeggedAPI(unittest.TestCase):
    def setUp(self):
        try:
            file = open('API.keys', 'r+')
        except IOError:
            print("You need to put key/secret in API.keys")
            raise
        except:
            print("Unexpected error:", sys.exc_info()[0])
        else:
            data = json.load(file)
            file.close()
            self.plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])

    def teardown(self):
        pass

    def test_get_public_profile(self):
        jdata = self.plurk.callAPI('/APP/Profile/getPublicProfile',
                                   {'user_id': 'clsung'})
        self.assertIsInstance(jdata, dict, "Object should be a dict")
        self.assertGreater(jdata['user_info']['uid'], 0, "Self Uid > 0")
        self.assertEqual(jdata['user_info']['nick_name'],
                         "clsung", "Author's Name ;)")
Beispiel #23
0
def hello(event, context):
    load_dotenv()
    plurkAPI = PlurkAPI(os.environ['PLURK_APP_KEY'],
                        os.environ['PLURK_SECRET'])
    plurkAPI.authorize(os.environ['PLURK_ACCESS_TOKEN'],
                       os.environ['PLRUK_ACCESS_SECRET'])

    query = os.environ['QUERY']
    max_size = int(os.environ['MAX_SIZE'])
    offset = 0
    while offset < max_size:
        results = plurkAPI.callAPI('/APP/PlurkSearch/search',
                                   options={
                                       'query': query,
                                       'offset': offset
                                   })
        filtered = list(filter(sould_replurk, results['plurks']))
        if not filtered:
            break
        plurk_ids = list(map(lambda x: x['plurk_id'], filtered))
        #print(plurk_ids)
        plurkAPI.callAPI('/APP/Timeline/replurk',
                         options={'ids': json.dumps(plurk_ids)})
        offset += results['last_offset']
Beispiel #24
0
#!/usr/bin/python
# -*- coding:utf-8 -*-

import re
import json
import urllib2
import telepot
import time
import pprint
from plurk_oauth import PlurkAPI
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('apitoken.txt')
plurk = PlurkAPI(parser.get('plurk', 'appkey'),
                 parser.get('plurk', 'appsecret'))
plurk.authorize(parser.get('plurk', 'usertoken'),
                parser.get('plurk', 'usersecret'))
try:
    comet = plurk.callAPI('/APP/Realtime/getUserChannel')
except:
    while True:
        comet = plurk.callAPI('/APP/Realtime/getUserChannel')
        if 'channel_name' in comet:
            break
comet_channel = comet.get('comet_server') + "&amp;new_offset=%d"
jsonp_re = re.compile('CometChannel.scriptCallback\((.+)\);\s*')
new_offset = -50


def handle(msg):
    #debug用
Beispiel #25
0

def usage():
    print('''Help Information:
    -h: Show help information
    ''')


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        print(str(err))  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    with open('API.keys', 'r+') as f:
        data = json.load(f)
        plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])
        if data.get('ACCESS_TOKEN'):
            plurk.authorize(data["ACCESS_TOKEN"], data["ACCESS_TOKEN_SECRET"])
        else:
            plurk.authorize()
            data["ACCESS_TOKEN"] = plurk._oauth.oauth_token['oauth_token']
            data["ACCESS_TOKEN_SECRET"] = plurk._oauth.oauth_token[
                'oauth_token_secret']
            f.seek(0)
            json.dump(data, f)

    print(plurk.callAPI('/APP/Profile/getOwnProfile'))
Beispiel #26
0
 def setUp(self):
     self.plurk = PlurkAPI.fromfile('API.keys')
     if not self.plurk.is_authorized():
         raise KeyError(
             "You need to put cunsomer/access key/secret in API.keys")
Beispiel #27
0
import json


def usage():
    print('''Help Information:
    -h: Show help information
    ''')


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        print(str(err))  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    with open('API.keys', 'r+') as f:
        data = json.load(f)
        plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])
        if data.get('ACCESS_TOKEN'):
            plurk.authorize(data["ACCESS_TOKEN"], data["ACCESS_TOKEN_SECRET"])
        else:
            plurk.authorize()
            data["ACCESS_TOKEN"] = plurk._oauth.oauth_token['oauth_token']
            data["ACCESS_TOKEN_SECRET"] = plurk._oauth.oauth_token['oauth_token_secret']
            f.seek(0)
            json.dump(data, f)

    print(plurk.callAPI('/APP/Profile/getOwnProfile'))
Beispiel #28
0
 def test_no_consumer_key(self):
     with self.assertRaises(ValueError):
         self.plurk = PlurkAPI()
         self.plurk.callAPI('/APP/Profile/getPublicProfile',
                            {'user_id': 'clsung'})
Beispiel #29
0
from plurk_oauth import PlurkAPI
import json
import requests

plurk = PlurkAPI.fromfile("API.keys")
channelAddr = plurk.callAPI("/APP/Realtime/GetUserChannel").get("comet_server")[:-len("&offset=0")]
offset = 0

while True:
    callback = json.loads(requests.get(channelAddr+"&offset="+str(offset))
                          .text[len("CometChannel.scriptCallback("):-len(");")])
    newOffset = callback.get("new_offset")
    if newOffset != -1:
        tds = callback.get("data")
        for td in tds:
            print(json.dumps(td, indent=4, sort_keys=True, ensure_ascii=False))
            # TODO: stuff td in to a queue

        offset = newOffset

# example of calling plurk API
# response = plurk.callAPI('/APP/Responses/get', options={'plurk_id': 1419178662})

# comet server call back data model:
# {
#    "data": [
#       {<json>},
#       {<json>}....
#    ],
#    "new_offset": 16
# }
Beispiel #30
0
 def setUp(self):
     self.plurk = PlurkAPI.fromfile('API.keys')
     if not self.plurk.is_authorized():
         raise KeyError("You need to put cunsomer/access key/secret in API.keys")
Beispiel #31
0
#!/usr/bin/env python
from datetime import datetime, timedelta
from dateutil.parser import parse as parse_date
from dateutil.tz import tzutc, tzlocal
from plurk_oauth import PlurkAPI

class Plurk(object):
    def __init__(self, plurk_id, posted, content_raw, **kwargs):
        self.plurk_id = plurk_id
        self.posted = parse_date(posted)
        self.content_raw = content_raw
    def __hash__(self):
        return self.plurk_id

plurk = PlurkAPI.fromfile('plurk.json')
start = datetime.now(tzlocal())
end = start - timedelta(hours=24)

plurks = []
while start > end:
    print('Fetching', start)
    resp = plurk.callAPI('/APP/Timeline/getPlurks', {
        'filter': 'my',
        'limit': 30,
        'offset': start.astimezone(tzutc()).isoformat() })
    plurks.extend(Plurk(**p) for p in resp['plurks'])
    start = min(plurks, key=lambda x: x.posted).posted

titles = set()
unique_plurks = sorted(set(plurks), key=lambda x: x.posted)
print('Unique plurks', len(unique_plurks))
class Compare_list:
    def __init__(self, file_name, my_account):
        self.file_name = file_name
        self.my_account = my_account
        self.deleted_friend = []
        self.friend_list_now = []
        # replace them with your consumer key and secret
        CONSUMER_KEY = YOUR_CONSUMER_KEY
        CONSUMER_SECRET = YOUR_CONSUMER_SECRET
        self.plurk = PlurkAPI(CONSUMER_KEY, CONSUMER_SECRET)

    def open_file(self):
        FILE = open(self.file_name, 'r', encoding='utf-8')
        friend_list_str = FILE.read()
        temp = friend_list_str.split('\n')
        self.friend_list = []
        for s in temp:
            # separate to ID NICK_NAME DISPLAY_NAME. Do this in case that there is a space in DISPLAY_NAME
            s = s.split(' ', 2)
            self.friend_list.extend(s)

    def get_friend_now(self):
        self.open_file()
        self.my_info_json = self.plurk.callAPI(
            '/APP/Profile/getPublicProfile',
            options={'user_id': self.my_account})
        if self.my_info_json:
            friends_count = self.my_info_json['friends_count']
            my_id = self.my_info_json['user_info']['uid']
            # getFriendsByOffset can only get 100 friends every time
            for offset in range(0, friends_count + 100, 100):
                my_friend = self.plurk.callAPI(
                    '/APP/FriendsFans/getFriendsByOffset',
                    options={
                        'user_id': my_id,
                        'offset': offset,
                        'limit': 100
                    })
                for friend_json in my_friend:
                    self.friend_list_now.append(str(friend_json['id']))

    def compare_friend(self):
        self.get_friend_now()
        if self.my_info_json:
            i = 0
            while True:
                # a deleted friend. get its NICK_NAME and DISPLAY_NAME
                if self.friend_list[i] not in self.friend_list_now:
                    self.deleted_friend.append(self.friend_list[i + 1])
                    self.deleted_friend.append(self.friend_list[i + 2])
                i += 3
                if i >= len(self.friend_list):
                    break
            if self.deleted_friend:
                i = 0
                while True:
                    # join NICK_NAME and DISPLAY_NAME and separate them with '(', and then append a ')' to the end
                    # NICK_NAME(DISPLAY_NAME)
                    self.deleted_friend[i:i + 2] = [
                        '('.join(self.deleted_friend[i:i + 2])
                    ]
                    self.deleted_friend[i] += ')'
                    i += 1
                    if i >= len(self.deleted_friend):
                        break
            return True
        else:
            return False
Beispiel #33
0
    # --OAuth Utilities
    def checkToken():
        pass
    def expireToken():
        pass
    def checkTime():
        pass
    def echo():
        pass

# Check plurk key
CONSUMER_SECRET = os.environ['CONSUMER_SECRET']
CONSUMER_KEY = os.environ['CONSUMER_KEY']
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']
plurk = PlurkAPI(key=CONSUMER_KEY, secret=CONSUMER_SECRET,
                 access_token=ACCESS_TOKEN, access_secret=ACCESS_TOKEN_SECRET)

# --Users
def getMe(*arg,**kwarg):
    return plurk.callAPI('/APP/Users/me')

def getKarma(*arg,**kwarg):
    return plurk.callAPI('/APP/Users/getKarmaStats')

# --Polling
def getPlurks(offset,limit=None,favorers_detail=None,limited_detail=None,
                replurkers_detail=None,*arg,**kwarg):
    options={'offset':util.dt2pt(offset)}
    if limit:options['limit']=limit
    if favorers_detail:options['favorers_detail']=favorers_detail
    if limited_detail:options['limited_detail']=limited_detail
Beispiel #34
0
 def test_no_consumer_key(self):
     with self.assertRaises(ValueError):
         self.plurk = PlurkAPI()
         self.plurk.callAPI('/APP/Profile/getPublicProfile',
                            {'user_id': 'clsung'})
Beispiel #35
0
class PlurkBot:
    def __init__(self):
        self.startTime = datetime.now(gmt8)
        self.p = PlurkAPI()
        self.p.authorize()
        if self.p.is_authorized():
            print('%s, authorization completed' % now_str())
        else:
            raise RuntimeError('authorize fail')

    def getActive(self):
        return self.p.callAPI('/APP/Alerts/getActive')

    def addAsFriend(self, uid):
        return self.p.callAPI('/APP/Alerts/addAsFriend', {'user_id': uid})

    def poll_getPlurks(self, options):
        return self.p.callAPI('/APP/Polling/getPlurks', options)

    def responseAdd(self, plurkId, content, qualifier=':'):
        options = {
            'plurk_id': plurkId,
            'content': content,
            'qualifier': qualifier
        }
        return self.p.callAPI('/APP/Responses/responseAdd', options)

    def check_notify_and_add_friend(self, logFile):
        t_str = now_str()
        alerts = self.getActive()
        logFile.log('%s, getActive, getAlert=%d' % (t_str, len(alerts)))
        for alert in alerts:
            print('notify type: %s' % alert['type'])
            if alert['type'] == 'friendship_request':
                uid = alert['from_user']['id']
                logFile.log('%s, addAsFriend, uid=%d' % (t_str, uid))
                self.addAsFriend(uid)

    def fetch_newer_plurks(
            self, offset, logFile,
            plurkFile):  # start from offset to now, return plurks
        t_str = now_str()
        options = {
            'offset': offset,
            'limit': '20',
            'minimal_data': 'true',
            'minimal_user': '******'
        }
        data = self.poll_getPlurks(
            options)  # offset = datetime.isoformat(timespec='seconds')
        ls = []
        for pk in data['plurks']:
            plurkFile.log('%s, %s, uid=%d, pkid=%d, %r' %
                          (t_str, gmt2offset(pk['posted']), pk['user_id'],
                           pk['plurk_id'], pk['content_raw']))
            ls.append(pk['plurk_id'])
        logFile.log('%s, Poll/getPlurks, %s, plurk=%d, pks=%s' %
                    (t_str, offset, len(data['plurks']), ls))
        return data['plurks']

    # def fetch_period_plurks(self,dt1,dt2): # start from dt1 to dt2, return plurks
    #     loader = []
    #     dt = dt1
    #     while dt < dt2:
    #         pks = self.fetch_newer_plurks(dt2offset(dt),logFile,plurkFile)
    #         print('from %s, get %d plurk' % (dt2offset(dt), len(pks)))
    #         dt = get_plurk_post_time(pks[-1:]) # update last time
    #         print('last time in plurk: %s' % dt2offset(dt))
    #         if dt < dt2: # add all
    #             loader = loader + pks
    #         else: # overhead
    #             for pk in pks:
    #                 t = get_plurk_post_time(pk)
    #                 if t < dt2:
    #                     print('add plurk, plurkId=%d, postTime=%s' % (pk['plurk_id '], pk['posted']))
    #                     loader.append(pk)
    #                 else:
    #                     break
    #     print('get %d plurk' % len(loader))
    #     return loader

    def test_keywords(self, keywordList, string):
        for i in range(len(keywordList)):
            if keywordList[i] in string:
                return True, i + 1
        return False, None

    def timeline_detect(self, logFile, plurkFile):
        pks = self.fetch_newer_plurks(ts2offset(now() - 62), logFile,
                                      plurkFile)
        keywordList = ['!占星骰', '!占星骰', '#召喚占星骰', '[召喚占星骰]', '召喚占星骰']
        for pk in pks:
            b, i = self.test_keywords(keywordList, pk['content_raw'])
            if b:
                print('has keyword')
                self.reply_astroDice(pk['plurk_id'], i, logFile)

    def reply_astroDice(self, plurkId, keywordId, logFile):
        tpl = dice()
        content = dice2str(tpl)
        logFile.log('%s, responseAdd, keyword=%d, pkid=%d, dice(%s)' %
                    (now_str(), keywordId, plurkId, str(tpl)))
        self.responseAdd(plurkId, content)
Beispiel #36
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
 
import re
import json
import urllib.request
import random
from itertools import islice
#import oauth2 as oauth
import sys

from plurk_oauth import PlurkAPI

 
plurk = PlurkAPI('APP_KEY', 'APP_SECRET')
plurk.authorize('ACCEESS_TOKEN', 'ACCESS_TOKEN_SECRET')
 
comet = plurk.callAPI('/APP/Realtime/getUserChannel')
comet_channel = comet.get('comet_server') + "&new_offset=%d"
jsonp_re = re.compile('CometChannel.scriptCallback\((.+)\);\s*');

keywords = [u'什麼', u'甚麼', u'what', u'?', u'?', u'沙小', u'啥']
others = dict({u'儚い': '* https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif ** https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif ** https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif * 儚い~ * https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif ** https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif ** https://emos.plurk.com/03860276d09cb8c3af57f4e1f67d7a10_w48_h48.gif *',
		u'小薰': '......つ!!!! 小千...(臉紅 https://emos.plurk.com/3110c3c233c48956057ec5c4628e3629_w39_h48.png',
		u'kaoru': '什麼事? 可愛的小貓咪?',
		u'喵': '\nhttps://emos.plurk.com/2855722f8a0cac58d9503de3999e3a16_w46_h48.jpeg 喔呀,可愛的小貓咪有什麼事呢? 這麼大的雨,待在這裡可是會感冒的喔?\nhttps://emos.plurk.com/cbf27bddd90675c4baf25fc7ce9c9ee9_w48_h47.jpeg ...薰,你在做什麼?\nhttps://emos.plurk.com/c998f6c405b82415369ee41a5cecb8bb_w48_h48.gif 呦,千聖,我打算給迷失的小貓咪找個家哦\nhttps://emos.plurk.com/2c98e01f6ab8b6483815c43b263e76fc_w47_h48.jpeg ...傘給我\nhttps://emos.plurk.com/8737ccc164cff4da40a56e1048e6d55e_w44_h48.jpeg ?\nhttps://emos.plurk.com/fff851e041880f422788fbc81f1ee159_w45_h48.jpeg 把傘給我幫你拿,這樣你也比較輕鬆吧?',
		u'貓咪': '\n哎呀 看來又有一隻小貓咪因為我的美麗 被奪去了心神\n啊~ 太美也是一種罪惡啊',
	        u'嗚欸': '啊,花音,你又迷路了嗎?',
		u'嗚誒': '啊,花音,你又迷路了嗎? 我們一起走吧',
		u'莎莎': '我的名字不叫莎莎喔,小貓咪',
	        u'千聖': '千聖是我的幼馴染呢,你也喜歡她嗎? 我也是呢 (自豪+儚い閃光',
Beispiel #37
0
    pip.main(['install', 'base36'])
    import base36

import urllib.request as urllib2
import sys
import json
from datetime import datetime
import datetime
from html.parser import HTMLParser

with open('token.json', 'r') as reader:
    Tjs = json.loads(reader.read())

TOKEN = Tjs['Discord']['Token']
ChannelID = Tjs['Discord']['ChannelID']
plurk = PlurkAPI(Tjs['Plurk']['APP_KEY'], Tjs['Plurk']['APP_SECRET'])
plurk.authorize(Tjs['Plurk']['ACCEESS_TOKEN'],
                Tjs['Plurk']['ACCESS_TOKEN_SECRET'])

Client = discord.Client()
bot = commands.Bot(command_prefix=Tjs['Discord']['Prefix'])

BlockedUser = dict()


def GetPlurkss():

    return plurk.callAPI('/APP/Timeline/getPlurks',
                         options={
                             'limit': '1',
                             'minimal_data': 'false',
Beispiel #38
0
def time_stamp():
    localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    return localtime


# fixed_plurk
fixed_plurk = {
    "plurk_id": "",
    "content": "",
    "qualifier": "says", "lang": "tr_ch"
}

if __name__ == '__main__':

    # get api token
    plurk = PlurkAPI.fromfile("api.key")

    # user info
    with codecs.open("users.yaml", encoding="utf-8") as f:
        users = yaml.load(f)

    try:
        # get every plurks
        timeline_plurks = plurk.callAPI('/APP/Polling/getPlurks', options={"offset": "2019-10-26T11:48:00"})['plurks']

        # choose new plurks(plurk_type == 0) from all plurks
        unread_plurks = [unread_plurk for unread_plurk in timeline_plurks
                         if unread_plurk['plurk_type'] == 0 and unread_plurk['owner_id'] in users['ids']]

        for unread_plurk in unread_plurks:
            # replurk format
Beispiel #39
0
def usage():
    print('''Help Information:
    -h: Show help information
    ''')


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        print(str(err))  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    with open('API.keys', 'r+') as f:
        data = json.load(f)
        plurk = PlurkAPI(data["CONSUMER_KEY"], data["CONSUMER_SECRET"])
        if data.get('ACCESS_TOKEN'):
            plurk.authorize(data["ACCESS_TOKEN"], data["ACCESS_TOKEN_SECRET"])
        else:
            plurk.authorize()
            data["ACCESS_TOKEN"] = plurk._oauth.oauth_token['oauth_token']
            data["ACCESS_TOKEN_SECRET"] = plurk._oauth.oauth_token['oauth_token_secret']
            f.seek(0)
            json.dump(data, f)

    content = 'Test from Plurk OAuth API'
    if len(sys.argv) > 1:
        content = sys.argv[1]
    qualifier = 'says'
    if len(sys.argv) > 2:
        qualifier = sys.argv[2]
Beispiel #40
0
        all_plurks = strip_tags(all_plurks)
        all_plurks = re.sub("\n[A-Za-z0-9_]*:", "\n", all_plurks)
        with open("data/" + i[1] + "_about.txt", "w") as f:
            f.write(about.encode("utf-8"))
        with open("data/" + i[1] + "_content.txt", "w") as f:
            f.write(all_plurks.encode("utf-8"))


OAUTH_REQUEST_TOKEN = "https://www.plurk.com/OAuth/request_token"
OAUTH_kCCESS_TOKEN = "https://www.plurk.com/OAuth/access_token"
key = "5JyesLyP14Hl"
secret = "sZbmxdVjYVjzkkJQ1LgK6z3dr8L1WwBs"
token = "xexYrByo6gIC"
token_secret = "XS6HdIwMX05wTUrTU1DGhalEz0jCuf31"

plurk = PlurkAPI(key, secret)
plurk.authorize(token, token_secret)

if (args.keyword == ""):
    if int(args.friends_n) == 0:
        if int(args.plurks_n) != 0:
            my_Profile = plurk.callAPI("/APP/Profile/getPublicProfile",
                                       options={"user_id": args.user})
            my_id = my_Profile["user_info"]["id"]
            friends_list = [(my_id, args.user)]
            get_friends_data(friends_list)
            exit()
        else:
            print("GG")
            exit()
    if int(args.plurks_n) == 0:
Beispiel #41
0
            yin_yang_yao(input_list_summed[3], compute_move=True),
            yin_yang_yao(input_list_summed[4], compute_move=True),
            yin_yang_yao(input_list_summed[5], compute_move=True),
        )
        change_to = baguaToHexagram(strToBagua(up)+strToBagua(down))
    return this_hexa, change_to

config = configparser.RawConfigParser()
config.read('config.ini')
App_key = config.get('SECRET', 'App_key')
App_secret = config.get('SECRET', 'App_secret')
oauth_token_secret = config.get('SECRET', 'oauth_token_secret')
oauth_token = config.get('SECRET', 'oauth_token')

print('Authorizing...')
plurk = PlurkAPI(App_key, App_secret)
plurk.authorize(oauth_token, oauth_token_secret)

# Do some tests for a certain fixed plurk (https://www.plurk.com/p/mpxyit)
req = plurk.callAPI('/APP/Timeline/getPlurk/?plurk_id={}'.format(1373830661))
content_raw = req['plurk']['content_raw']
content = req['plurk']['content']
is_ask = isAsking(content_raw)
if(is_ask):
    h, t = is_ask
    hexagram_raw = content.split('<br />')[h:t+1]
    hexagram_list = [[swapRndnum(int(y.split(' ')[-2][-2])) for y in c.split('<')[1:]] for c in hexagram_raw ]
    print(listToHexagram(hexagram_list))