def ListMessagesWithLabels(service, user_id, label_ids=[]): """List all Messages of the user's mailbox with label_ids applied. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. label_ids: Only return Messages with these labelIds applied. Returns: List of Messages that have all required Labels applied. Note that the returned list contains Message IDs, you must use get with the appropriate id to get the details of a Message. """ try: response = service.users().messages().list(userId='me', labelIds=label_ids).execute(http=auth.getAuth(user_id)) messages = [] if 'messages' in response: msgs = response['messages'] for msg in msgs[:30]: threadId = msg['threadId'] _cache = memcache.get("threadId_" + threadId) if _cache is not None: messages.append(_cache) else: mail_msg = GetMimeMessage(service, user_id, threadId) memcache.add("threadId_" + threadId, mail_msg) messages.append(mail_msg) return messages except errors.HttpError, error: print 'An error occurred: %s' % error
def get(self): # set the headers to return valid format for JSON self.response.headers.add_header("Content-Type", "application/json") # userID is an INT that is supplied from oAuth (this is then passed to check that we are authorized to perform the request) userId = self.request.get("userId") # perform API request to get list if labels results = service.users().labels().list(userId="me").execute(http=auth.getAuth(userId)) # get the labels labels = results.get("labels", []) # reuturn the labels back to the user self.response.out.write(labels)
def post_tweet(tweet, id): # Twitter Tokens api = auth.getAuth() # Seting "@var tweet" to be posted as status. # Getting picture media = api.media_upload("weather_image.png") # Sending # if(id == 0): status = api.update_status(status=tweet, media_ids=[media.media_id])
def GetMessage(user_id, msg_id): """Get a Message with given ID. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. msg_id: The ID of the Message required. Returns: A Message. """ try: message = service.users().messages().get(userId='me', id=msg_id).execute(http=auth.getAuth(user_id)) return message except errors.HttpError, error: print 'An error occurred: %s' % error
def GetMimeMessage(service, user_id, msg_id): """Get a Message and use it to create a MIME Message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. msg_id: The ID of the Message required. Returns: A MIME Message, consisting of data from Message. """ try: data = {} message = service.users().messages().get(userId='me', id=msg_id, format='raw').execute(http=auth.getAuth(user_id)) msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII')) msg = message_from_string(msg_str) subject=getmailheader(msg.get('Subject', '')) data["subject"] = subject from_ = getmailaddresses(msg, 'from') data["from"] = from_ tos=getmailaddresses(msg, 'to') data["to"] = tos data['msgId'] = msg_id html = [] text = [] for part in msg.walk(): if part.get_content_type() == "text/plain": text.append(part) elif part.get_content_type() == "text/html": html.append(part) if html: soup = BeautifulSoup(html[0].get_payload(decode=True).decode(html[0].get_content_charset())) texts = soup.findAll(text=True) data["payload"] = "".join(texts) elif text: data["payload"] = text[0].get_payload(decode=True).decode(text[0].get_content_charset()) else: raise Exception('No suitable part found') return data except errors.HttpError, error: print 'An error occurred: %s' % error
def SendMessage(user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Message. """ try: message = (service.users().messages().send(userId="me", body=message) .execute(http=auth.getAuth(user_id))) print 'Message Id: %s' % message['id'] return message except errors.HttpError, error: print 'An error occurred: %s' % error
def GetThread(user_id, thread_id): """Get a Thread. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. thread_id: The ID of the Thread required. Returns: Thread with matching ID. """ try: thread = service.users().threads().get(userId='me', id=thread_id).execute(http=auth.getAuth(user_id)) messages = thread['messages'] print ('thread id: %s - number of messages ' 'in this thread: %d') % (thread['id'], len(messages)) return thread except errors.HttpError, error: print 'An error occurred: %s' % error
print("Searching for tweets...", flush=True) last_seen_id = retrieve_last_seen_id(mentions_file) mentions = api.mentions_timeline(last_seen_id, tweet_mode="extended") for mention in reversed(mentions): # mention.text if not mention: return print("New tweet found, replying...", flush=True) # print(str(mention.id) + '-' + mention.full_text, flush=True) # print(mention.full_text[16:]) last_mention = mention.id store_last_seen_id(last_mention, mentions_file) post_tweet_call(mention.full_text[16:].strip(), mention.id) def post_tweet_call(text, id): print("text: ", text) print("id: ", id) os.system( "python3 /home/pi/TwitterProject/src/tweeting/post_tweet.py \"{}\" \"{}\"" .format(text, id)) while True: # # Twitter Tokens api = auth.getAuth() while True: retrieve_mentions() time.sleep(10)
client = commands.Bot(command_prefix='^') @client.command( name='Search', description= 'Google searches and sends the top results to text channel, default # of results are one but can be changed in request', help= 'Type "Search" and an optional amount of desired results followed by a google search query' ) async def LetMeGoogleThat(ctx, results=1): if results > 10: await ctx.send("Too many results to search for try 10 or less") return await ctx.send('Please enter search Query') query = await client.wait_for('message') if query.author != client: await ctx.send( f'now searching for {results} results for "{query.content}"') for i in search(str(query.content), stop=results, verify_ssl=False, safe='on'): await ctx.send(i) token = auth.getAuth() client.run(token)
import spotipy import pdb from auth import getAuth, getUserId from sets import Set sp = spotipy.Spotify(auth=getAuth()) def get_user_data_total_liked_tracks(sp): return sp.current_user_saved_tracks()['total'] def create_song_set(sp, total): songs = Set([]) i = 0 while i < total: i += 20 tracks = sp.current_user_saved_tracks(20, i) for c, t in enumerate(tracks['items']): if (t['track']['album']['artists'][0]['name'] != 'Vitamin String Quartet'): songs.add(t['track']['name'].encode('ascii', 'ignore')) return songs def get_total_artist_album(artist): return sp.artist_albums(artist, 'album', 'US')['total'] def get_artist_albums(artist): albums = {} i = 0
def getUser(): return getAuth(SPOTIPY_CLIENT_ID, "{}:{}/callback/".format(SPOTIPY_REDIRECT_URI, PORT), SCOPE)