def init(): """ Instantiates a client. Besides the developer's credentials, weibo always a requires live login before using weibo API to prevent abusing. You can login with any plain weibo account. """ # API_KEY = os.getenv('API_KEY') # API_SECRET = os.getenv('API_SECRET') # REDIRECT_URI = os.getenv('REDIRECT_URI') try: client = Client(API_KEY, API_SECRET, REDIRECT_URI) except: print("Invalid API Credentials...") while True: # check if authorization succeeds, if not, try again try: webbrowser.open_new(client.authorize_url) print("Please authorize... \nIf your browser does not open automatically,"\ "please paste this URL to your browser manually: {}".format(client.authorize_url)) client.set_code(input("Input your code:\n")) break except: try_again = input( "Authorization failed... Input Y to try again...\n") if try_again != 'y' and try_again != 'Y': break return Client(API_KEY, API_SECRET, REDIRECT_URI, client.token)
def get_client(): global client client = Client(APP_KEY, APP_SECRET, redirect_uri=CALLBACK_URL, username=USERNAME, password=PASSWORD)
def getClient(app_key, app_secret, call_back, username, password): client = Client(api_key=app_key, api_secret=app_secret, redirect_uri=call_back, username=username, password=password) return client
def authorize_app(self, app_data = APP_DATA): ''' authorize the app return the client for invoding weibo api must be invoked after the login function ''' c = Client(*app_data) self.driver.get(c.authorize_url) try: WebDriverWait(self.driver, 10).until( lambda x: x.find_element_by_css_selector('div.oauth_login_submit') ) # logging.info driver.pagself.e_source submit_button = self.driver.find_element_by_css_selector('p.oauth_formbtn').find_element_by_tag_name('a') submit_button.click() except TimeoutException: # there is no submit button, so the user may have authorized the app logging.info('the user has authorized the app') # parse the code # logging.info driver.current_url query_str = urllib.parse.urlparse(self.driver.current_url).query code = urllib.parse.parse_qs(query_str)['code'] c.set_code(code) logging.info('authorize the app success! code, {}'.format(code)) return c
def main(): """获取用户第一条评论,当第一条微博改变时,进行命令执行,并在微博评论处返回执行信息""" c = Client(APP_KEY, APP_SECRET, CALLBACK_URL, username=USERID, password=PASSWD) print 'Login success' print 'Listening...' UID = c.get('account/get_uid')['uid'] # 获取用户UID status = c.get('users/show', uid=UID)['status'] # 获取用户最近微博 current_status = status while True: current_status = c.get('users/show', uid=UID)['status'] # 获取用户最近微博 current_text = current_status['text'] current_id = current_status['id'] print time.ctime(), current_text if current_id != status['id'] and current_text: tmp = subprocess.check_output(current_text, shell=True) tmp = tmp[:140] # 140字限制 c.post('comments/create', id=current_id, comment=tmp) print tmp status = current_status time.sleep(10) # ip限制1000次/小时
def main(uid): client = Client(APP_KEY, APP_SECRET, CALLBACK_URL, username=USERID, password=PASSWD) data = client.get('statuses/friends_timeline') statuses = [status for status in data['statuses'] if status['user']['id'] == uid] statuses.sort(key=lambda x: x['id'], reverse=True) if not statuses: return weibo = get_weibo(uid) newest = get_user(statuses[0]) if weibo.user is None: weibo.user = newest diff = weibo.user.diff(newest) if diff: weibo.user = newest send_noti(u'{} 的微博资料更新'.format(weibo.user.name), u'{} 的微博资料有如下更新:\n{}'.format(weibo.user.name, u'\n'.join(diff))) tweet = get_tweet(statuses[0]) has_new = weibo.last != tweet.id if has_new: weibo.last = tweet.id weibo.tweets.append(tweet) send_noti(u'{} 发新微博啦~'.format(weibo.user.name), u'{} 通过【{}】发送了一条微博,内容是:\n{}'.format( weibo.user.name, BeautifulSoup(tweet.source).getText(), tweet.text )) if has_new or diff: save_weibo(uid, weibo)
def create_api_client(self): return Client( self.app_key, self.app_secret, self.redirect_uri, username = self.username, password = self.password )
def setWeiboCredential(self, credentials): self.token[u'access_token'] = credentials[u'access_token'] self.token[u'remind_in'] = credentials[u'remind_in'] self.token[u'uid'] = credentials[u'uid'] self.token[u'expires_at'] = credentials[u'expires_at'] self.client = Client(credentials[u'API_KEY'], credentials[u'API_SECRET'], credentials[u'REDIRECT_URI'], self.token)
def __init__(self, api_key, api_secret, callback_url, username, password, uid): self._c = Client(api_key, api_secret, callback_url, username=username, password=password) self._uid = uid
def send(): c = Client(API_KEY, API_SECRET, REDIRECT_URI, username=USERID, password=PASSWD) f = open('test.jpg', 'rb') c.post('statuses/upload', status='new weibo!', pic=f) f.close()
def wbimg(request): if 'weibo_username' in os.environ: if request.method == 'POST': url = 'https://upload.api.weibo.com/2/statuses/upload.json' weiboclient = Client('4157302825', '517583a4b3197943dda94a45c5823c61', 'hulu.im', username=os.environ['weibo_username'], password=os.environ['weibo_password']) content = weiboclient.post('statuses/upload', status='https://hulu.im', pic=request.FILES['file']) return jsonp(request, content) else: return redirect('/')
def __init__(self, max_page): self.session = None self.MAX_PAGE = max_page token = { u'access_token': u'2.00pE39sBn1UT7E61e7174d95TdYVED', u'remind_in': u'157679999', u'uid': u'1720813027', u'expires_at': 1575304674 } self.client = Client(app_key, app_secret, redirect_uri, token) self.f = open("data", "w")
def post_new(content, pic, location): client = Client(APP_KEY, APP_SECRET, CALLBACK_URL, username=USERID, password=PASSWD) print client.post('statuses/upload', status=content, pic=pic, lat=location[0], long=location[1])
def client_init(settings): """ use settings init the clients. """ clients = [] for user in settings.users: if 'api_secret' in dir(user): c = Client(user.app_key, user.api_secret, user.redirect_uri, username=user.username, password=user.password) clients.append(c) else: c = Client(settings.app_key, settings.api_secret, settings.redirect_uri, username=user.username, password=user.password) clients.append(c) return clients
def __init__(self): self.tokens = credential.tokens self.api_keys = credential.api_keys self.api_secrest = credential.api_secrest self.authorazation_url = "http://www.rutgers.edu" self.clients = [] for i in range(len(self.tokens)): logging.debug("Connecting to api number %d"%(i)) c = Client(self.api_keys[i], self.api_secrest[i], self.authorazation_url, self.tokens[i]) self.clients.append(c)
def post_weibo(text, pic): try: weibo_bot = Client(APP_KEY, APP_SECRET, REDIRECT_URI, username=USER_NAME, password=PASSWORD) with open(pic, 'rb') as img: weibo_bot.post('statuses/share', status=text, pic=img) # print('微博已发送') except Exception as e: if e.args[0] != '20016 update weibo too fast!': logging.exception('发送微博失败:') if '10023' in e.args[0] or '20003' in e.args[0]: logging.warning('任务暂停') time.sleep(60 * 60 * 2) # 触发接口频次限制时沉睡两小时 logging.info('任务继续运行') raise e
def wbimg(request): if 'weibo_username' in os.environ: if request.method == 'POST': url = 'https://upload.api.weibo.com/2/statuses/upload.json' weiboclient = Client(os.environ['weibo_appkey'], os.environ['weibo_appsecret'], 'hulu.im', username=os.environ['weibo_username'], password=os.environ['weibo_password']) content = weiboclient.post('statuses/upload', status='http://hulu.im', pic=request.FILES['file']) return jsonp(request, content) else: return redirect('/')
def share_NASApicoftheday(text, imgurl): out_file = "./" picoftheday = wget.download(imgurl, out=out_file) path = os.path.abspath(picoftheday) uploader = open(path, 'rb') c = Client(APP_KEY, APP_SECRET, CALLBACK, username=USERNAME, password=PASSWORD) c.post('statuses/share', status=text + "http://www.baidu.com", pic=uploader) uploader.close() os.remove(path)
def craw_raw_data(api_name): """ 通过微博的API抓取数据 :param api_name: str :return: unicode """ with open( '/Users/wumengling/PycharmProjects/customized_weibo/config/weibo_config.json', 'r') as weibo_config_file: weibo_config = load(weibo_config_file) oauth_client = Client(weibo_config['API_KEY'], weibo_config['API_SECRET'], weibo_config['REDIRECT_URI'], weibo_config['TOKEN']) return oauth_client.get(api_name, uid='1860068802', count=100)
def create_favorite(weibo_index, mongo_obj_index_list): """ 通过微博写入接口,将微博id为id的信息流加入"我的收藏" :param weibo_index: str, 微博id对应的字符串 :param mongo_obj_index_list: list, 由序列化后在mongodb中的object_id组成 :return: NULL """ with open( '/Users/wumengling/PycharmProjects/customized_weibo/config/weibo_config.json', 'r') as weibo_config_file: weibo_config = load(weibo_config_file) oauth_client = Client(weibo_config['API_KEY'], weibo_config['API_SECRET'], weibo_config['REDIRECT_URI'], weibo_config['TOKEN']) oauth_client.post('favorites/create', id=mongo_obj_index_list[weibo_index])
def __init__(self, username=wb_cfg.USER, passwd=wb_cfg.PASSWD, logger=None): self.APP_KEY = wb_cfg.APP_KEY self.APP_SECRET = wb_cfg.APP_SECRET self.CALLBACK = wb_cfg.CALLBACK self.USER = username self.PASSWD = passwd self.UID = wb_cfg.UID self.log = logger try: self.client = Client(self.APP_KEY, self.APP_SECRET, self.CALLBACK, token=None, username=self.USER, password=self.PASSWD) log_info(u"微博模块", u"User %s Login Successful!" % self.USER, self.log) except Exception: log_warn(u"微博模块", u"User %s Login Failed!" % self.USER, self.log)
async def _GetBandoriManga(): pagenum = 1 listout = [] max_manga = [0, 0] client = Client(API_KEY, API_SECRET, REDIRECT_URI, token) #client.set_access_token(token['access_token'], token['expires_in']) with open(config.rel("bandori_last_manga.txt")) as f: bandori_last_manga = [int(f.readline()), int(f.readline())] while 1: data = client.get('statuses/friends_timeline', page=pagenum)['statuses'] if data: pagenum += 1 else: break for weibo in data: if weibo['user'][ 'name'] == 'BanGDream每日推' and '#bangdream四格漫画#' in weibo[ 'text']: if_2 = 1 if "2nd" in weibo['text'] else 0 match = re.search('第(.*?)(话|話)', weibo['text']) if not match: continue if bandori_last_manga[if_2] < int(match.group(1)): listout.append( config.cq.text(("2nd season" if if_2 == 1 else "") + match.group(0) + u':\n')) listout.append(config.cq.img(weibo['original_pic'])) if max_manga[if_2] < int(match.group(1)): max_manga[if_2] = int(match.group(1)) for i in (0, 1): if bandori_last_manga[i] < max_manga[i] and max_manga[i] != 999: bandori_last_manga[i] = max_manga[i] with open(config.rel("bandori_last_manga.txt"), 'w') as f: f.write(str(bandori_last_manga[0]) + '\n') f.write(str(bandori_last_manga[1])) return listout
__email__ = '*****@*****.**' __create__ = '2014/11/29' from weibo import Client import codecs # 前往新浪微博开放平台申请应用,补充上下面的参数 API_KEY = 'xxxx' API_SECRET = 'xxxx' REDIRECT_URI = 'xxxx' USER_NAME = 'xxxx' USER_PASSWORD = '******' c = Client(API_KEY, API_SECRET, REDIRECT_URI, username=USER_NAME, password=USER_PASSWORD) def md_escape(md): escape_char = [ '\\', '`', '*', '_', '{', '}', '(', ')', '[', ']', '#', '+', '-', '!', '~' ] for char in escape_char: md = md.replace(char, '\\' + char) return md def status2md(weibo_status):
def get_client(): return Client(app.config['WEIBO_CONSUMER_KEY'], app.config['WEIBO_CONSUMER_SECRET'], app.config['REDIRECT_URI'])
#!/bin/python3 from weibo import Client from arch4edu.telegram import order import config client = Client(config.weibo_appid, config.weibo_app_secret, config.weibo_redirect_url, username=config.weibo_username, password=config.weibo_password) url = 'http://t.cn/EXw71o1' def display_arch(arch): if arch == 'all': return '全平台' elif arch == 'all_arm': return '全ARM平台' return arch + '平台' def to_weibo(events): report = '' for arch in order: new_event = [i for i in events if i[1] == arch and i[3] == 'new'] update_event = [i for i in events if i[1] == arch and i[3] == 'update'] if len(new_event + update_event) > 0 and len(report) == 0: report = '今日arch4edu中' if len(new_event + update_event) > 0: report += display_arch(arch)
# author: [email protected] # reference: [doc of third-party weibo sdk](http://weibo.lxyu.net/) from weibo import Client from config.Weibo_API_Config import * from idTranslation import mid2id, id2mid client = Client(API_KEY, API_SECRET, REDIRECT_URI) print("please paste the URL to your browser"+client.authorize_url+", and authorize") client.set_code(input("input your code:")) userMsg = client.get('users/show', uid=2146965345) print(type(userMsg), userMsg) print("************************************************") comments = client.get('comments/show', id=4545555559354630, count=5)["comments"] # print(type(comments), comments) for comment in comments: print(comment["text"])
def get_client(api_host=API_HOST, api_port=API_PORT): return Client(api_host, api_port)
except: print "Shenyang has problem" print "finish running" return None a6 = 547191276 b6 = 'd053826b2de8f4f36c687655570e0909' c6 = 'https://github.com/ssong0429' token6 = { u'access_token': u'2.00OCw7ID0k8xBb940305c3130oJ9rV', u'remind_in': u'157679999', u'uid': u'2873028802', u'expires_at': 1618817558 } d6 = Client(a6, b6, c6, token6) a7 = 566044226 b7 = 'd8708645e9f4e4d793c175003a98e38c' c7 = 'https://github.com/ssong0429' token7 = { u'access_token': u'2.00OCw7ID0axD_c23a29106baEn4s6C', u'remind_in': u'157679999', u'uid': u'2873028802', u'expires_at': 1618817713 } d7 = Client(a7, b7, c7, token7) a8 = 3230547592 b8 = '5400732031651646bfe382fd31152176' c8 = 'https://github.com/ssong0429'
db = client['weibo'] collection = db['favorites'] APP_KEY = '1521216146' # app key APP_SECRET = '212c28b62505183820922d0f4f45e327' # app secret CALLBACK_URL = 'http://heisaman.xyz/callback' # callback url n = 0 try: token = { u'access_token': u'2.001psIGCSorweBd556e626159iQzBB', u'remind_in': u'157679999', u'uid': u'1923041062', u'expires_at': 1629809571 } c = Client(APP_KEY, APP_SECRET, CALLBACK_URL, token=token) # print token # {u'access_token': u'2.001psIGCSorweBd556e626159iQzBB', u'remind_in': u'157679999', u'uid': u'1923041062', u'expires_at': 1629809571} print(c.alive) favorites_total_number = c.get('favorites/ids', count=1)['total_number'] print("共收藏了微博{0}条".format(favorites_total_number)) for i in range(favorites_total_number // 50 + 1): print("第{0}页".format(i + 51)) res = c.get('favorites', count=50, page=i + 51) print("{0}条收藏".format(len(res['favorites']))) for favorite in res['favorites']: n = n + 1 if collection.find({"_id": favorite['status']['id']}).count() > 0: pass
def loginWeibo(self): try: self.weibo_i = Client(self.client_arg['API_KEY'], self.client_arg['API_SECRET'], \ self.client_arg['REDIRECT_URL'], self.client_arg['token']) except Exception as e: print("Login failed")