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 ;)")
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")
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)
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)
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")
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']
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")
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'千聖': '千聖是我的幼馴染呢,你也喜歡她嗎? 我也是呢 (自豪+儚い閃光', u'機車': '小貓咪心情不好嗎?真是儚い啊', u'去死': '怎麼了小貓咪? 今天很暴躁呢',
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
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'))
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)
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'))
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] print(plurk.callAPI('/APP/Timeline/plurkAdd', { 'content': content, 'qualifier': qualifier }))
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') + "&new_offset=%d" jsonp_re = re.compile('CometChannel.scriptCallback\((.+)\);\s*') new_offset = -50 def handle(msg): #debug用 #pprint.pprint(msg) content_type, chat_type, chat_id = telepot.glance(msg) chat_id = msg['chat']['id']
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: print("GG") exit() my_Profile = plurk.callAPI("/APP/Profile/getPublicProfile", options={"user_id": args.user}) my_id = my_Profile["user_info"]["id"] my_friends_id = plurk.callAPI("/APP/FriendsFans/getFriendsByOffset", options={
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)) ''' comet = plurk.callAPI('/APP/Realtime/getUserChannel') comet_channel_str = comet.get('comet_server') + "&new_offset={}" new_offset = -1