jtweets = [process_tweet(r) for r in results] # ban a few simple aggregator accounts banned = ['medrxivpreprint', 'biorxivpreprint', 'glycopreprint'] jtweets = [t for t in jtweets if t['name'] not in banned] return jtweets # ----------------------------------------------------------------------------- if __name__ == '__main__': keys = get_api_keys() api = twitter.Api(consumer_key=keys[0], consumer_secret=keys[1], access_token_key=keys[2], access_token_secret=keys[3], tweet_mode='extended') # run forever while True: # open the latest state of database with open('jall.json', 'r') as f: jall = json.load(f) # get all tweets for all papers tweets = {} for i, j in enumerate(jall['rels']): jtweets = get_tweets(j) tweets[j['rel_doi']] = jtweets
from config import * from flask import Flask, jsonify,request from flask_cors import CORS global path import logging from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.tokenize import word_tokenize # from textblob import TextBlob import io api = twitter.Api(consumer_key=twitter_app_key, consumer_secret=twitter_app_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret) gmaps = googlemaps.Client(key=google_key) language_dict = dict(languages_countries_dict.languages) countries_dict = dict(languages_countries_dict.countries) def get_key(_string): return ''.join(chr(int(i) + 97) for i in _string.split('|')) alerts_password = get_key(password_encr)
try: import json except ImportError: import simplejson as json import twitter import time from langid.langid import LanguageIdentifier, model ACCESS_KEY = '1052159436108779520-umLnDy6pA9mfDiU2Sr52GDdFUFgR6l' ACCESS_SECRET = 'QgiAitaCOqRrI7cq8b1AYiNiPC1Ol6TeLnLGBwxu6swn3' CONSUMER_KEY = 'Vn2vtBzY8uZirkuqIMJQHLpbD' CONSUMER_SECRET = 'BcluieZLGLqgwT8Xn2J6nbuYmjrOwNHeWdfsn9HDc8f2OKlQgK' api = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key=ACCESS_KEY, access_token_secret=ACCESS_SECRET, sleep_on_rate_limit=True) def gatherTweets(data): data = json.load(data) usrDict = {} for key in data: usrDict[key['id']]=[] try: tmp = api.GetUserTimeline(user_id=key['id'], count=200) for tweet in tmp: text=tweet.text usrDict[key['id']].append(text)
def get_api(auth, name=''): return twitter.Api(**auth['twitter'][name or Name.NAME])
from flask import Flask from flask import render_template, flash, redirect, session, url_for, request, g from app import app from example import extract_words import twitter from math import pow, exp from string import ascii_letters api = twitter.Api( consumer_key='WEAtvjCzQYb92C8WNPHiD8gTI', consumer_secret='K2kjcE8zmBj7lx1Y1XmsOs4FaVYTwMDcJoM3ULG0fBFqGCL4sH', access_token_key='2842676480-LotHCY0lXhJMfVUrCBZBenJPrfcE58lqG82xJGD', access_token_secret='yVhww4cNX0kBccyOIrQpGBTPpXfukGGW1HopleVuGxAp9') @app.route('/') @app.route('/index') def my_form(): return render_template("my-form.html", name='Home') def classifySentiment(words, happy_log_probs, sad_log_probs): # Get the log-probability of each word under each sentiment happy_probs = [ happy_log_probs[word] for word in words if word in happy_log_probs ] sad_probs = [ sad_log_probs[word] for word in words if word in sad_log_probs ] # Sum all the log-probabilities for each sentiment to get a log-probability for the whole tweet
import json import os import sys import twitter USER_SCREEN_NAME = sys.argv[1] TWEET_AMOUNT = 200 # cannot exceed 200 per call # call https://developer.twitter.com/en/apps/app_id to get the credentials api = twitter.Api() # get latest 2 * TWEET_AMOUNT tweets by this user. data = api.GetUserTimeline(screen_name=USER_SCREEN_NAME, count=TWEET_AMOUNT) data2 = api.GetUserTimeline(screen_name=USER_SCREEN_NAME, count=TWEET_AMOUNT, max_id=(data[199].id-1)) as_json = [json.loads(str(d)) for d in data] as_json.extend([json.loads(str(d)) for d in data2]) # write to file as JSON with open(USER_SCREEN_NAME+'Tweets.json', 'w') as file: json.dump(as_json, file) user = api.GetUser(screen_name=USER_SCREEN_NAME) user_as_json = [json.loads(str(user))] with open(USER_SCREEN_NAME+'User.json', 'w') as file: json.dump(user_as_json, file)
database='dispositivo', user='******', password='******') cur = con.cursor() #extrai a tupla de mac e nome do db e converte em dicionário cur.execute('select mac, nome from mac') macs = dict(cur.fetchall()) con.close() dispositivosConhecidos = [] dispositivosDesconhecidos = [] #Autenticação do twitter api = twitter.Api( consumer_key='9yVXdpHRetwN643Qux2TE2C14', consumer_secret='sBmujbqdIwnKD8ucd96p3bsam3MguiSThFXbMzzJLgQI4M4rl6', access_token_key='832896102366068736-V2zAYhuAA8D6n0GvFjPyqitSZo1jvsX', access_token_secret='31ORvOjvpxU3bRYVVAgSG2vt8lxTlNbBYOCESiFeWODiZ') #Buscando os dispositivos conectados da minha rede nm = nmap.PortScanner() cidr2 = '192.168.0.1-254' # rede da facul #cidr2='10.1.4.0-254' a = nm.scan(hosts=cidr2, arguments='-sP') for k, v in a['scan'].iteritems(): try: endMac = str(v['addresses']['mac'])
def handle(self, *args, **kwargs): if kwargs['username'] == '': sys.stderr.write( self.style.ERROR( "Must supply a Twitter username using the --username argument.\n" )) sys.exit(1) api_key = settings.TWITTER_API api = twitter.Api(tweet_mode='extended', consumer_key=api_key['consumer_key'], consumer_secret=api_key['consumer_secret'], access_token_key=api_key['access_token'], access_token_secret=api_key['access_secret']) res = api.GetSearch(term=kwargs['username'], result_type='recent', return_json=True, include_entities=True, count=100) outgoing = [] incoming = [] for tweet in res['statuses']: if tweet['user']['screen_name'] == kwargs['username']: if 'retweeted_status' in tweet: continue outgoing.append(tweet) continue for mention in tweet['entities']['user_mentions']: if mention['screen_name'] == kwargs['username']: incoming.append(tweet) continue for tweet in incoming: dt = dateparse(tweet['created_at']) addr = "https://twitter.com/" + tweet['user']['screen_name'] try: t = RemoteInteraction.objects.get(type='microblogpost', incoming=True, address=addr, time=dt) except: t = RemoteInteraction(type='microblogpost', incoming=True, address=addr, time=dt, message=tweet['full_text']) t.save() for tweet in outgoing: dt = dateparse(tweet['created_at']) if len(tweet['entities']['user_mentions']) == 0: try: t = RemoteInteraction.objects.get(type='microblogpost', incoming=False, address='', time=dt) except: t = RemoteInteraction(type='microblogpost', incoming=False, address='', time=dt, message=tweet['full_text']) t.save() else: for target in tweet['entities']['user_mentions']: addr = "https://twitter.com/" + target['screen_name'] try: t = RemoteInteraction.objects.get(type='microblogpost', incoming=False, address=addr, time=dt) except: t = RemoteInteraction(type='microblogpost', incoming=False, address=addr, time=dt, message=tweet['full_text']) t.save()
def get_api(): return twitter.Api( consumer_key=settings.TWITTER_INTERNAL_CONSUMER_KEY, consumer_secret=settings.TWITTER_INTERNAL_CONSUMER_SECRET, access_token_key=settings.TWITTER_INTERNAL_ACCESS_TOKEN, access_token_secret=settings.TWITTER_INTERNAL_ACCESS_SECRET)
import re import tweepy import datetime import json import os from pattern.en import sentiment import datetime import sys, twitter, operator from dateutil.parser import parse api = twitter.Api(consumer_key='GHzCdYMAs2fy1VjsGcP5rwYiG', consumer_secret='aT3Ti5OFVZZSDtu4Ymp1qMbWZ31TaJFtULLSFyo6xYXSS1gKu7', access_token_key='2784122806-LfJbvTHuS5g2cK7mUTUfKIzLlSWt1mqXq7sQYxL', access_token_secret='eIqqhDzhDNe9uTeKmzRBcExFI7ALa0MYFx7ufv1XF7Xkl') ''' changer ex2 mettre dans des fichier passer fichier aux foncction en dessous ''' def rest_query_for_M(): output_folder_date = 'data/{0}'.format(datetime.datetime.now().strftime('%Y_%m_%d')) if not os.path.exists(output_folder_date):
import os import twitter from markov import main TWITTER_CONSUMER_KEY = os.environ["TWITTER_CONSUMER_KEY"] TWITTER_CONSUMER_SECRET = os.environ["TWITTER_CONSUMER_SECRET"] TWITTER_ACCESS_TOKEN = os.environ["TWITTER_ACCESS_TOKEN"] TWITTER_ACCESS_TOKEN_SECRET = os.environ["TWITTER_ACCESS_TOKEN_SECRET"] api = twitter.Api( consumer_key=TWITTER_CONSUMER_KEY, consumer_secret=TWITTER_CONSUMER_SECRET, access_token_key=TWITTER_ACCESS_TOKEN, access_token_secret=TWITTER_ACCESS_TOKEN_SECRET ) text = main("markov_waka.txt","markov_seagulls.txt") status = api.PostUpdate(text)
parser.add_argument('--input', required=True) TWITTER_CREDS = '.twitter_credentials.conf' if not os.path.exists(TWITTER_CREDS): raise OSError('Credentials File Not Found') with open(TWITTER_CREDS) as f: credentials = json.load(f) for key, value in credentials.items(): if len(value) == 0: raise Exception(f'Missing {key} in {TWITTER_CREDS}') api = twitter.Api(**credentials, sleep_on_rate_limit=True) args = parser.parse_args() input_file_path = args.input assert args.input.endswith('.txt') output_file_path = args.input.replace('.txt', '.tweets.tsv') with open(input_file_path) as in_file: tids = [line.strip() for line in in_file.readlines()] cached_tids = [] if os.path.exists(output_file_path): with open(output_file_path) as out_file:
import twitter api = twitter.Api( consumer_key='S0qxTno0fWuYCc175lN0cFDfc', consumer_secret='Hv5IBt1cCeaxWtRyjCilCmLGIUUVDhP3WWDBTfpzuh2xuwP1gk', access_token_key='88917640-oZW6BpeJ7wHMVjPa8o2qquGcN9fxW7985Z4XlxVcO', access_token_secret='Z7sbrHS0WPaTuW6XN4PDsEEViEf67sksh5URKidildgR6') # print(api.VerifyCredentials()) tweets = api.GetUserTimeline(screen_name='azhryarliansyah', count=10) for tweet in tweets: print(tweet)
import os import json import boto3 import twitter session = boto3.session.Session() sns = session.client('sns') sm = session.client('secretsmanager') eb = session.client('events') twitter_secret = json.loads( sm.get_secret_value(SecretId=os.environ['twitter_secret'])['SecretString']) api = twitter.Api(consumer_key=twitter_secret['consumer_key'], consumer_secret=twitter_secret['consumer_secret'], access_token_key=twitter_secret['access_token_key'], access_token_secret=twitter_secret['access_token_secret']) res = api.VerifyCredentials() user_id = str(res.id) def handler(event, context): print(json.dumps(event)) result = {"statusCode": 200} try: # an exception will be thrown if the key doesn't exit. easier to ask for forgiveness than permission if event["requestContext"]['httpMethod'] == "POST": # Queue up each tweet for processing
def authenticate(self): self.api = twitter.Api( consumer_key=os.getenv('consumer_key'), consumer_secret=os.getenv('consumer_secret'), access_token_key=os.getenv('access_token_key'), access_token_secret=os.getenv('access_token_secret'))
def getTimeLine(target): apiTwitter = twitter.Api( consumer_key="cRz70QuhNCGvFMlFHy3ARekMY", consumer_secret="WBdhkig3nZ5DTFZS0UKN0k2HnmwgbQ39xQRN6kWzeE2DfvYztg", access_token_key="201832916-lLrZ1Qw4D5zQZii0k3RgOxuY0ymnyJfPkQSXu1sc", access_token_secret="YLKNQfqIfgN9PK8IwYBd3TsSI3fkl1pfXgUkM3aP9Xgl8") timeline = apiTwitter.GetUserTimeline(screen_name=target) print("\nStatus:", timeline[0]) print("\nFriends:") accountFriends = [ account.name for account in apiTwitter.GetFriends(screen_name=target) ] for friend in accountFriends: print(friend.encode('ascii', 'ignore').decode('utf-8')) print("\nTweets: ") query = apiTwitter.GetSearch("#" + target, count=100) twitter_results = [] for result in query: tweet = {} print("Tweet: %s " % (result.text.encode('ascii', 'ignore').decode('utf-8'))) tweet['text'] = result.text.encode('ascii', 'ignore').decode('utf-8') print("Creation date: %s " % (result.created_at)) tweet['date'] = result.created_at.encode('ascii', 'ignore').decode('utf-8') print("Favs count: %d" % (result.favorite_count)) tweet['favorite_count'] = result.favorite_count print("Language: %s" % (result.lang)) tweet['lang'] = result.lang.encode('ascii', 'ignore').decode('utf-8') print("Retweets count: %d" % (result.retweet_count)) tweet['retweet_count'] = result.retweet_count print("Account: %s" % (result.user.screen_name)) tweet['account'] = result.user.screen_name.encode( 'ascii', 'ignore').decode('utf-8') print("\n") twitter_results.append(tweet) connection = sqlite3.connect('db.sqlite3') print("Database db.sqlite3 created succesfully") cursor = connection.cursor() connection.execute( "create table if not exists TwitterMessages(id integer primary key autoincrement, message varchar(140), account varchar(20),favs integer,retweets integer,langTweet varchar(5), dateMessages varchar (30) );" ) query = apiTwitter.GetSearch("#" + target, count=100) insert = "insert into TwitterMessages(message, dateMessages, favs, langTweet, retweets, account) values(?,?,?,?,?,?)" for result in query: cursor.execute( insert, (result.text, result.created_at, result.favorite_count, result.lang, result.retweet_count, result.user.screen_name)) connection.commit() outfile = open('twitter.json', 'wb') with open('twitter.json', 'w') as file: for twitter_result in twitter_results: json.dump(twitter_result, file, ensure_ascii=False, indent=4) with open('twitter.csv', 'w') as csvfile: twitter_writer = csv.writer(csvfile) for result in twitter_results: twitter_writer.writerow([ str(result['text']), str(result['date']), str(result['favorite_count']), str(result['lang']), str(result['retweet_count']) ])
print("Gathering wholesome content...") try: content = [] with open(file_path(config.WHOLESOME_CONTENT), "r") as f: content = f.read().splitlines() random_tweet = random.choice(content) tweet_content = f"{random_tweet} {config.WHOLESOME_CONTENT}" print("Success.") except FileNotFoundError: print("Unable to retrieve wholesome content.") print("Shutting down.") sys.exit(1) api = twitter.Api( consumer_key=config.TWITAPI_CONSUMER_KEY, consumer_secret=config.TWITAPI_CONSUMER_SECRET, access_token_key=config.TWITAPI_TOKEN_KEY, access_token_secret=config.TWITAPI_TOKEN_SECRET, ) print("Connecting to Twitter API...") try: followers = api.GetFollowerIDs(user_id=config.TWITTER_ID) print("Success.\nUpdating follower cache...") with open(file_path(config.FOLLOWER_CACHE), "wb") as f: pickle.dump(followers, f, protocol=pickle.HIGHEST_PROTOCOL) print("Success:", len(followers), "followers.") except twitter.error.TwitterError: print("Unable to connect.") print("Getting cache...") try:
#!/usr/bin/python import sys import os import syslog import twitter,tinyurl from my_password import (p_tvdb, p_twitter) from tvnamer.utils import (FileParser,EpisodeInfo) from tvdb_api import (tvdb_error, tvdb_shownotfound, tvdb_seasonnotfound, tvdb_episodenotfound, tvdb_attributenotfound, tvdb_userabort,Tvdb) # tvdb instance tvdb_instance = Tvdb(apikey=p_tvdb.key) # specify our log file, here local0 ! syslog.openlog('torrent_ended.py', 0, syslog.LOG_LOCAL0) api = twitter.Api(consumer_key=p_twitter.consumer_key,consumer_secret=p_twitter.consumer_secret, access_token_key=p_twitter.access_token_key, access_token_secret=p_twitter.access_token_secret) # Parse a string to find a tvshow using tvnamer # Return a couple (boolean,episode) def tvnamer(filename): try: episode = FileParser(filename).parse() except Exception, e: return(False,"") else: if episode.seriesname is None: return(False,episode) else: return(True,episode) def checkifTV(episode):
# -*- coding: utf-8 -*- """ Created on Sat Jan 25 15:47:47 2014 @author: Feng Chen """ import twitter, sys, json reload(sys) sys.setdefaultencoding("utf-8") myApi = twitter.Api(consumer_key='PeH7lROp4ihy4QyK87FZg', \ consumer_secret='1BdUkBd9cQK6JcJPll7CkDPbfWEiOyBqqL2KKwT3Og', \ access_token_key='1683902912-j3558MXwXJ3uHIuZw8eRfolbEGrzN1zQO6UThc7', \ access_token_secret='e286LQQTtkPhzmsEMnq679m7seqH4ofTDqeArDEgtXw') def print_info(tweet): print '***************************' print 'Tweet ID: ', tweet['id'] print 'Post Time: ', tweet['created_at'] print 'User Name: ', tweet['user']['screen_name'] try: print 'Tweet Text: ', tweet['text'] except: pass def rest_query_ex1(): geo = [37.781157, -122.398720, "1mi"]
import discord from discord.ext import commands from .utils import checks import twitter import json import random configDict = json.load(open('config.json')) api = twitter.Api(consumer_key=configDict['twitter_consumer_key'], consumer_secret=configDict['twitter_consumer_secret'], access_token_key=configDict['twitter_accsess_token'], access_token_secret=configDict['twitter_accsess_secret']) rt = False replies = True STATUS_LINK = "https://twitter.com/{}/status/{}" BANNED_USER_ROLES = ['Bad Memer'] try: tweet_log = json.load(open('twit.json')) except Exception as e: tweet_log = {} class twitterCog: """Commands for twitter""" def __init__(self, bot): self.bot = bot @commands.command()
f = open(File, 'r') List_from_file=list() for line in f: List_from_file = json.loads(line) f.close() return(List_from_file) def WriteNewList(Input, File): # Removes anything already there! with open(File, 'w+') as f: f.write(json.dumps(Input)) if __name__ == "__main__": api = twitter.Api( CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, tweet_mode='extended' # , sleep_on_rate_limit=True #Fixed with kludge instead, since this fails. ) api.InitializeRateLimit() # VSN_Memberlist = get_followers(api, "WHO_VSN") # For Reference # print(VSN_Memberlist) #file = open('Updating_User_List_Retrieved_Followers.json', 'w+') #file.close() List_To_Get_Followers = GetListFile('Updating_Pulled_Exclude_IDs.json') #print(List_To_Get_Followers) #Check That List against Retreived Follower List Updating_User_List_Retreived_Followers = GetListFile('Updating_User_List_Retrieved_Followers.json')
import twitter import csv api = twitter.Api(consumer_key='XxX', consumer_secret='XxX', access_token_key='XxX', access_token_secret='XxX') petTweets = api.GetSearch(raw_query='q="first%dog"') csvFile = open('FirstPet.csv', 'a') csvWriter = csv.writer(csvFile) for tweet in petTweets: csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')]) print(tweet.created_at, tweet.text) csvFile.close()
return text server = 'your_imap_server' username = '******' password = '******' M = imaplib.IMAP4_SSL(server) M.login(username, password) try: M.select('Chumby') typ, data = M.search(None, 'UNSEEN') if len(data[0].split()) > 0: api = twitter.Api(consumer_key='consumer_key', consumer_secret='consumer_secret', access_token_key='access_token_key', access_token_secret='access_token_secret') for num in data[0].split(): typ, msg_data = M.fetch(num, '(BODY[TEXT])') msg = bitify_urls(msg_data[0][1].replace('\r', '').replace('\n', '')) if len(msg) < 140: status = api.PostUpdate(msg) #else: #too long! handle it finally: M.close() M.logout() sys.exit
import xlwt from django.http import Http404 # Create your views here. from django.contrib.auth.models import User from django.http import HttpResponse from django.template import loader MAX_FETCH = 10 YOUR_API_KEY = 'AIzaSyAutyhulLRnlnWms5bEQVys3e0kQPO5Fo8' google_places = GooglePlaces(YOUR_API_KEY) api = twitter.Api( consumer_key='jOwOxaedw3LF65HKDeHVjeFqK', consumer_secret='mlcejDBraF0TQp47G481KZ9ZchhALi4gDIksoCKRYVQI47mfWM', access_token_key='1047290727686950913-ELqL7KEZJIqiGhw7AqJCnTMy6uuqHZ', access_token_secret='Bmj5vZdCoFPlZhUvIm3LNE4WE6mZuJoIZPhyucAwSXqHs') sites_list = list() lista_tipos = list() direction = 0 def homepage(request): return render(request, 'nearway.html') def twitter(request): return render(request, 'twitter.html')
TWITTER_SECRET = os.environ["TWITTER_SECRET"] except KeyError: TWITTER_SECRET = input("Secret: ") try: TWITTER_TOKEN = os.environ["TWITTER_TOKEN"] except KeyError: TWITTER_TOKEN = input("Token: ") try: TWITTER_TOKEN_SECRET = os.environ["TWITTER_TOKEN_SECRET"] except KeyError: TWITTER_TOKEN_SECRET = input("Token secret: ") api = twitter.Api( consumer_key=TWITTER_KEY, consumer_secret=TWITTER_SECRET, access_token_key=TWITTER_TOKEN, access_token_secret=TWITTER_TOKEN_SECRET, sleep_on_rate_limit=True, tweet_mode="extended", ) def wrap(s: str) -> str: """Wraps over multiple paragraphs correctly since `textwrap` only works on one paragraph at a time.""" paras = [p for p in s.split("\n\n") if p] wrapped = [textwrap.fill(p) for p in paras] return "\n\n".join(wrapped) def indent(s: str, prefix: str, predicate=str.strip) -> str: """Adds 'prefix' to the beginning of selected lines in 's'.
import twitter import json consumer_key = '' # deleted for security consumer_secret = '' # deleted for security access_token_key = '' # deleted for security access_token_secret = '' # deleted for security api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token_key, access_token_secret=access_token_secret) # San Francisco coordinates latlong = ["-122.75,36.8,-121.75,37.8"] f = open('./twitter_streaming_data.json', 'w') for tweet in api.GetStreamFilter(locations=latlong): f.write(json.dumps(tweet)) f.write('\n')
################################################## # This sets your Twitter Developer API credentials. # It imports the keys from 'keys.py', which is not included in the repository. # The keys are in this format: # # twitter = { # "consumer_key": "YOUR KEY HERE", # "consumer_secret": "YOUR KEY HERE", # "access_token_key": "YOUR KEY HERE", # "access_token_secret": "YOUR KEY HERE" # } api = twitter.Api( consumer_key = keys.twitter["consumer_key"], consumer_secret = keys.twitter["consumer_secret"], access_token_key = keys.twitter["access_token_key"], access_token_secret = keys.twitter["access_token_secret"], tweet_mode= 'extended' # Include this or tweets will be truncated ) ########################## ## IMPORT FONTS FOR USE ## ########################## # ImageFont.truetype accepts two arguments, (1, 2): # 1. "path/to/font" - where path/to/font is the path to the .ttf or .otf file # 2. font size - as an integer ##### YOU WILL NEED TO CHANGE THESE FONTS TO MATCH FONTS YOU CHOOSE ##### I HAVE USED A COMMERCIAL FONT ON MY PI, LOCALLY, SO CAN'T UPLOAD THAT
# Can maybe remove these imports import nltk import json import numpy as np from nltk.corpus import stopwords from pymongo import MongoClient client = MongoClient() db = client.test_database # Use Twitter API to get all tweets from a specific handle api = twitter.Api( consumer_key='uJGBbVHC8Ph8Qe2HFIxO6v7bX', consumer_secret='78NZzYNcbrHkU2wGKnmbooj0nbUXq3e5Ot9ofpgsPJm2varhiZ', access_token_key='869585426520170500-CgymaP0a37Y0cU5iSAIVa1XY9B7ruap', access_token_secret='1bzkszzLcnsaOw2mYsC8p9Qt5f2nKkcgBBxXbKyOg7azg') def fetch_tweets(from_handle=None, to_handle=None, keywords=None, filter_replies=True, reply_id=None): # Function to retrieve Tweets for sent to/from a specific Twitter handle and/or that mention a specific keyword # If the tweets are already in the Tweet database, return null if check_cache(from_handle): # collection = db[from_handle]
import twitter import csv import re import nltk import oauthlib api = twitter.Api(consumer_key='GwpuXi1ZMyc0ATSb3FEPaTyOU', consumer_secret='0Y1jaPrDOa0uGsxQc4DSDphRWPPYCtVZ0TtvgZorAvzywIZtXJ', access_token_key='220846580-ZUElx1lLAd5XRxrL9hYVG6CBkbjLUl3ftvCGIMqE', access_token_secret='WEFkSeH59z92ptB76tGKnh8l6mMKmWN1fVKqV6dYCuc77') # # with open('../untitled5/username.csv') as f: # reader = csv.DictReader(f) # read rows into a dictionary format # for row in reader: #for items in l: t = api.GetUserTimeline(screen_name="p", count=1000) f = open('test.txt','w') tweets = [i.AsDict() for i in t] for t in tweets: # print(t['id'], t['text']) # print(t['text']) f.write(t['text']) f.write('\n') f.close() #c= []
def _process_tweet(tweet): """ Receives a Tweet from the Search API and processes it """ text = tweet.full_text.replace('\n', ' ') # Replaced with the created_at_in_seconds attribute # timestamp = _parse_date(tweet.created_at) is_retweet = True if text.startswith('RT') else False try: city = tweet.place['name'] country = tweet.place['country'] except TypeError: city = None country = None tweet_instance = Tweet(tweet.created_at, tweet.created_at_in_seconds, tweet.id, tweet.full_text, tweet.user.screen_name, tweet.user.id, tweet.user.followers_count, tweet.favorite_count, tweet.retweet_count, is_retweet, city, country) return tweet_instance if __name__ == '__main__': api = twitter.Api(*api_key, sleep_on_rate_limit=True, tweet_mode='extended') main()