Beispiel #1
0
def twittear(tweet_local_id):
    from twitter import Api
    from tw.models import Credential, Tweet
    tweet = Tweet.objects.get(id=tweet_local_id)
    if tweet.tweet_id is None:
        twitter_user = tweet.user
        user_credentials = Credential.objects.get(twitter_user=twitter_user)
        api = Api(user_credentials.consumer_key,
                  user_credentials.consumer_secret,
                  user_credentials.access_token_key,
                  user_credentials.access_token_secret)
        files = []
        if tweet.image1:
            files.append(tweet.image1.path)
        if tweet.image2:
            files.append(tweet.image2.path)
        if tweet.image3:
            files.append(tweet.image3.path)
        if tweet.image4:
            files.append(tweet.image4.path)
        result = api.PostUpdate(status=tweet.text, media=files)
        tweet.tweet_id = result.id
        tweet.pub_datetime = datetime.utcfromtimestamp(
            result.created_at_in_seconds)
        tweet.published = True
        tweet.save()
Beispiel #2
0
def pull_and_publish(
    consumer_key: str,
    consumer_secret: str,
    access_token: str,
    access_token_secret: str,
    slack_token: str,
    slack_channel: str,
    wait_time: int,
):
    """Continuously pull recent Twitter statuses and publish them to Slack."""

    twitter_api = Api(consumer_key, consumer_secret, access_token,
                      access_token_secret)

    slack_client = WebClient(slack_token)
    channel_id = _get_channel_id(slack_client, slack_channel)

    since_id = None
    while True:
        statuses = twitter_api.GetHomeTimeline(since_id=since_id)

        if statuses:
            logger.info(f"Got {len(statuses)} statuses from Twitter.")
            since_id = publish_new_statuses(channel_id, since_id,
                                            slack_channel, slack_client,
                                            statuses)
        else:
            logger.info("No new twitter statuses.")

        time.sleep(wait_time)
Beispiel #3
0
def index(request):

    # Set up Twitter API with our auth details
    api = Api(consumer_key=CONSUMER_KEY,
              consumer_secret=CONSUMER_SECRET,
              access_token_key=ACCESS_TOKEN_KEY,
              access_token_secret=ACCESS_TOKEN_SECRET)

    profile, _ = Profile.objects.get_or_create(user=request.user)
    if profile.twitter_name:  # If we had a profile and saved a twitter name, use it here or use our username
        user_id = profile.twitter_name
    else:
        user_id = request.user.username
    if request.method == "GET":
        if 'user' in request.GET:
            user_id = request.GET['user']
    twitter = api.GetUserTimeline(screen_name=user_id, count=10)
    twitter_user = api.GetUser(screen_name=user_id)
    country_list = Country.objects.values('name', 'longitude', 'latitude')
    for tweet in twitter:  # this is horribly slow atm, could speed this up if I thought about it harder.
        for country in country_list:
            if country[
                    'name'] in tweet.text:  # stupid simple search method, doesn't rank countries by relevance
                tweet.country = {
                    'name': country['name'],
                    'latitude': country['latitude'],
                    'longitude': country['longitude']
                }
                break

    return render(request, 'index.html', {
        'twitter': twitter,
        'twitter_user': twitter_user
    })
Beispiel #4
0
    def __init__(self):
        """ Get twitter configuration and create the twitter Api
        """
        ### load the json to get twitter config
        # check if the file exists
        if os.path.isfile(CONFIG_FILE):
            tmp_json = json.load(open(CONFIG_FILE))
            # test if tweeting is enabled or not....
            if not tmp_json['twitter']['enable']:
                print("We don't want to tweet!")
                return
            consumer_key = tmp_json['twitter']['consumer_key']
            consumer_secret = tmp_json['twitter']['consumer_secret']
            access_token_key = tmp_json['twitter']['access_token']
            access_token_secret = tmp_json['twitter']['access_token_secret']
        else:
            raise Exception(
                "Twitter oauth configuration : unable to open or read file '{0}')"
                .format(CONFIG_FILE))
            return

        ### Connect to twitter
        try:
            self.api = Api(consumer_key=consumer_key,
                           consumer_secret=consumer_secret,
                           access_token_key=access_token,
                           access_token_secret=access_token_secret)
            self.api.VerifyCredentials()
        except TwitterError:
            raise Exception(
                "Unable to log in the twitter account : {0}".format(
                    traceback.format_exc()))
Beispiel #5
0
    def __init__(self):

        # Create API object
        self.api = Api(consumer_key=CONSUMER_KEY,
                       consumer_secret=CONSUMER_SECRET,
                       access_token_key=ACCESS_TOKEN,
                       access_token_secret=ACCESS_TOKEN_SECRET)
Beispiel #6
0
def database():
	search_term = "bills.com"
	print search_term
	api = Api(consumer_key='uy3Utit3PhWPmM5284sh7w',
			consumer_secret='zA6ps76R3ID2oRXXdUjQ7jsPgcmXD1rPsNYVSw', 
			access_token_key='61793468-PoarjfBLEa8KxtmFvNcLwFlvSGsh03U2LyNbroXye',
			access_token_secret='qg6cEIa33rX725oVAqmN4CtIgG0fmuPeI7pb2Vjeyxs')
	results = api.GetSearch(search_term)
	tweets = []
	for r in results:
		user = r.GetUser()
		text = r.GetText()
		seconds_ago = r.GetCreatedAtInSeconds()
		hours_ago = ConvertTime(seconds_ago)
		source_url = r.GetSource()
		screenname = user.GetScreenName()
		image = user.GetProfileImageUrl()
		tweet = {"text": text, "hours_ago":hours_ago, "screenname": screenname, 
				"img": image, "view_tweet": source_url}
		tweets.append(tweet)
		#Add each tweet to database.
		t = Tweet( author= screenname, body = text, is_read = False )
		db.session.add(t)
	for t in tweets:
		print t 
	db.session.commit()
	return "Connected to db. Check db."
 def __init__(self, twitter_credentials):
     try:
         self.username = twitter_credentials["username"]
         # python-twitter
         self.api = Api(
             consumer_key=twitter_credentials["consumer_key"],
             consumer_secret=twitter_credentials["consumer_secret"],
             access_token_key=twitter_credentials["access_token"],
             access_token_secret=twitter_credentials["access_token_secret"])
         # tweepy
         auth = tweepy.OAuthHandler(twitter_credentials["consumer_key"],
                                    twitter_credentials["consumer_secret"])
         auth.set_access_token(twitter_credentials["access_token"],
                               twitter_credentials["access_token_secret"])
         self.tweepy_api = tweepy.API(auth)
     except KeyError as key_error:
         logging.critical(
             "Invalid \"twitter_credentials\" argument: {}".format(
                 key_error.args[0]))
         raise
     except TypeError as type_error:
         logging.critical(
             "Incorrect \"twitter_credentials\" argument: {}".format(
                 type_error.args[0]))
         raise
Beispiel #8
0
    def update_twitter(self, author):
        from django.conf import settings
        from meegloo.core.models import OAuthToken
        from meegloo.urlshortening.helpers import shorten
        from meegloo.social.helpers import format_tweet
        from twitter import Api

        oauth_creds = getattr(settings, 'OAUTH_CREDENTIALS').get('TWITTER')
        logger = logging.getLogger()

        api = Api(consumer_key=oauth_creds.get('CONSUMER_KEY'),
                  consumer_secret=oauth_creds.get('CONSUMER_SECRET'),
                  access_token_key=oauth_creds.get('BOT_TOKEN'),
                  access_token_secret=oauth_creds.get('BOT_SECRET'))

        try:
            username = '******' + author.oauth_tokens.get(site='twitter').username
        except OAuthToken.DoesNotExist:
            username = author.get_full_name() or author.username

        tags = self.get_twitter_tags(author)
        url = shorten(self, self.network, author)
        text = '%s - Covered by %s' % (self.name, username)
        tweet = format_tweet(text, tags, url)

        try:
            api.PostUpdate(tweet)
        except Exception, ex:
            logger.error('Unable to post tweet', exc_info=ex)
Beispiel #9
0
    def init(self):
        opts = {}
        for key, default in self.defaults.iteritems():
            setting = self._setting_prefix + key.upper()
            val = getattr(settings, setting, None)
            if val is None:
                val = default
            opts[key] = val
        x, y = tee(
            imap(
                '{}_{}'.format,
                *izip(*product(['consumer', 'access_token'],
                               ['key', 'secret']))))
        self.api = Api(**dict(izip(x, imap(opts.pop, y))))
        if opts.pop('disable_cache'):
            self.api.SetCache(None)
        self.last_error_announce = 0
        self.last_id = None
        vars(self).update(opts)

        try:
            status = self.api.VerifyCredentials()
        except TwitterError, exc:
            exc_info = sys.exc_info()
            error = APIError.from_twitter_error(exc)
            self.log.error('twitter oAuth2 failure, disabling task: {}'.format(
                error.message))
            self.unload()
            reraise(*exc_info)
Beispiel #10
0
    def update_twitter(self):
        from django.conf import settings
        from meegloo.core.models import OAuthToken
        from meegloo.urlshortening.helpers import shorten
        from meegloo.social.helpers import format_tweet
        from twitter import Api

        oauth_creds = getattr(settings, 'OAUTH_CREDENTIALS').get('TWITTER')
        logger = logging.getLogger()

        try:
            token = self.author.oauth_tokens.get(site='twitter')
        except OAuthToken.DoesNotExist:
            logger.debug('No OAuth token for %s' % self.author.username)
            return

        api = Api(consumer_key=oauth_creds.get('CONSUMER_KEY'),
                  consumer_secret=oauth_creds.get('CONSUMER_SECRET'),
                  access_token_key=token.token,
                  access_token_secret=token.secret)

        tags = self.get_twitter_tags()
        tags = ['#%s' % t for t in self.tags.values_list('slug', flat = True)] + \
         ['#%s' % t for t in tags]

        url = shorten(self, self.stream.part_of.network, self.author)
        tweet = format_tweet(self.text, tags, url)

        try:
            api.PostUpdate(tweet)
        except Exception, ex:
            logger.error('Unable to post tweet', exc_info=ex)
Beispiel #11
0
def create_session(consumer_key: str, consumer_secret: str, access_token: str,
                   access_secret: str) -> Api:
    api = Api(consumer_key=consumer_key,
              consumer_secret=consumer_secret,
              access_token_key=access_token,
              access_token_secret=access_secret)
    return api
 def __init__(self):
     self.api = Api(CONSUMER, CONSUMER_SECRET, ACCESS_TOKEN,
                    ACCESS_TOKEN_SECRET)
     self._producer = KafkaProducer(bootstrap_servers='localhost:9092',
                                    max_in_flight_requests_per_connection=5,
                                    acks='all',
                                    api_version=(0, 10),
                                    retries=100000000000)
Beispiel #13
0
 def __init__(self):
     self.api = Api(CONSUMER,
                    CONSUMER_SECRET,
                    ACCESS_TOKEN,
                    ACCESS_TOKEN_SECRET)
     self._producer = KafkaProducer(
         bootstrap_servers='localhost:9092', max_in_flight_requests_per_connection=5, acks='all',
         api_version=(0, 10), retries=100000000000, compression_type='snappy', linger_ms=20, batch_size=32*1024)
Beispiel #14
0
def _get_api():

    load_dotenv()

    return Api(consumer_key = os.getenv('app_key'),
        consumer_secret = os.getenv('app_secret'),
        access_token_key = os.getenv('oauth_token'),
        access_token_secret = os.getenv('oauth_token_secret') )
Beispiel #15
0
 def __init__(self, mention=False):
     self.api = Api(
         settings.TWITTER_CONSUMER_KEY,
         settings.TWITTER_CONSUMER_SECRET,
         settings.TWITTER_ACCESS_TOKEN,
         settings.TWITTER_ACCESS_SECRET,
     )
     self._bill = None
Beispiel #16
0
 def __init__(self):
     """
     Initializes python-twitter wrapper with the Twitter API credentials
     """
     self.api = Api(consumer_key=credentials["consumer_key"],
                    consumer_secret=credentials["consumer_secret"],
                    access_token_key=credentials["access_token_key"],
                    access_token_secret=credentials["access_token_secret"])
Beispiel #17
0
def get_tweets(screen_name, limit):
    api = Api(consumer_key=app.config['CONSUMER_KEY'],
              consumer_secret=app.config['CONSUMER_SECRET'],
              access_token_key=app.config['ACCESS_TOKEN_KEY'],
              access_token_secret=app.config['ACCESS_TOKEN_SECRET'])
    api.VerifyCredentials()
    tweets = api.GetUserTimeline(screen_name=screen_name, count=limit)
    include_tweets(screen_name, tweets)
    return database.tweets.find()
Beispiel #18
0
 def __init__(self, **kwargs):
     # Instantiate Twitter API
     # Set env variables with values from https://developer.twitter.com/apps
     self.api = Api(
         consumer_key=environ['TWITTER_CONSUMER_KEY'],
         consumer_secret=environ['TWITTER_CONSUMER_SECRET'],
         access_token_key=environ['TWITTER_ACCESS_TOKEN_KEY'],
         access_token_secret=environ['TWITTER_ACCESS_TOKEN_SECRET'],
     )
Beispiel #19
0
 def __init__(self, config, socketio):
     self.config = config
     self.api = Api(
         config["consumer_key"],
         config["consumer_secret"],
         config["access_token"],
         config["access_token_secret"]
     )
     self.socketio = socketio
Beispiel #20
0
 def __init__(self, consumer_key, consumer_secret, access_token_key,
              access_token_secret):
     self._api = Api(base_url="https://api.twitter.com/1.1",
                     consumer_key=consumer_key,
                     consumer_secret=consumer_secret,
                     access_token_key=access_token_key,
                     access_token_secret=access_token_secret)
     self.UpdateRateLimitStatus()
     self._tweets = []
     self._users = {}
Beispiel #21
0
def load_api(name, app=False):
    key = twitter_keys.get(name)
    if not key:
        raise
    api = Api(key['consumer-key'],
              key['consumer-secret'],
              key['access-token'],
              key['access-token-secret'],
              application_only_auth=app)
    return api
Beispiel #22
0
def follow(username):
    from twitter import Api
    from django.conf import settings

    api = Api(getattr(settings, 'DO_TWITTER_CONSUMER_KEY'),
              getattr(settings, 'DO_TWITTER_CONSUMER_SECRET'),
              getattr(settings, 'TWITTER_ACCESS_TOKEN_KEY'),
              getattr(settings, 'TWITTER_ACCESS_TOKEN_SECRET'))

    return api.CreateFriendship(username)
Beispiel #23
0
    def connect_api(self):
        '''
        Connects the api with the given cesidentials
        '''
        self.api = Api(consumer_key=self.consumer_key,
                       consumer_secret=self.consumer_secret,
                       access_token_key=self.access_token_key,
                       access_token_secret=self.access_token_secret)

        #Our try/catch given to us by twitter api
        self.api.VerifyCredentials()
Beispiel #24
0
def get_tweets(screen_name, limit):
    api = Api(consumer_key=app.config['CONSUMER_KEY'],
              consumer_secret=app.config['CONSUMER_SECRET'],
              access_token_key=app.config['ACCESS_TOKEN_KEY'],
              access_token_secret=app.config['ACCESS_TOKEN_SECRET'])
    api.VerifyCredentials()
    tweets = api.GetUserTimeline(screen_name=screen_name, count=limit)
    for tweet in tweets:
        tweet.url = 'https://twitter.com/{}/statuses/{}'.format(
            screen_name, tweet.id)
    return tweets
Beispiel #25
0
 def __init__(self):
     """
     Initializes python-twitter wrapper with the Twitter API credentials
     """
     self.api = Api(consumer_key=os.environ["consumer_key"],
                    consumer_secret=os.environ["consumer_secret"],
                    access_token_key=os.environ["access_token_key"],
                    access_token_secret=os.environ["access_token_secret"])
     self.redis_search_engine = Redis()
     logging.info('App name: ' +
                  self.redis_search_engine.get_string('app:name'))
Beispiel #26
0
 def _send_message(self, message, **kwargs):
     try:
         api = Api(consumer_key=CONSUMER_KEY,
                   consumer_secret=CONSUMER_SECRET,
                   access_token_key=autosubliminal.TWITTERKEY,
                   access_token_secret=autosubliminal.TWITTERSECRET)
         api.PostUpdate(text_type(message[:280]))
         return True
     except Exception:
         log.exception('%s notification failed', self.name)
         return False
Beispiel #27
0
 def test_source(self):
     if self.api is None:
         w = self.sleep_on_rate_limit
         self.api = Api(self.consumer_key,
                        self.consumer_secret,
                        self.access_token,
                        self.access_token_secret,
                        sleep_on_rate_limit=w)
     if self.api is None:
         raise Exception("Unable to connect to twitter")
     return self.api.VerifyCredentials()
Beispiel #28
0
 def save_model(self, request, obj, form, change):
     """
     Sends a tweet with the title/short_url if applicable.
     """
     super(TweetableAdminMixin, self).save_model(request, obj, form, change)
     if Api and request.POST.get("send_tweet", False):
         auth_settings = get_auth_settings()
         obj.set_short_url()
         message = truncatechars(obj, 140 - len(obj.short_url) - 1)
         api = Api(*auth_settings)
         api.PostUpdate("%s %s" % (message, obj.short_url))
Beispiel #29
0
 def __init__(self,
              consumer_key,
              consumer_secret,
              access_key,
              access_secret,
              log_level=None):
     self.log_level = log_level or self.INFO
     self.api = Api(consumer_key, consumer_secret, access_key,
                    access_secret)
     if not self.api.VerifyCredentials():
         raise ValueError(
             "Could not log in to Twitter with the keys provided.")
Beispiel #30
0
def direct_message_follower(self, follower_id):
    """ Logs into api and post a direct tweet to the follower """
    api = Api(consumer_key=settings.CONSUMER_KEY,
              consumer_secret=settings.CONSUMER_SECRET,
              access_token_key=settings.ACCESS_TOKEN_KEY,
              access_token_secret=settings.ACCESS_TOKEN_SECRET)
    tweet = (
        'Time for some Java livestreams: https://www.livecoding.tv/username1, '
        'https://www.livecoding.tv/username2')

    api.PostDirectMessage(tweet, user_id=follower_id)

    return True