Esempio n. 1
0
def post_entity_tweet(
        view_set_obj: Union[ActionViewSet, QuoteViewSet]) -> None:
    """Função que posta um tweet de uma entidade (ação ou declaração).

    Args:
        view_set_obj (Union[ActionViewSet, QuoteViewSet]): O ViewSet da entidade.
    """
    api = TwitterApi(
        consumer_key=settings.TWITTER_API_KEY,
        consumer_secret=settings.TWITTER_API_SECRET_KEY,
        access_token_key=settings.TWITTER_API_TOKEN,
        access_token_secret=settings.TWITTER_API_SECRET_TOKEN,
    )

    entity_name = view_set_obj.__class__.__name__.split("ViewSet")[0].lower()
    infos = _get_random_entity(view_set_obj=view_set_obj)
    if isinstance(view_set_obj, QuoteViewSet):
        infos["description"] = f'"{infos["description"]}"'

    try:
        api.PostUpdate(status=(
            f"{infos['description']}\n\nMais informações: "
            f"http://bolsonaro-api.herokuapp.com/{entity_name}s/{infos['id']}/"
        ))
        logger.info("%s tweet postado com sucesso. ID da entidade: %s",
                    entity_name, infos["id"])
    except TwitterError as error:
        logger.error("Erro ao postar no twitter: %s", error.message)
Esempio n. 2
0
class Tweet():
    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()))

    def publish(self, message, nb_try=0):
        """ Just tweet
        """
        try:
            status = self.api.PostUpdate(message)
        except TwitterError as e:
            # duplicate message error...
            # let's try to add some random data at the end
            if e[0][0]['code'] == 187:
                if nb_try == 0:
                    message_addon = "Enjoy."
                elif nb_try == 1:
                    message_addon = "Have fun."
                elif nb_try == 2:
                    message_addon = ":)"
                elif nb_try == 3:
                    message_addon = ";)"
                elif nb_try == 4:
                    message_addon = ":D"
                else:
                    raise Exception(
                        "Too much duplicates for this message (3)....")
                new_message = "{0}. {1}".format(message, message_addon)
                self.publish(new_message, nb_try + 1)
        except:
            print("Unable to tweet : {0}".format(traceback.format_exc()))
Esempio n. 3
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)
Esempio n. 4
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)
Esempio n. 5
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()
Esempio n. 6
0
 def get_official(cls) -> '_ApiOfficial':
     api = TwitterApi(consumer_key=Config.CONSUMER_KEY,
                      consumer_secret=Config.CONSUMER_SECRET,
                      access_token_key=Config.ACCESS_TOKEN,
                      access_token_secret=Config.ACCESS_TOKEN_SECRET)
     api.VerifyCredentials()
     return _ApiOfficial(api)
Esempio n. 7
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
    })
Esempio n. 8
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
Esempio n. 10
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)
Esempio n. 11
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)
Esempio n. 12
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)
Esempio n. 13
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()))
Esempio n. 14
0
 def __init__(self, consumer_key, consumer_secret, access_token=None):
     if access_token:
         Api.__init__(self, access_token.key, access_token.secret)
     else:
         Api.__init__(self)
     self._Consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self._access_token = access_token
Esempio n. 15
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)
Esempio n. 16
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
Esempio n. 17
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)
Esempio n. 18
0
 def __init__(self, consumer_key, consumer_secret, access_token=None):
     if access_token:
         Api.__init__(self,access_token.key, access_token.secret)
     else:
         Api.__init__(self)
     self._Consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self._access_token = access_token
Esempio n. 19
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"])
Esempio n. 20
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'],
     )
Esempio n. 21
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
Esempio n. 22
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()
Esempio n. 23
0
 def __init__(self, consumer_key, consumer_secret, access_token=None):
     if access_token:
         Api.__init__(self,access_token.key, access_token.secret)
         #Api.__init__(self, '51630838-bcRhEqm8IYpvi4xoK0LNomItrdV7xMY1mAZA4Xus8', 'T4HiqriU7MbPqKwSBmC6EeP7SAqSMpCMGssbgcn210')
     else:
         Api.__init__(self)
     self._Consumer = oauth.OAuthConsumer(consumer_key, consumer_secret)
     self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
     self._access_token = access_token
Esempio n. 24
0
class Main(Task):

    defaults = {
        'consumer_key': None,
        'consumer_secret': None,
        'access_token_key': None,
        'access_token_secret': None,
        'disable_cache': True,
        'output': 'ALL',
        'update_freq': 45,
        'tweet_format':
        u'>> tweet from {tweet.user.screen_name}: {tweet.text_clean} <<',
        'err_announce': True,
        'err_announce_freq': timedelta(hours=8).total_seconds(),
        'soft_limit': 10,
    }

    _setting_prefix = 'TWITTER_'

    log = property(lambda s: s.madcow.log)

    def __new__(cls, *args, **opts):
        obj = super(Main, cls).__new__(cls, *args, **opts)
        obj.ready = False
        return obj

    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)
        else:
Esempio n. 25
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 = {}
Esempio n. 26
0
 def __init__(self, consumer_key, consumer_secret, 
              token=None, token_secret=None, verified=False):
 	if token and token_secret:
 		token = oauth.Token(token, token_secret)
 	else:
         token = None
     Api.__init__(self, verified=verified)
     self._Consumer = oauth.Consumer(consumer_key, consumer_secret)
     self._signature_method = oauth.SignatureMethod_HMAC_SHA1()
     self._access_token = token 
Esempio n. 27
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)
Esempio n. 28
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'))
Esempio n. 29
0
 def test_fetch_resource(self):
     api = Api(consumer_key="ckey", consumer_secret="csecret", 
         access_token_key="akey", access_token_secret="asecret")
     self.m.StubOutWithMock(api, "_FetchUrl")
     
     json_blob = json.dumps({})
     api._FetchUrl(IgnoreArg()).AndReturn(json_blob)
     
     self.m.ReplayAll()
     api.FetchResource("/trends/current.json")
     self.m.VerifyAll()
Esempio n. 30
0
 def test_retweet(self):
     api = Api(consumer_key="ckey", consumer_secret="csecret", 
         access_token_key="akey", access_token_secret="asecret")
     self.m.StubOutWithMock(api, "_FetchUrl")
     
     json_blob = json.dumps({})
     api._FetchUrl(IgnoreArg(), post_data=IgnoreArg()).AndReturn(json_blob)
     
     self.m.ReplayAll()
     api.PostRetweet(1)
     self.m.VerifyAll()
Esempio n. 31
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
Esempio n. 32
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
Esempio n. 33
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))
Esempio n. 34
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()