Example #1
0
    def __init__(self):
        self.auths = [ \
            tw.OAuth( \
                consumer_key='lbXi5nIK19eQy608cKqQ0BlXt', \
                consumer_secret='xk5UN9VxS2IKVNF3nFFeXftIvO3ZUvZHq3aN5GbrLgkmJE3YME', \
                token='2776510801-rbNCNtaWsLL4wUfadYMozdXZ5kfZntor0k7smpz', \
                token_secret='l6T3CQZEHPUzqwe6OkKcQOJ2jRAi88BEGuF01hDZvPaao' ), \
            tw.OAuth( \
                consumer_key='tLQ7mqTw9efbhtZwnSlZaNPmj', \
                consumer_secret='rNbvnEc8kMaSNsJTJSKN5VcycdN8AFeWz0GyDxxk4MOIIgNZkq', \
                token='2776510801-dDb465XLDcqsMODw7y4qcSfByyrrLDf4aWVdA8G', \
                token_secret='81egIP2MqQF3aDxMsll5fX7fuDi2w0GH29o5ey39ghqJv' ), \
            tw.OAuth( \
                consumer_key='tcisclFNiZzG461eZoOIunGuG', \
                consumer_secret='XMSZjIo1KHzXTLmU8nqALc40coSBs1WDqb52rxS6OZgusbLEXU', \
                token='2776510801-EVBOEmy1rdyTf8G3FBabRUhuiv5ov7vBbfPpKuk', \
                token_secret='FT4SREVvx7VZetn2LuoEZIbjA33SfK7V9NHZFu4kDWie7' ), \
            tw.OAuth( \
                consumer_key='GlCjgzCpezgKbhBNVVAVI8UUk', \
                consumer_secret='lIcyR3tQEaBw2SCtPdeNr1neY6U2wnJNpIZLhFwRskN3FGmfhg', \
                token='2776510801-eOIS6G2BHvhDyCa07NmwYNPbzGSolDD0GD7ZXsp', \
                token_secret='eIc0VBaHTVkckC7usAjOZBtdjMpKwwh2NEvxHxIzdDdh6' ) ]

        self.tws = [ tw.Twitter(auth=self.auths[0]), \
                     tw.Twitter(auth=self.auths[1]), \
                     tw.Twitter(auth=self.auths[2]), \
                     tw.Twitter(auth=self.auths[3]) ]

        self.last_twid = 0
        self.trade_symbol = [re.compile('TRADE:'), re.compile('\$ES')]
        self.default_stop = 4.
        self.max_stop = 8.
Example #2
0
def check_twitter_auth():
    authorized = False
    if os.path.isfile(fn):  # Does the token file exist?
        tokens = twitter.oauth.read_token_file(fn)
        #print 'OAuth tokens exist, will try to authorize with them...'
        twapi = twitter.Twitter(auth=twitter.OAuth(token=tokens[0],
                                                   token_secret=tokens[1],
                                                   consumer_secret=con_secret,
                                                   consumer_key=con_key))
        try:
            result = twapi.account.verify_credentials()
            twitter_id = result['id']
            twitter_handle = result['screen_name']
            #print 'Good, we seem to be authorized for username %s with id %d' % (twitter_handle, int(twitter_id))
            authorized = twapi
        except twitter.TwitterError as e:
            logging.debug(
                "Call failed, we don't seem to be authorized with existing credentials.  Deleting..."
            )
            print e
            os.remove(fn)

    if authorized == False:  # If not authorized, do the OAuth dance
        logging.debug("Authorizing the app...")
        tokens = oauth_dance(app_name='TreeOfLight',
                             consumer_key=con_key,
                             consumer_secret=con_secret,
                             token_filename=fn)
        os.chmod(fn, stat.S_IRUSR | stat.S_IWUSR)  # Read/write, user-only
        #
        # Get an open API object for Twitter
        #
        twapi = twitter.Twitter(auth=twitter.OAuth(token=tokens[0],
                                                   token_secret=tokens[1],
                                                   consumer_secret=con_secret,
                                                   consumer_key=con_key))
        try:  # Is this going to work?
            result = twapi.account.verify_credentials()
            twitter_id = result['id']
            twitter_handle = result['screen_name']
            logging.debug(
                "Good, we seem to be authorized for username %s with id %d" %
                (twitter_handle, int(twitter_id)))
            authorized = twapi
        except twitter.TwitterError as e:  # Something bad happening, abort, abort!
            logging.debug(
                "Call failed, we don't seem to be authorized with new credentials.  Deleting..."
            )
            print e
            os.remove(fn)

    return authorized
Example #3
0
    def __init__(self, consumer_key, consumer_secret, access_token,
                 access_token_secret):

        # 初期化
        self.twitter = twitter.Twitter(auth=twitter.OAuth(
            access_token, access_token_secret, consumer_key, consumer_secret))
        self.upload = twitter.Twitter(domain='upload.twitter.com',
                                      auth=twitter.OAuth(
                                          access_token, access_token_secret,
                                          consumer_key, consumer_secret))

        # 自分の情報を取得
        self.accountinfo = self.twitter.account.verify_credentials()
Example #4
0
def do_tweet(tweet_content="Something!", use_progress_twitter_account=False):
    if tweet_content == None:
        return False
    my_twitter = tw.Twitter(auth=tw.OAuth(
        cred.TW_C3R_ACCESS_TOKEN, cred.TW_C3R_ACCESS_TOKEN_SECRET,
        cred.TW_C3R_API_KEY, cred.TW_C3R_API_SECRET))
    if use_progress_twitter_account:
        my_twitter = tw.Twitter(auth=tw.OAuth(
            cred.TW_C3P_ACCESS_TOKEN, cred.TW_C3P_ACCESS_TOKEN_SECRET,
            cred.TW_C3P_API_KEY, cred.TW_C3P_API_SECRET))
    try:
        my_twitter.statuses.update(status=tweet_content)
        return True
    except tw.TwitterHTTPError as e:
        return False
Example #5
0
def oauth_helper(request):

    oauth_verifier = request.GET.get('oauth_verifier')

    # Pick back up credentials from ipynb_oauth_dance
    oauth_token, oauth_token_secret = read_token_file(OAUTH_FILE)

    _twitter = twitter.Twitter(
        auth=twitter.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,
                                    oauth_token=oauth_token,
                                    oauth_consumer_key=CONSUMER_KEY))

    # Save tokens to TwitterUser model
    tuser, created = TwitterUser.objects.get_or_create(
            OAUTH_TOKEN = oauth_token,
            OAUTH_TOKEN_SECRET = oauth_token_secret
    )
    
    django_login(request, tuser.user)

    return HttpResponseRedirect(request.build_absolute_uri(REDIRECT_URL_AFTER_AUTH))
Example #6
0
 def __init__(self) -> None:
     # Twitter情報
     self.auth = twitter.OAuth(consumer_key=CK,
                               consumer_secret=CS,
                               token=AT,
                               token_secret=AS)
     self.api = twitter.Twitter(auth=self.auth)
Example #7
0
def tweet_it(string, credentials):
    """ Tweet string using credentials """

    global TWITTER
    if len(string) <= 0:
        return

    # Create and authorise an app with (read and) write access at:
    # https://dev.twitter.com/apps/new
    # Store credentials in YAML file
    if TWITTER is None:
        TWITTER = twitter.Twitter(auth=twitter.OAuth(
            credentials['access_token'], credentials['access_token_secret'],
            credentials['consumer_key'], credentials['consumer_secret']))

    print_it("TWEETING THIS:\n" + string)

    if args.test:
        print("(Test mode, not actually tweeting)")
    else:
        result = TWITTER.statuses.update(status=string)
        url = "http://twitter.com/" + \
            result['user']['screen_name'] + "/status/" + result['id_str']
        print("Tweeted:\n" + url)
        if not args.no_web:
            webbrowser.open(url, new=2)  # 2 = open in a new tab, if possible
def main():
    '''
    This pulls top trends from an area
    1. Import credentals
    2. connect to twitter API
    3. Pull top trends
    4. Save as html
    5. Push to s3
    '''
    credentials = yaml.load(open(os.path.expanduser('~/.ssh/twitter_api_cred.yml')))

    t = twitter.Twitter(auth=twitter.OAuth(**credentials['twitter']))

    df = pd.DataFrame(t.trends.place(_id = 1)[0]['trends']).sort_values('tweet_volume', ascending=False)

    df.iloc[:10,:].to_html('trends.html')

    conn = boto.connect_s3()

    if hasattr(ssl, '_create_unverified_context'):
        ssl._create_default_https_context = ssl._create_unverified_context

    bucket = conn.get_bucket('superawesomedataproject.com')
    file = bucket.new_key('lab_demo.html')
    file.set_contents_from_filename('trends.html', policy='public-read')
Example #9
0
def oauth_and_get_twitter():
    config_parser = configparser.ConfigParser()
    config_parser.read(CONFIG_FILE)
    if len(config_parser) == 0:
        print("ERROR: no config file loaded")
        exit(1)

    app_name = config_parser.get('Login Parameters', 'app_name')
    api_key = config_parser.get('Login Parameters', 'api_key')
    api_secret = config_parser.get('Login Parameters', 'api_secret')
    oauth_token = config_parser.get('Login Parameters',
                                    'oauth_token',
                                    fallback='')
    oauth_secret = config_parser.get('Login Parameters',
                                     'oauth_secret',
                                     fallback='')

    if oauth_token == '' or oauth_secret == '':
        oauth_token, oauth_secret = twitter.oauth_dance(
            app_name, api_key, api_secret)
        config_parser['Login Parameters']['oauth_token'] = oauth_token
        config_parser['Login Parameters']['oauth_secret'] = oauth_secret
        with open(CONFIG_FILE, 'w') as configfile:
            config_parser.write(configfile)

    t = twitter.Twitter(
        auth=twitter.OAuth(oauth_token, oauth_secret, api_key, api_secret))
    return t
Example #10
0
 def login(self):
     token, token_secret, consumer_key, consumer_secret = VowelPollBot.get_auth_tokens(
     )
     self.oauth = twitter.OAuth(token, token_secret, consumer_key,
                                consumer_secret)
     self.twitter = twitter.Twitter(auth=self.oauth)
     self.credentials = self.twitter.account.verify_credentials()
def main():

    conn, cursor = get_SQL_connection()
#    cursor.execute('DROP TABLE twitter')
    try:
       cursor.execute("CREATE TABLE twitter (id INT UNSIGNED NOT NULL AUTO_INCREMENT, at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_id CHAR(20), state CHAR(2), city VARCHAR(30), tweet VARCHAR(140), PRIMARY KEY (id))")
    except:
       print("Table already exists")
    

    token_dict = getApiKeys(sys.argv[1])

    tw_stream = twitter.TwitterStream(auth=twitter.OAuth(
                     token_dict['access_token_key'], 
                     token_dict['access_token_secret'],
                     token_dict['consumer_key'],
                     token_dict['consumer_secret']))

    tw_iterator = tw_stream.statuses.sample()


    insert_string = "INSERT INTO twitter (user_id,state,city,tweet) VALUES (%s, %s, %s, %s)"

    i = 1
    for tw in tw_iterator:
       tw_userid, tw_text, tw_lang, tw_country, tw_state, tw_city = '', '', '', '', '', ''
       try:
          tw_userid = tw['id_str']
          tw_text =  tw['text']
          tw_lang =  tw['lang']
          tw_place = tw['place']
          if tw_text and tw_place and tw_lang == 'en':
             tw_country = tw_place['country']
             if tw_country == 'United States':
                tw_fullname = tw_place['full_name']
                tw_location = tw_fullname.split()
                for s in tw_location:
                   if s in States:
                      tw_state = s
                      tw_city = tw_place['name']
                      if tw_city:
                         data = (tw_userid, tw_state, tw_city, tw_text)
                         print (i, tw_state, tw_city, tw_text)
                         cursor.execute(insert_string, data)
                         i = i + 1
                         break
       except:
          continue

       if i%10 == 0:
           cursor.close()
           conn.commit()
           conn.close()

           print("Total size of Twitter table: {0}".format(len(get_SQL_table())))

           if i==20:
               break
           else:
               conn, cursor = get_SQL_connection()
Example #12
0
    def load_modules(self):
        self.auth = twitter.OAuth(self.auth_tokens[atok], self.auth_tokens[asec], \
         self.auth_tokens[ckey], self.auth_tokens[csec])
        self.tw = twitter.Twitter(auth=self.auth, retry=True)

        self.init_rate_lim()
        self.update_relevant_cnts(2, 2)
Example #13
0
def use_defaults_and_create(CONFIG_FILE):
    """
  This functions set the default options and generates
  a simple configuration file. The default application
  key and secret is not written on the generated config
  file, this forces this function to decode the keys on
  each call to the script.
  """
    config_vars = {'magicword': '#rpitwit', 'AppName': 'RPiTwit'}

    keys = load_config(build_secret(), fromString=True)

    import twitter
    config_vars['oauth_token'],config_vars['oauth_secret'] = \
      twitter.oauth_dance(
        config_vars['AppName'],
        keys['CONSUMER_KEY'],
        keys['CONSUMER_SECRET']
      )

    twitter_handler = twitter.Twitter(auth=twitter.OAuth(
        config_vars['oauth_token'], config_vars['oauth_secret'],
        keys['CONSUMER_KEY'], keys['CONSUMER_SECRET']))

    config_vars['follow'] = find_userids(twitter_handler)

    write_config(config_vars, CONFIG_FILE)

    config_vars = dict(config_vars.items() + keys.items())

    return config_vars
Example #14
0
def tweet(tweetcontent, ping, down, up, img):
    #Twitter API connection
    my_auth = twitter.OAuth(config.TOKEN, config.TOKEN_KEY, config.CON_SEC,
                            config.CON_SEC_KEY)
    twit = twitter.Twitter(auth=my_auth)

    print("Tweeting...")

    tweet = tweetcontent
    if '%p' in tweet:
        tweet = tweet.replace('%p', str(ping))
    if '%d' in tweet:
        tweet = tweet.replace('%d', str(down))
    if '%u' in tweet:
        tweet = tweet.replace('%u', str(up))
    if '%img' in tweet:
        tweet = tweet.replace('%img', str(img))

    try:
        twit.statuses.update(status=tweet)
        print(tweet)
        print("Tweeted successfully")

    except Exception as e:
        print("Error tweeting:", e)
 def __init__(self):
     tf_conf = {k.lower(): os.environ[k] for k in API_ENV_KEY}
     oauth = tw.OAuth(**tf_conf)
     self.target_time = int(
         (datetime.now() + timedelta(hours=-24)).strftime('%s'))
     self.finder = tf.TweetNewsFinder(auth=oauth)
     self.client = tw.Twitter(auth=oauth)
    def issue_geo_query(self,
                        lat=0,
                        lon=0,
                        max_range=1000,
                        query='',
                        count=100):
        '''
        Issue geo query using a keyword, latitude and longitude with a maximum range.
        
        Parameters
        ==========
        lat = int: latitude
        lon = int: longitude
        max_range = int: max distance from lat/lon in km
        query = str: twitter search term 
        count = int: number of twitter results, maximum is 100
        
        Returns
        =======
        self.resp = response from Twitter api
        '''
        self.check_query(query, count)

        t = twitter.Twitter(
            auth=twitter.OAuth(self._token, self._token_secret,
                               self._consumer_key, self._consumer_secret))

        self.resp = t.search.tweets(q=query,
                                    geocode=f"{lat},{lon},{max_range}km",
                                    count=count)

        return self.resp
Example #17
0
def tweet(entry, conf, dryrun=False):
    """Send a tweet with the title, link and tags from an entry. The first time you
    need to authorize Acrylamid but than it works without any interaction."""

    key = "6k00FRe6w4SZfqEzzzyZVA"
    secret = "fzRfQcqQX4gcZziyLeoI5wSbnFb7GGj2oEh10hnjPUo"

    creds = os.path.expanduser('~/.twitter_oauth')
    if not os.path.exists(creds):
        twitter.oauth_dance("Acrylamid", key, secret, creds)

    oauth_token, oauth_token_secret = twitter.read_token_file(creds)
    t = twitter.Twitter(
        auth=twitter.OAuth(oauth_token, oauth_token_secret, key, secret))

    tweet = u"New Blog Entry: {0} {1} {2}".format(
        entry.title, helpers.joinurl(conf['www_root'], entry.permalink),
        ' '.join([u'#' + helpers.safeslug(tag) for tag in entry.tags]))

    print('     ', bold(blue("tweet ")), end='')
    print('\n'.join(wrap(tweet.encode('utf8'), subsequent_indent=' ' * 13)))

    if not dryrun:
        try:
            t.statuses.update(status=tweet.encode('utf8'))
        except twitter.api.TwitterError as e:
            try:
                log.warn("%s" % json.loads(e.response_data)['error'])
            except (ValueError, TypeError):
                log.warn("Twitter: something went wrong...")
Example #18
0
 def _get_api(self):
     api_key = self.bot.config["twitter-api-key"]
     api_secret = self.bot.config["twitter-api-secret"]
     access_token = self.bot.config["twitter-access-token"]
     access_secret = self.bot.config["twitter-access-secret"]
     return twitter.Twitter(auth=twitter.OAuth(
         access_token, access_secret, api_key, api_secret))
Example #19
0
 def __init__(self):
     self.client = twitter.Twitter(auth=twitter.OAuth(
         token=settings.SOCTRACK_TWITTER_TOKEN,
         token_secret=settings.SOCTRACK_TWITTER_TOKEN_SECRET,
         consumer_key=settings.SOCTRACK_TWITTER_CONSUMER_KEY,
         consumer_secret=settings.SOCTRACK_TWITTER_CONSUMER_SECRET,
     ))
def getTwitterByConfig(filename="MYCREDS.txt", path='.'):
    oauth_token, oauth_secret = twitter.read_token_file(
        os.path.join(path, filename))
    tw = twitter.Twitter(auth=twitter.OAuth(
        oauth_token, oauth_secret, APIKEYS.SPOKENTIMELINE_CONSUMERKEY,
        APIKEYS.SPOKENTIMELINE_CONSUMERSECRET))
    return tw
Example #21
0
def main():

    import argparse
    parser = argparse.ArgumentParser(
        description="Swift Navigation Tweetxample.")
    parser.add_argument("TOKEN")
    parser.add_argument("TOKEN_KEY")
    parser.add_argument("CON_SEC")
    parser.add_argument("CON_SEC_KEY")
    parser.add_argument("-p",
                        "--port",
                        default=['/dev/ttyUSB0'],
                        nargs=1,
                        help="specify the serial port to use.")
    args = parser.parse_args()

    my_auth = twitter.OAuth(args.TOKEN, args.TOKEN_KEY, args.CON_SEC,
                            args.CON_SEC_KEY)
    twit = twitter.Twitter(auth=my_auth)

    # Open a connection to Piksi using the default baud rate (1Mbaud)
    with PySerialDriver(args.port[0], baud=1000000) as driver:
        # Create a handler to connect our Piksi driver to our callbacks
        with Handler(driver.read, driver.write, verbose=True) as handler:
            try:
                for msg, metadata in handler.filter(SBP_MSG_TWEET):
                    if twit is not None:
                        twit.statuses.update(msg)
            except KeyboardInterrupt:
                pass
Example #22
0
    def __init__(self,
                 name,
                 token,
                 token_key,
                 con_secret_key,
                 con_secret,
                 defanged_only=True,
                 **kwargs):
        self.name = name
        self.api = twitter.Twitter(
            auth=twitter.OAuth(token, token_key, con_secret, con_secret_key))

        # let the user decide whether to include non-obfuscated URLs or not.
        self.include_nonobfuscated = not defanged_only

        # forward kwargs.
        # NOTE: no validation is done here, so if the config is wrong, expect bad results.
        self.kwargs = kwargs

        # decide which endpoint to use based on passed arguments.
        # if slug and owner_screen_name, use List API.
        # if screen_name or user_id, use User Timeline API.
        # if q is set, use Search API.
        # otherwise, default to mentions API.
        self.endpoint = self.api.statuses.mentions_timeline
        if kwargs.get('slug') and kwargs.get('owner_screen_name'):
            self.endpoint = self.api.lists.statuses
        elif kwargs.get('screen_name') or kwargs.get('user_id'):
            self.endpoint = self.api.statuses.user_timeline
        elif kwargs.get('q'):
            self.endpoint = self.api.search.tweets
Example #23
0
def update_twitter_list():
    from twitter import twitter_globals
    twitter_globals.POST_ACTIONS.append('create_all')
    t = twitter.Twitter(auth=twitter.OAuth(**settings.TWITTER_OAUTH),
                        domain='api.twitter.com/1.1')
    current_names = set(
        PoliticianInfo.objects.exclude(value='').filter(
            schema='twitter').values_list('value', flat=True))
    list_names = set()
    cursor = -1
    while cursor:
        result = t.lists.members(owner_screen_name=settings.TWITTER_USERNAME,
                                 slug=settings.TWITTER_LIST_NAME,
                                 cursor=cursor)
        for u in result['users']:
            list_names.add(u['screen_name'])
        cursor = result['next_cursor']
    not_in_db = (list_names - current_names)
    if not_in_db:
        logger.error("Users on list, not in DB: %r" % not_in_db)

    not_on_list = (current_names - list_names)
    t.lists.members.create_all(owner_screen_name=settings.TWITTER_USERNAME,
                               slug=settings.TWITTER_LIST_NAME,
                               screen_name=','.join(not_on_list))
    logger.warning("Users added to Twitter list: %r" % not_on_list)
Example #24
0
def post_twitter(user, twi_content, image_box, content):
    social_auth = UserSocialAuth.objects.get(user=user, provider='twitter')

    client_key = social_auth.extra_data['access_token']['oauth_token']
    client_secret = social_auth.extra_data['access_token'][
        'oauth_token_secret']

    auth = twitter.OAuth(
        consumer_key=settings.
        SOCIAL_AUTH_TWITTER_KEY,  # settings.pyに設定しているトークン
        consumer_secret=settings.
        SOCIAL_AUTH_TWITTER_SECRET,  # settings.pyに設定しているシークレットキー
        token=client_key,
        token_secret=client_secret)
    t = twitter.Twitter(auth=auth)

    t_upload = twitter.Twitter(domain='upload.twitter.com', auth=auth)

    id_imgs = []
    for image in image_box:
        id_img = t_upload.media.upload(media=image)["media_id_string"]
        id_imgs.append(id_img)

    content_all = content.flavor_text + '…\n\n' + twi_content.replace(
        ',', '\n') + '\n\nです!'
    content_all += '\n#Favorite4' + '\n' + content.hashtag + '\nurl'

    status_update = t.statuses.update(status=content_all,
                                      media_ids=",".join(id_imgs))

    return status_update
Example #25
0
	def twitter_login(self, cons_key, cons_secret, access_token, \
		access_token_secret):
		
		"""Logs in to Twitter, using the provided access keys. You can get
		these for your own Twitter account at apps.twitter.com
		
		Arguments

		cons_key		-	String of your Consumer Key (API Key)

		cons_secret		-	String of your Consumer Secret (API Secret)

		access_token	-	String of your Access Token

		access_token_secret
					-	String of your Access Token Secret
		"""
		
		# Raise an Exception if the twitter library wasn't imported
		if not IMPTWITTER:
			self._error(u'twitter_login', u"The 'twitter' library could not be imported. Check whether it is installed correctly.")
		
		# Log in to a Twitter account
		self._oauth = twitter.OAuth(access_token, access_token_secret, \
			cons_key, cons_secret)
		self._t = twitter.Twitter(auth=self._oauth)
		self._ts = twitter.TwitterStream(auth=self._oauth)
		self._loggedin = True
		
		# Get the bot's own user credentials
		self._credentials = self._t.account.verify_credentials()
Example #26
0
def post_tweet(language):
    if language == "ja":
       RSS_URL = ""
    else:
       RSS_URL = ""
    wordpress = feedparser.parse(RSS_URL)
    auth = twitter.OAuth(consumer_key=os.environ['tw_consumer_key'],
                     consumer_secret=os.environ['tw_consumer_secret'],
                     token=os.environ['tw_token'],
                     token_secret=os.environ['tw_token_secret'])

    data_bloglist = r'\temp\bloglist.csv'
    df = pd.read_csv(data_bloglist,encoding = "shift-jis", index_col=1)
    t = twitter.Twitter(auth=auth)

    for entry in wordpress.entries:
  
      published = entry.published.replace(",","").replace(" +0000","")
      objDate = datetime.strptime(published,'%a %d %b %Y %H:%M:%S')
  
      strtag = ""
      for tag in entry.tags:
          strtag = strtag + " #"+tag.term
      if language == "ja":
          strTweet = "ブログの新着記事です\nタイトル:{0}\nURL:{1}\n投稿日:{2}\n#情シス #Python {3}".format(entry.title,entry.link,str(objDate),strtag)
      else:
          strTweet = "New article\nTitle:{0}\nURL:{1}\nPosted Date:{2}\n#Python {3}".format(entry.title,entry.link,str(objDate),strtag)

      blog_list = df[df["url"] == entry.link]
      if blog_list.empty:
           df=df.append({'url' : entry.link , 'title':entry.title} , ignore_index=True)
           t.statuses.update(status=strTweet)
           print(strTweet)
           df.to_csv(data_bloglist,encoding = "shift-jis",index=False)
	def connect_twitter():
		twitter_stream = twitter.TwitterStream(auth=twitter.OAuth(
												token = "get_your_own_credentials",
												token_secret = "get_your_own_credentials",
												consumer_key = "get_your_own_credentials",
												consumer_secret = "get_your_own_credentials"))
		return twitter_stream
Example #28
0
def twitter_post(auth_token, db_event):
    t = twitter.Twitter(
        auth=twitter.OAuth(auth_token.oauth_token, auth_token.oauth_token_secret, consumer_key, consumer_secret))

    update_params = {}
    if db_event.latitude:
        update_params['lat'] = db_event.latitude
        update_params['long'] = db_event.longitude

    media = create_media_on_twitter(t, db_event)
    if media:
        update_params['media_ids'] = media['media_id']

    TWITTER_HANDLE_LENGTH = 16
    description = db_event.description
    twitter_handles = re.findall(r'\s@[A-za-z0-9_]+', description)
    twitter_handles = [x.strip() for x in twitter_handles if len(x) <= 1 + TWITTER_HANDLE_LENGTH]
    twitter_handles2 = re.findall(r'twitter\.com/([A-za-z0-9_]+)', description)
    twitter_handles2 = ['@%s' % x.strip() for x in twitter_handles2 if len(x) <= 1 + TWITTER_HANDLE_LENGTH]
    # This is the only twitter account allowed to @mention, to avoid spamming everyone...
    if auth_token.token_nickname == 'BigTwitter':
        # De-dupe these lists
        handles = list(set(twitter_handles + twitter_handles2))
    else:
        handles = []
    config = get_twitter_config(t)
    status = format_twitter_post(config, db_event, media, handles=handles)
    t.statuses.update(status=status, **update_params)
Example #29
0
def tweet_it(string, credentials):
    if len(string) <= 0:
        return

    # Create and authorise an app with (read and) write access at:
    # https://dev.twitter.com/apps/new
    # Store credentials in YAML file
    t = twitter.Twitter(auth=twitter.OAuth(
        credentials["oauth_token"],
        credentials["oauth_token_secret"],
        credentials["consumer_key"],
        credentials["consumer_secret"],
    ))

    print("TWEETING THIS:\n", string)

    if args.test:
        print("(Test mode, not actually tweeting)")
    else:
        result = t.statuses.update(
            status=string,
            lat=HELSINKI_LAT,
            long=HELSINKI_LONG,
            display_coordinates=True,
        )
        url = ("http://twitter.com/" + result["user"]["screen_name"] +
               "/status/" + result["id_str"])
        print("Tweeted:\n" + url)
        if not args.no_web:
            webbrowser.open(url, new=2)  # 2 = open in a new tab, if possible
Example #30
0
def tweet(text):
    auth = twitter.OAuth(consumer_key=os.environ['TWITTER_CONSUMER_KEY'],
                         consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'],
                         token=os.environ['TWITTER_ACCESS_TOKEN'],
                         token_secret=os.environ['TWITTER_ACCESS_SECRET'])
    t = twitter.Twitter(auth=auth)
    t.statuses.update(status=text)