def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None): """ Perform the OAuth dance with some command-line prompts. Return the oauth_token and oauth_token_secret. Provide the name of your app in `app_name`, your consumer_key, and consumer_secret. This function will open a web browser to let the user Allow your app to access their Twitter account. PIN authentication is used. If a token_filename is given, the oauth tokens will be written to the file. """ print("Hi there! We're gonna get you all set up to use %s." % app_name) twitter = Twitter(auth=OAuth('', '', consumer_key, consumer_secret), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( twitter.oauth.request_token()) print(""" In the web browser window that opens please choose to Allow access. Copy the PIN number that appears on the next page and paste or type it here: """) oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' + oauth_token) print("Opening: %s\n" % oauth_url) try: r = webbrowser.open(oauth_url) time.sleep(2) # Sometimes the last command can print some # crap. Wait a bit so it doesn't mess up the next # prompt. if not r: raise Exception() except: print(""" Uh, I couldn't open a browser on your computer. Please go here to get your PIN: """ + oauth_url) oauth_verifier = _input("Please enter the PIN: ").strip() twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_key, consumer_secret), format='', api_version=None) oauth_token, oauth_token_secret = parse_oauth_tokens( twitter.oauth.access_token(oauth_verifier=oauth_verifier)) if token_filename: write_token_file(token_filename, oauth_token, oauth_token_secret) print() print("That's it! Your authorization keys have been written to %s." % (token_filename)) return oauth_token, oauth_token_secret
def __init__(self, configFilename): self.configFilename = configFilename self.config = load_config(self.configFilename) global ACTIVE_PREFIXES ACTIVE_PREFIXES = PREFIXES[self.config.get('irc', 'prefixes')] oauth_file = self.config.get('twitter', 'oauth_token_file') if not os.path.exists(oauth_file): oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file) oauth_token, oauth_secret = read_token_file(oauth_file) self.twitter = Twitter( auth=OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1', domain='api.twitter.com') self.irc = irclib.IRC() self.irc.add_global_handler('privmsg', self.handle_privmsg) self.irc.add_global_handler('ctcp', self.handle_ctcp) self.ircServer = self.irc.server() self.sched = Scheduler( (SchedTask(self.process_events, 1), SchedTask(self.check_statuses, 120))) self.lastUpdate = (datetime.utcnow() - timedelta(minutes=10)).utctimetuple()
def __init__(self, oauth_token=None, oauth_token_secret=None): self.config = config self.oauth_client = None self.http_client = httplib2.Http() if (oauth_token and oauth_token_secret): self.oauth_client = OAuth(token=oauth_token, secret=oauth_token_secret).client()
def __get_oauth_url(self, url, method): """ Generate oAuth1.0a URL """ oauth = OAuth(url=url, consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, version=self.version, method=method) return oauth.get_oauth_url()
def get(self): gh_code = self.get_query_argument('code', None) if not gh_code: return self.redirect('/') gh_oauth = OAuth(gh_code) yield gh_oauth.set_access_token() if not gh_oauth.access_token: return self.redirect('/') user_data = yield gh_oauth.get_user_data() login = user_data['login'] user = yield User.get(login=login) if not user: user = User(login, data=user_data, gh_token=gh_oauth.access_token) yield user.put() self.set_secure_cookie('token', user.token) self.redirect('/')
from django.shortcuts import render, redirect, HttpResponse from django.conf import settings from django.template import loader from oauth import OAuth oauthWrapper = OAuth(settings.NCTU_APP_CLIENT_ID, settings.NCTU_APP_CLIENT_SECRET, settings.NCTU_APP_REDIRECT_URI) def login(request): # check for token from nctu oauth redirection if OAuth.get_profile(request) == None: return oauthWrapper.authorize() return redirect('/')
track_details['followers'] = followers # try except to catch Spotify max retries error try: # get audio features attribute_info(sp, mood, track_uri, track_details) except: print("Connection refused by the server...") print("sleeping for 5 seconds...") time.sleep(5) print("Slept for 5 seconds, time to continue...") continue return track_dict sp = OAuth() token = sp.get_token() if token: # get angry songs track_dict = {} sp = spotipy.Spotify(auth=token) print(type(sp)) track_dict = get_songs(sp, 0, num_angry, angry, track_dict) # get info about angry songs print(len(track_dict)) # turn dictionary of songs into a dataframe df = pd.DataFrame.from_dict(track_dict, orient='index') df.rename(columns={'Unnamed: 0': 'track_uri'}, inplace=True) print(df)
def main(): auth = OAuth(oauth_filename) if not auth.is_login() or auth.get_expire_time() < datetime.datetime.now(): username = input('user name or email address: ') password = input('password: '******'r') as f: cache_list = json.load(f) else: cache_list = [] cache_list = set(cache_list) exp_json = requests.get('https://www.bilibili.com/plus/account/exp.php', cookies=cookies).json() coins_left = 5 - int(exp_json['number'] / 10) page = 1 while True: params = {'callback': 'abc', 'pn': page, 'ps': 100, 'jsonp': 'jsonp'} history_json = json.loads( requests.get('https://api.bilibili.com/x/v2/history', params=params, cookies=cookies, headers={ 'Referer': 'https://www.bilibili.com' '/account/history' }).text[4:-1]) for video in history_json['data']: bvid = video['bvid'] aid = video.get('aid', bv_to_av(bvid)) copyright = video['copyright'] headers = {'Referer': f'https://www.bilibili.com/video/av{aid}'} if aid not in cache_list: params = {'callback': 'abc', 'jsonp': 'jsonp', 'aid': aid} coin_json = json.loads( requests.get( 'https://api.bilibili.com/x/web-interface/archive/coins', params=params, cookies=cookies, headers=headers).text[4:-1]) available_coins = 3 - copyright - coin_json['data']['multiply'] throw_coins = min(coins_left, available_coins) if throw_coins > 0: params = { 'aid': aid, 'multiply': throw_coins, 'select_like': 0, 'cross_domain': True, 'csrf': cookies['bili_jct'] } requests.post( 'https://api.bilibili.com/x/web-interface/coin/add', data=params, cookies=cookies, headers=headers) print('throw %d coins to av%d' % (throw_coins, aid)) if throw_coins == 0 or throw_coins == available_coins: cache_list.add(aid) coins_left -= throw_coins if coins_left == 0: with open(cache_coin_av_list, 'w') as f: json.dump(list(cache_list), f) return if len(history_json['data']) == 0: with open(cache_coin_av_list, 'w') as f: json.dump(list(cache_list), f) return page += 1
def __init__(self, parent): wx.Panel.__init__(self, parent, -1) # Create a dataview control self.dvc = dv.DataViewCtrl(self, style=wx.BORDER_THEME | dv.DV_ROW_LINES | dv.DV_VERT_RULES | dv.DV_MULTIPLE) self.model = DataModel([]) self.dvc.AssociateModel(self.model) self.dvc.AppendTextColumn("path", 1, width=170) self.dvc.AppendTextColumn("title", 2, width=300, mode=dv.DATAVIEW_CELL_EDITABLE) self.dvc.AppendProgressColumn("progress", 3, width=130) self.dvc.AppendTextColumn("status", 4, width=300, mode=dv.DATAVIEW_CELL_EDITABLE) # set the Sizer property (same as SetSizer) self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer.Add(self.dvc, 1, wx.EXPAND) b2 = wx.Button(self, label="Add files") self.Bind(wx.EVT_BUTTON, self.OnAddRow, b2) self.button_add = b2 b3 = wx.Button(self, label="Delete selected") b3.Enable(False) self.Bind(wx.EVT_BUTTON, self.OnDeleteRows, b3) self.button_delete = b3 b5 = wx.Button(self, label="Start upload") b5.Enable(False) self.Bind(wx.EVT_BUTTON, self.start_upload, b5) self.button_upload_start = b5 b6 = wx.Button(self, label="Stop upload") b6.Enable(False) self.Bind(wx.EVT_BUTTON, self.stop_upload, b6) self.button_upload_stop = b6 self.in_progress = False self.files_in_progress = 0 btnbox = wx.BoxSizer(wx.HORIZONTAL) btnbox.Add(b2, 0, wx.LEFT | wx.RIGHT, 5) btnbox.Add(b3, 0, wx.LEFT | wx.RIGHT, 5) btnbox.Add(b5, 0, wx.LEFT | wx.RIGHT, 5) btnbox.Add(b6, 0, wx.LEFT | wx.RIGHT, 5) self.Sizer.Add(btnbox, 0, wx.TOP | wx.BOTTOM, 5) # Bind some events so we can see what the DVC sends us self.Bind(dv.EVT_DATAVIEW_ITEM_START_EDITING, self.on_before_edit, self.dvc) # self.Bind(dv.EVT_DATAVIEW_ITEM_EDITING_DONE, self.OnEditingDone, self.dvc) # self.Bind(dv.EVT_DATAVIEW_ITEM_VALUE_CHANGED, self.OnValueChanged, self.dvc) self.Bind(dv.EVT_DATAVIEW_ITEM_ACTIVATED, self.RightClick, self.dvc) parent.Bind(wx.EVT_CLOSE, self.OnClose) self.parent = parent # worker stuff self.enclosure_queue = Queue() self.worker = None # drop file_drop_target = MyFileDropTarget(self.on_drop) self.SetDropTarget(file_drop_target) auth = OAuth(self) self.oauth = auth if not auth.ShowModal(): self.parent.Close()
if options['refresh'] and options['action'] not in ('friends', 'public', 'replies'): print >> sys.stderr, "You can only refresh the friends, public, or replies actions." print >> sys.stderr, "Use 'twitter -h' for help." return 1 oauth_filename = os.path.expanduser(options['oauth_filename']) if (options['action'] == 'authorize' or not os.path.exists(oauth_filename)): oauth_dance("the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename']) oauth_token, oauth_token_secret = read_token_file(oauth_filename) twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=options['secure'], api_version='1', domain='api.twitter.com') try: Action()(twitter, options) except NoSuchActionError, e: print >> sys.stderr, e raise SystemExit(1) except TwitterError, e: print >> sys.stderr, str(e) print >> sys.stderr, "Use 'twitter -h' for help." raise SystemExit(1)
return delta.total_seconds() def _get_next_alarm(self): today = datetime.now() today_alarm = datetime(today.year, today.month, today.day, 18, 40, 0) if (today_alarm - today - timedelta(seconds=15)).days >= 0: return today_alarm else: return today_alarm + timedelta(days=1) def run(self): if self.chat_client.connect(): self.chat_client.process(block=False) while True: sleep(self._get_secs_to(self._get_next_alarm())) self.send_alarm() else: raise RuntimeError("Unable to connect!") if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s', stream=sys.stdout) oauth = OAuth() oauth.read_cfg('oauth.cfg') jid = '*****@*****.**' chat_client = ChatClient(jid, oauth) medbot = MedBot(chat_client, 'Buddy') medbot.run()
from pprint import pprint from api import Foursquare from oauth import OAuth if __name__ == '__main__': # say hello and ask for foursquare email/phone print('Foursquare API') print('--------------\n') username = raw_input( 'Email associated with your Foursquare account: ').strip() # build oauth obj, do oauth_dance if oath_token not available oauth_fname = '%s.token' % username if not os.path.exists(oauth_fname): raise Exception('need to do OAuth token getting blaaaah...') else: oauth_token = open(oauth_fname, 'r').readlines()[0] oauth_token = oauth_token.strip() auth = OAuth(oauth_token) # make our foursquare object fsq = Foursquare(auth=auth) # foursquare api requests phil_id = 5804431 me = fsq.users() my_friends = fsq.users.friends(id=phil_id) pprint(me)