def handle_plot(tweet): """ Gets name of user who tweeted the COMMAND - Generates word cloud - Sends out tweet @param tweet - The tweet object that tweeted the COMMAND """ twitter = Twitter(tweet['user']['screen_name']) tweets = twitter.get_last_month_tweets_for_user() # Make sure the user tweeted the previous month if len(tweets) == 0: return words = twitter.get_words(tweets) generate_word_cloud(words) user = tweets[0]['user'] month = tweets[0]['created_at'].strftime('%B') tweet_text = f""" @{user} here are the most common words you tweeted for the month of {month}. #visualization #wordcloud #automation #AWS #Lambda #{month} """ twitter.send_tweet(tweet_text, IMG_PATH) os.remove(IMG_PATH)
def tweet_data(config, parsed_string): twitter_credentials = config['twitter'] twitter_session = Twitter() twitter_session.login(twitter_credentials['username'], twitter_credentials['password']) num_tweets = len(parsed_string) count = 1 for tweet in parsed_string: print("sending tweet {}/{}".format(count, num_tweets)) twitter_session.tweet(tweet) count = count + 1
def get_my_mentions(): """ Gets my timeline for the last minute and checks for tweets that match the COMMAND """ twitter = Twitter('jabernall24') tweets = twitter.get_timeline() one_minutes_ago = datetime.now(timezone.utc) - timedelta(minutes=1) tweets = list(filter(lambda x: parse(x['created_at']) > one_minutes_ago, tweets)) for tweet in tweets: if tweet['full_text'].lower() == COMMAND: handle_plot(tweet)
def fillDB(self): print("Start fill DB...") # Fill price history of stocks pandasDatareder = PandasDatareader.PandasDatareder() print("Price history was filled Successfully.") # Fill Tweets from Twitter twitter = Twitter.Twitter() print("Tweets was filled Successfully.") # Analyze Tweets and fill watson = Watson.Watson() print("Analyzed tweets was filled Successfully.") print("Adding new data to DB is finished and will resume tomorrow")
def getTwitterImages(): twitter = Twitter(TWITTER_USER_ID) dropbox = Dropbox(USER_NAME, 'twitter') xml = Xml(TWITTER_USER_ID, 'twitter') xml.createXmlFile() dropbox.makeDropboxFolder() timeline = twitter.getTimeLine() url_list = [] for tweet in timeline: img_url = twitter.getMediaUrls(tweet) if img_url is not None: url_list.extend(img_url) not_download_url_list = xml.compareXmlAndWeb(url_list) for url in not_download_url_list: path = twitter.downloadImage(url) dropbox.uploadPicture(path) xml.insertPicUrl(url) os.remove(path)
def __init__(self,config=None): ''' Constructor ''' if config==None: with open('apiconfigs.txt', 'rb') as fp: config = json.load(fp) self.twitter=Twitter(config["twitter"]) self.facebook=Facebook(config["facebook"]) self.twitterMessage=config["twitter"]["message"] self.facebookMessage=config["facebook"]["message"] #self.outgoingPath=os.path.join(os.getcwd()+"/outgoing/") self.outgoingPath="/tmp/photobooth/outgoing/" self.scheduler=sched.scheduler(time.time,time.sleep) self.scheduler.enter(2,1,self.upload,()) self.uploadThread = threading.Thread(target=self.scheduler.run) self.uploadThread.start()
if platform.system() == 'Windows': CHROMEDRIVER_PATH = "./chromedriver.exe" else: CHROMEDRIVER_PATH = "./chromedriver" self.driver = webdriver.Chrome(CHROMEDRIVER_PATH) self.driver.get(LOGIN_URL) elem = self.driver.find_element_by_css_selector('#AdminUsername') elem.send_keys(LOGIN_ID) elem = self.driver.find_element_by_css_selector('#AdminPassword') elem.send_keys(LOGIN_PASS) elem = self.driver.find_element_by_css_selector( '#AdminAdminIndexForm > fieldset > input.btn.btn-lg.btn-success.btn-block' ) elem.click() def twitterLogin(self): self.driver.get(OAUTH_SITE_URL) elem = self.driver.find_element_by_css_selector('#allow') elem.click() if __name__ == '__main__': try: driver = Twitter(twitter_id=TWITTER_ID, twitter_pass=TWITTER_PASS, twitter_email=TWITTER_EMAIL).getDriver() except Exception: driver = webdriver.Chrome() sl = SocialLogin(driver=driver, app_ip='36.55.241.31') sl.twitterLogin()
@author: Carl """ from Stocks import Stocks from Learner import Learner from Market import Market from Twitter import Twitter import datetime start = datetime.date(2010, 1, 1) end = datetime.date(2017, 3, 31) stocks = Stocks(start, end, ['GOOG', 'AAPL', 'SPY']) learner = Learner(stocks) market = Market(stocks, 1000000, 1) twitter = Twitter('./PickledTweets') ticker = stocks.get_tickers()[0] features = [ feature for feature in stocks.get_features() if feature not in ['Open', 'High', 'Low', 'Close'] ] target = 'Daily Log Return Direction' test_size = 0.1 scale_data = True learner.prepare_data(ticker, features, target, test_size, scale_data) print("---Classifiers---") learner.train_classifiers() target = 'Daily Log Return'
def __init__(self, lock, logger): self.twitter = Twitter(logger) translate = Translate(logger) self.paper = Paper(logger, translate) self.lock = lock self.logger = logger
from Twitter import Twitter from Analysis import Analysis twitter = Twitter() analysis = Analysis() analysis.load_saved() running = True print("Welcome to SentAlysis!\n") while running: user_option = input(""" 1. Enter text to be analysed 2. Provide a text file to analyse 3. Search Twitter and retrieve tweets to analyse 4. Load previously saved report 5. Quit What would you like to do? (Enter 1, 2, 3, 4 or 5) """) if user_option == '5': running = False break elif user_option == '4': analysis.view_saved()
auth = tweepy.OAuthHandler(keys.consumer_key, keys.consumer_secret) auth.set_access_token(keys.access_token, keys.access_token_secret) api = tweepy.API(auth) menu = Menu() menu.blue_world() usuario = menu.log_menu() while not usuario: print("Check that you put a screen name") usuario = menu.log_menu() user = api.get_user(usuario) tw = Twitter(user, api) menu.welcome_message() menu.print_main_menu() menu.set_main_menu_opt() while menu.option != -1: if menu.option == 0: num_opt = 3 menu.print_user_menu() menu.set_submenu_opt(num_opt-1) while menu.suboption_menu != -1: if menu.suboption_menu == 0: print("More mentioned users by "+user.screen_name)
from Twitter import Twitter import pprint consumer_key = 'xrY6V4Ues00o9jr5mdLlto6uJ' consumer_secret = 'oscjnGiRUOrQM6wrxLwOoBZ2dvmBN9FJjkTmGZHaXViYlla6EM' token_key = '307586034-sP38XqIK6d2PhNosXXBLfbNvUWUIywMCRm2g8R9v' token_secret = 'BbIwJPXN7rGEmQDc2f5Ufueo76lDChlJ6INrLgc9g1Fxy' twitter = Twitter(consumer_key, consumer_secret, token_key, token_secret) try: pesquisa = Twitter.search(twitter, 'globo', 'pt') #pprint.pprint(pesquisa) for resultado in pesquisa: pprint.pprint('User: '******'user']['screen_name']) print() pprint.pprint('Tweet: ' + resultado['text']) except Exception as Error: print('Houve um erro: ', Error) ''' try: resp = twitter.tweet('PostIt') except Exception as Error: print('Houve um erro: ', Error) '''
from Twitter import Twitter if __name__ == '__main__': f = open("dictionaries/insultos.txt", "r") paraulesclau = f.readlines() f.close() f = open("dictionaries/topics.txt", "r") paraulesclau += f.readlines() f.close() index = 0 for p in paraulesclau: paraulesclau[index] = p[:-1].lower() index += 1 # print(paraulesclau) #inicialitzem twitter Twitter(paraulesclau, 'es')
'page_post': '1', "groupe_post": '1', "gropes_links": 'link1, link2, link3', 'priority': "", } if json['id'] == "fb": FB = Facebook(json['login'], json['pass'], json['text'], json['link'], json['datetime'], json['page_post'], json['groupe_post'], json['title'], json['image_link'], json['hashtags'], json['gropes_links'], json["priority"]) FB.post() print(FB.get_bugrep()) if json['id'] == "tw": TW = Twitter(json['login'], json['pass'], json['text'], json['link'], json['datetime'], json['page_post'], json['groupe_post'], json['title'], json['image_link'], json['hashtags'], json['gropes_links'], json['priority']) TW.post() print(TW.get_bugrep()) if json['id'] == "vk": VK = Vkontakte(json['login'], json['pass'], json['text'], json['link'], json['datetime'], json['page_post'], json['groupe_post'], json['title'], json['image_link'], json['hashtags'], json['gropes_links'], json["priority"]) VK.post() print(VK.get_bugrep()) if json['id'] == "ok": OK = Odnoklassniki(json['login'], json['pass'], json['text'], json['link'], json['datetime'], json['page_post'], json['groupe_post'], json['title'], json['image_link'], json['hashtags'], json['gropes_links'],
from Twitter import Twitter if __name__ == '__main__': f = open("dictionaries/englishInsults.txt", "r") paraulesclau = f.readlines() f.close() f = open("dictionaries/topics.txt", "r") paraulesclau += f.readlines() f.close() index = 0 paraulesEng = [] for p in paraulesclau: if index % 4 == 0: paraulesEng.append(p[:-1].lower()) index += 1 # print(len(paraulesEng)) # print(paraulesEng) #inicialitzem twitter Twitter(paraulesEng, 'en')
def getDaveTweet(): twitter = Twitter(); return twitter.getDaveTweet();
#Main Prog Loop loops = 0 constant_empty_rgb_val = 0 while (True): if (loops < 2): if (loops == 0): print("Calibrating, please ensure pot is FULL,") raw_input("Press ENTER when pot is FULL...") constant_empty_rgb_val += getAVGcoffee(4) else: constant_empty_rgb_val += getAVGcoffee(5) constant_empty_rgb_val /= 2 else: print("Checking for coffee... ") currentCoffeeLevel = getAVGcoffee(4) percentDiff = (abs(constant_empty_rgb_val - currentCoffeeLevel) / float(constant_empty_rgb_val)) * 100.0 onlineCoffee.updateCoffeeSite(percentDiff < 11) print("RGB val of pot is: " + str(currentCoffeeLevel)) print( "There is approximately {}% coffee in the pot".format(percentDiff)) if (loops % 10 == 0): t = Twitter() if (currentCoffeeLevel == 100): t.tweet(True) else: t.tweet(False) #time.sleep(3) loops += 1
from flask_sockets import Sockets import pandas as pd from Twitter import Twitter from Analyse import Analyse import csv csv_columns = ['tweet_id', 'sentiment', 'confidence', 'username', 'created', 'location', 'text'] #define file upload folder and extensions UPLOAD_FOLDER = 'uploads/' ALLOWED_EXTENSIONS = set(['txt', 'csv']) #twitter authntication twitter = Twitter("9jZwbeNcxoRd9BMS2SrRBCNls", "Tbhae7JDjfpDRvb1XFxlCvNB4KIJXgxzOcQzkvqVRY77HDhjqR", "896463626076401664-3j9DGMoxuxFu9OjsXe2iX19R6bhWVkQ", "R0Y4YB4fYQ3CSrDz1Qfj9o4eHB09F2zIwUp1mqi9L1OnE") #print(twitter.get_timeline("zanguejoel")) # Create Flask application app = Flask(__name__) app.config.from_pyfile('config.py') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER db = SQLAlchemy(app) sockets = Sockets(app) # Define models roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))