Esempio n. 1
0
    def get_twitter_followers(self):
        """
		how many Twitter followers an artist has right now
		"""
        client = UserClient(
            **json.load(open(f'{Artist.CRED_DIR}/twitter.json')))

        for i, rc in enumerate(self.artists, 1):

            med = rc.get('media', None)
            if med:
                tw = rc['media'].get('twitter', None)
                if tw:
                    try:
                        tw_followers_ = client.api.users.show.get(
                            screen_name=tw).data['followers_count']
                        rc.update({'twitter_followers': tw_followers_})
                    except:
                        print(f'can\'t get followers from {tw}!')

        return self
Esempio n. 2
0
def twitter():
    # your app keys
    CONSUMER_KEY = 'YOUR_CONSUMER_KEY'
    CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'
    ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'
    ACCESS_TOKEN_SECRET = 'YOUR_ACCESS_TOKEN_SECRET'
    # initialize UserClient class with your app keys
    client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                        ACCESS_TOKEN_SECRET)

    # create an infinite loop to check received messages
    while True:
        # use exception handler to manage twitter errors
        try:
            # get received direct messages
            directMsg = client.api.direct_messages.get()
            # get text of first list object (last received message)
            msg = directMsg.data[0]['text']
            # print message on the IDE console
            print "Last direct message received :", msg
            # test message to turn on the LED in a color
            if msg == "weio_red":
                digitalWrite(18, LOW)
                digitalWrite(19, HIGH)
                digitalWrite(20, HIGH)
            if msg == "weio_green":
                digitalWrite(18, HIGH)
                digitalWrite(19, LOW)
                digitalWrite(20, HIGH)
            if msg == "weio_blue":
                digitalWrite(18, HIGH)
                digitalWrite(19, HIGH)
                digitalWrite(20, LOW)
        # catch eventual errors
        except TwitterApiError, e:
            # print error on the IDE console
            print e
        # wait a minute to not exeed twitter API rate limits
        delay(60000)
Esempio n. 3
0
def twitter_war(request):
    client = UserClient('5xOlVgTTxqlDp3c9NbhDxypXC',
                        'rXFB2WgX3rLQ3S0PPYOI2b6UA3sKMwF7VZpTQA03jCasDzPOt2',
                        '2982752483-A6yeIrm7qC4QHPL3Ar0Hphvg2bZHqHAnJ62f7sr',
                        'o8qR72i1tiampZnWtlZOuZq97tyEBynNk75U9BhH5X2r3')

    twitter_names = [
        'brunoraljic', 'EnsarBavrk', "Ognjetina", "sdejan89", "_rstokic_",
        "milansusnjar_", "KnightOfRen_", "A_Popadic", "milos_brdar",
        "borisjanjanin", "deni_n88", "djovic82", "GJungic", "Gonguli88",
        "buconis", "ozegster", "mladen_vasic", "Nemanjas_Vasic", "novislavs",
        "stek993", "Tin_M_", "stasa_m"
    ]

    twitter_accounts = []

    for twitter_name in twitter_names:
        twitter_accounts.append(
            client.api.users.show.get(screen_name=twitter_name).data)

    twitter_accounts.sort(key=lambda x: x['followers_count'], reverse=True)

    return render(request, 'war.html',
                  {"twitter_accounts": twitter_accounts[:10]})
Esempio n. 4
0
 def __init__(self):
     self.client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
Esempio n. 5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import random

from birdy.twitter import UserClient
from birdy.twitter import TwitterApiError

CONSUMER_KEY = os.environ['CONSUMER_KEY']
CONSUMER_SECRET = os.environ['CONSUMER_SECRET']
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = os.environ['ACCESS_TOKEN_SECRET']
QUOTES_FILE_PATH = os.environ['QUOTES_FILE_PATH']

client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                    ACCESS_TOKEN_SECRET)

with open(QUOTES_FILE_PATH, 'r') as quotes:
    random_line = random.choice(quotes.readlines())
    while True:
        try:
            client.api.statuses.update.post(status=random_line)
        except TwitterApiError:
            continue
        else:
            break
Esempio n. 6
0
import json
#import db_init
import datetime
#from pony.orm import *
#from dateutil import parser

from birdy.twitter import UserClient
import pass_tw_2  ## twitter credentials
#import unicodedata
#from unidecode import unidecode

client = UserClient(pass_tw_2.CONSUMER_KEY, pass_tw_2.CONSUMER_SECRET,
                    pass_tw_2.ACCESS_TOKEN, pass_tw_2.ACCESS_TOKEN_SECRET)

#follow = ['8802752','9317502','14594813','790680', '2174537102', '54341363', '65473559', '17715048', '14594698', '16632084', '128372940', '354095556', '29913589']
follow = ['23941036', '21207962', '142393421']
# revista piaui = 23941036
# epocA = 21207962
# globo news = 142393421

#follow = ['790680']

for u in follow:

    u_id = u

    response = client.api.statuses.user_timeline.get(user_id=u_id,
                                                     exclude_replies=True,
                                                     include_rts=False,
                                                     count=30)
Esempio n. 7
0
"""
                    Insight Data Engineering SEA'19C
Project: Traffic Control of API source
Birdie implementation

"""
from private_twitter_authentication_config import my_system_designer_cred
from birdy.twitter import UserClient
from birdy.twitter import StreamClient
import pprint

CONSUMER_KEY = my_system_designer_cred.consumer_api_key
CONSUMER_SECRET = my_system_designer_cred.consumer_secret_api_key
ACCESS_KEY = my_system_designer_cred.access_token
ACCESS_SECRET = my_system_designer_cred.access_token_secret
client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
response = client.api.users.show.get(screen_name='twitter')
pprint.pprint(response.data)

# # DO SOME STREAMING
# client = StreamClient(CONSUMER_KEY,
#                     CONSUMER_SECRET,
#                     ACCESS_KEY,
#                     ACCESS_SECRET)
# resource = client.stream.statuses.filter.post()
Esempio n. 8
0
    def post(self):

        good = 0
        bad = 0
        customer = 'unknown'
        resp1 = 'unknown'
        artTitle = 'unknown'

        tw_instructions = """When logged into the Rainmaker Lead System, in the top right, near the red Logout button is a link to your account page.<br ><br >

                    On your account page in the left column is a Twitter Login button.  Click that and then select where you would like your articles posted.<br ><br >

                    You will get a confirmation that everything's set up.<br ><br >

                    Then please click on the Social tab and then Errors.  Go into any articles that didn't post and click the "Reset article" checkbox.<br ><br >

                    Let us know if you have any trouble.<br ><br >"""

        error_sent = []

        try:

            aa_key = self.request.get('aa_key')

            aaDoc = getDocByKey(aa_key)
            if aaDoc:
                aaDoc.twstatus = "working"
                aaDoc.put()
            else:
                err_mess = 'error_social_twitter_badkey: ' + aa_key
                logging.error(err_mess)
                return err_mess

            acctDoc = getAccountDoc(aaDoc.account_id)
            tw_access_token = acctDoc.tw_access_token

            if tw_access_token != '':

                user_message = ""
                custom_tweet = ""

                try:
                    if aaDoc.user_message != '':
                        custom_tweet = (
                            aaDoc.user_message[:114] + '.. '
                        ) if len(
                            aaDoc.user_message) > 116 else aaDoc.user_message
                except Exception as e:
                    user_message = ''

                from birdy.twitter import UserClient

                CONSUMER_KEY = "qjw7GAC8WQuuAkBQnt04KXej0"
                CONSUMER_SECRET = "3FpFoubONGhf7vR4TGffbTNzRYC1XK2CVoGZhCCLMxFmbQUFzW"
                ACCESS_TOKEN = acctDoc.tw_access_token
                ACCESS_TOKEN_SECRET = acctDoc.tw_secret

                client = UserClient(CONSUMER_KEY, CONSUMER_SECRET,
                                    ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
                if custom_tweet != "":
                    response = client.api.statuses.update.post(
                        status=custom_tweet + aaDoc.content_url)
                else:
                    response = client.api.statuses.update.post(
                        status=aaDoc.title + ": " + aaDoc.subtitle + " " +
                        aaDoc.content_url)

                resp0 = response.data

                logging.info(resp0)

                if "code" in resp0:
                    try:
                        aaDoc.twstatus_note = "Error: " + customer + json.loads(
                            resp0)['error']['message']
                    except:
                        aaDoc.twstatus_note = "Error: " + customer + resp0
                    # json.loads(resp1)['error']['message']
                    aaDoc.twstatus = "error"
                    aaDoc.put()
                    bad += 1

                    logging.info('tw failed: ' + customer + aaDoc.title)

                    eml = {
                        'to_email':
                        acctDoc.account_email,
                        'body':
                        'Please login to your _________ account and refresh your Twitter login on the Account page.<br /><br />'
                        + aaDoc.twstatus_note,
                        'subject':
                        '_________ needs your attention',
                        'title':
                        'Expired Connection',
                        'bcc_email':
                        '_____@_______.com'
                    }

                    sendEmailGenericSG(**eml)

                elif 'id' in resp0:
                    aaDoc.twstatus_note = "Posted: " + customer + str(
                        datetime.datetime.today())
                    aaDoc.twstatus = "posted"
                    aaDoc.put()
                    good += 1
                    logging.info('tw posted: ' + customer + aaDoc.title)
                else:
                    aaDoc.twstatus_note = "Error: " + customer + resp1
                    aaDoc.twstatus = "error"
                    aaDoc.put()
                    bad += 1
                    logging.info('tw failed: ' + customer + aaDoc.title)

                    if not aaDoc.account_id in error_sent:
                        eml = {
                            'to_email':
                            acctDoc.account_email,
                            'body':
                            'Please login to your _________ account and refresh your Twitter login on the Account page.'
                            + tw_instructions,
                            'subject':
                            '_________ needs your attention',
                            'title':
                            'Expired Connection',
                            'bcc_email':
                            '_____@_______.com'
                        }

                        sendEmailGenericSG(**eml)

                        error_sent.append(aaDoc.account_id)

            else:

                aaDoc.twstatus_note = "Error: " + customer

                aaDoc.twstatus = "error"

                aaDoc.put()

                bad += 1

                logging.info('Twitter failed: ' + customer + aaDoc.title)

                if not aaDoc.account_id in error_sent:
                    eml = {
                        'to_email':
                        acctDoc.account_email,
                        'body':
                        'Please login to your _________ account and create your Twitter connection on the Account page.<br /><br />'
                        + tw_instructions,
                        'subject':
                        '_________ needs your attention',
                        'title':
                        'Twitter Connection',
                        'bcc_email':
                        '_____@_______.com'
                    }

                    sendEmailGenericSG(**eml)

                    error_sent.append(aaDoc.account_id)

        except Exception as e:
            logging.error('error_worker_342: ' + e.message)
            aaDoc.twstatus_note = "Error: " + e.message
            aaDoc.twstatus = "error"
            aaDoc.put()
            bad += 1
Esempio n. 9
0
def auth_check(app):
    """
    Check authorization.  Get signin token and auth_url, if needed.
    <app> = application identifier
    
    @redirect = redirect to this url post-authorization verification
    """
    try:
        access_token = session_get(app, 'access_token')
        access_token_secret = session_get(app, 'access_token_secret')

        if access_token and access_token_secret:
            tk = get_twitter_keys(app)
            client = UserClient(tk.consumer_key,
                                tk.consumer_secret,
                                access_token=access_token,
                                access_token_secret=access_token_secret)
            """
            We need to make a call to verify_credentials in case the user
            has revoked access for this application. This is a rate-limited
            call and so this approach might not be ideal. If we end up
            having rate-limiting problems, we might try giving each user
            a unique application ID that is kept in local storage and used
            as a lookup for Twitter creds (vs. session data which is domain-
            specific and thus problematic for our extension-approach). This
            might allow us to consolidate Twitter creds per user rather than
            storing them for each domain visited."""
            verif = client.api.account.verify_credentials.get()
            if verif.headers['status'].split()[0] == '200':
                return jsonify({'is_auth': 1})
            else:
                # possibly revoked access, although this will probably
                # get handled by the TwitterAuthError catch
                remove_session_credentials('stakeholder')
                return jsonify({'is_auth': 0})

        tk = get_twitter_keys(app)
        client = UserClient(tk.consumer_key, tk.consumer_secret)

        callback = 'http://' + request.host + url_for('auth_verify', app=app)
        print 'getting auth token for callback:', callback
        token = client.get_authorize_token(callback)

        session_set(app, 'auth_token', token.oauth_token)
        session_set(app, 'auth_token_secret', token.oauth_token_secret)
        session_set(app, 'auth_redirect', request.args.get('redirect') or '')

        # START DEBUG
        print 'AUTH_CHECK', app
        for k, v in session.iteritems():
            print k, v
        # END DEBUG
        if 'html' in request.headers['Accept'] and request.args.get(
                '_format') != 'json':
            print 'redirecting', token.auth_url
            return redirect(token.auth_url)
        else:
            data = {'is_auth': 0, 'auth_url': token.auth_url}
            return jsonify(data)
    except TwitterAuthError:
        remove_session_credentials(app)
        return jsonify({'is_auth': 0})
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 10
0
from birdy.twitter import UserClient
from geopy.geocoders import Nominatim
import json
import datetime

# Create twitte client
client = UserClient("ekYpdh37MmkQWTcrG484zgwXw",
                    "AMHi5d8hEOfDLDJexKpnvqj2YOzAwxLPkotqEEkR81NaFdYseK",
                    "609379206-usySeSFiB9nqMZRkmIxWolvscDVl22m1rB9v6RFM",
                    "KFSMqHyOcLL5PHKynpVwsnPv4E1tIQi5yszf8ijh69zs2")

# user inputs
radius = input("enter a radius ex: 1mi, 15mi:  ->")
address = input("enter an address. ex: 123 fake street Houston, TX 77006:  ->")
query = input("enter a search query. ex: hurricane harvey 2017:  ->")
# since_id = input("enter a start date. ex: 2017-11-03 ")
# until = input("enter an end date. ex: 2017-11-03 ")

# GeoLocation
# geolocator = Nominatim()
# def gen_location(address):
#     if address:
#         return geolocator.geocode(address)
#     else:
#         return gen_location(input("no address found. please enter address"))
# GEOCODE
# location = gen_location(address)
# coordinates = "{} {}".format(location.latitude, location.longitude)
# geocode = "{} {}".format(coordinates, radius)

# Date
Esempio n. 11
0
loadfont = pygame.font.SysFont('Arial', 10)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption(userScreenName + "'s " + streamMode)

clock = pygame.time.Clock()
crashed = False




CONSUMER_KEY 	= 
CONSUMER_SECRET = 
TOKEN_KEY 		= 
TOKEN_SECRET 	= 

client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET)

try:
	pickle_in = open(pickleFileName,"rb")
	ID, response = pickle.load(pickle_in)
except:
	ID = -1
	response = -1

if(loadData == False):
	ID = -1
	response = -1

def generateQRCode(url):
	qr = qrcode.QRCode(
		version = 1,
Esempio n. 12
0
 def step1(self, key, secret):
     self.consumer_key = key
     self.consumer_secret = secret
     self.client = UserClient(self.consumer_key, self.consumer_secret)
Esempio n. 13
0
# see birdy documentation for further use

from birdy.twitter import UserClient
client = UserClient('XXX', 'XXX', 'XXX', 'XXX')
Esempio n. 14
0
from birdy.twitter import UserClient
import json
from settings import APIKEYS

client = UserClient(APIKEYS['CONSUMER_KEY'], APIKEYS['CONSUMER_SECRET'],
                    APIKEYS['ACCESS_TOKEN'], APIKEYS['ACCESS_TOKEN_SECRET'])

response = client.api.statuses.user_timeline.get(user_id='17919972', count=1)
print json.dumps(response.data[0])
__author__ = 'artemkorhov'
from birdy.twitter import UserClient
import csv
import json
from collections import deque

consumer_key = 'cqPq4cD2V4BiMeHIn0H4ZAArj'
consumer_secret = 'bHH14mWh7oAGzOX9RWRpe9j5nrXMROPzbHW3GnGyj6kXGOXVxk'
access_token_key = '939819955-HNlyWZbEwXq5GeTR0ZsgaxcDQ2fA8xsABahPVH0d'
access_token_secret = 'Pb33YWDCDISlq9tZo80qvyh8IjuK9Ebtk3290pYXDf7GR'

client = UserClient(consumer_key, consumer_secret, access_token_key, access_token_secret)

# Get tweet ids
with open('uids.csv', 'rU') as f:
    reader = csv.reader(f)
    user_ids = []
    for row in reader:
        user_ids.extend(row)

    f.close()
print len(user_ids)

# tweet_ids - queue
queue = deque(user_ids)
for i in range(0, 1):
    user_id = queue.popleft()
    response = client.api.followers.ids.get(id=str(user_id), count=5000)
    followers = response.data.get('ids', [])
    obj = {user_id: followers}
    obj = json.dumps(obj)
Esempio n. 16
0
#import pandas as pd
from birdy.twitter import UserClient
from pandas.io.json import json_normalize
import sqlalchemy as sa

ckey='your jkey'
csecret='your secret'
token='token'
token_secret='secret'

c=UserClient(ckey, csecret, token, token_secret)

r=c.api.statuses.user_timeline
resp=r.get(screen_name='mugecevik', count=100)

df=json_normalize(resp.data)
df.to_sql('mugecevik_tw' , e, if_exists='append', index = False, )

Esempio n. 17
0
Created on Tue Jul 10 20:37:06 2018

@author: Peter
"""
testing = False

from birdy.twitter import UserClient
import urllib
import emoji
import textwrap
import datetime
import os
import sys
import twittersettings as settings

client = UserClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET,
                    settings.ACCESS_TOKEN, settings.ACCESS_TOKEN_SECRET)

os.chdir(os.path.dirname(sys.argv[0]))
if not os.path.isfile('tweetlock'):

    f = open('tweetlock', 'w+')
    f.close()
    try:
        printHist = 'tweets.txt'

        idfile = open(printHist, 'r')
        ids = idfile.readlines()
        idfile.close()

        print('\n')
        print(str(datetime.datetime.now()))
Esempio n. 18
0
import json
from decimal import Decimal
from time import time
from delorean import parse
from settings import *
from birdy.twitter import UserClient, StreamClient
import boto3

rest_client = UserClient(**TWITTER_APP)
stream_client = StreamClient(**TWITTER_APP)

user_ids = []
for twitter_list in LISTS:
    print 'Fetching %s / %s' % twitter_list
    owner_screen_name, slug = twitter_list
    response = rest_client.api.lists.members.get(
        owner_screen_name=owner_screen_name,
        slug=slug,
        count=5000,
        include_entities=False,
        skip_status=True,
    )
    users = [user['id_str'] for user in response.data['users']]
    print 'Fetched %s members' % len(users)
    user_ids += users

user_ids = list(set(user_ids))
print 'Fetched %s unique users' % len(user_ids)

dynamodb = boto3.resource(
    'dynamodb',
Esempio n. 19
0
import json
import pathlib
import pprint
import sys

from birdy.twitter import UserClient, TwitterClientError,\
                          TwitterApiError, TwitterRateLimitError
import yaml

if len(sys.argv) < 2:
    sys.exit('see usage.')

with pathlib.Path('config.yaml').open('r') as f:
    config = yaml.load(f)

client = UserClient(config['consumer_key'], config['consumer_secret'],
                    config['access_token'], config['access_token_secret'])

for arg in sys.argv[1:]:
    print('Working on file: ' + arg)
    tweet_file = pathlib.Path(arg)
    if not tweet_file.is_file:
        sys.exit('file does not exist or is not a file.')

    try:
        with tweet_file.open('r') as f:
            tweet_json = f.read()
    except:
        sys.exit('Error on reading file: ' + arg)

    try:
        if tweet_json.find('=') < tweet_json.find('['):
Esempio n. 20
0
#!/usr/bin/env python
#To get twitter oauth tokens
#1. Get your consumer key and consumer secret from the app page on apps.twitter.com
#2. Use the birdy python library

from birdy.twitter import UserClient

key = raw_input("Consumer key: ")
secret = raw_input("Consumer secret: ")
client = UserClient(key, secret)
token = client.get_signin_token()
access_key = token.oauth_token
access_secret = token.oauth_token_secret
print token.auth_url
pin = raw_input("PIN: ")
client = UserClient(key, secret, access_key, access_secret)
client.get_access_token(pin)
print token
Esempio n. 21
0
def twitter_connect():
    return UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                      ACCESS_TOKEN_SECRET)
Esempio n. 22
0
from birdy.twitter import UserClient

CONSUMER_KEY = CONSUMER_KEY
CONSUMER_SECRET = CONSUMER_SECRET
CALLBACK_URL = 'https://127.0.0.1:8000/register'

client = UserClient(CONSUMER_KEY, CONSUMER_SECRET)
token = client.get_authorize_token(CALLBACK_URL)

ACCESS_TOKEN = token.oauth_token
ACCESS_TOKEN_SECRET = token.oauth_token_secret
TWITTER_URL = token.auth_url

OAUTH_VERIFIER = request.GET['oauth_verifier']
Esempio n. 23
0
from config import *
from birdy.twitter import UserClient

# Use the client to generate the auth token and auth secret
client = UserClient(get_consumer_key(), get_consumer_secret())
token = client.get_authorize_token()
AUTH_TOKEN = token.oauth_token
AUTH_TOKEN_SECRET = token.oauth_token_secret

# Prompt the user to visit the auth URL
print "Go to the following URL to get the PIN: "
print token.auth_url

# Get PIN (OAUTH_VERIFIER) from user
OAUTH_VERIFIER = raw_input("Enter PIN: ")

# Use the client to generate the access token and access secret
client = UserClient(get_consumer_key(), get_consumer_secret(), AUTH_TOKEN,
                    AUTH_TOKEN_SECRET)
token = client.get_access_token(OAUTH_VERIFIER)

# Display OAUTH token and secret
print "Save these values in your application's config.py file: "
print "OAUTH_TOKEN = '" + token.oauth_token + "'"
print "OAUTH_TOKEN_SECRET = '" + token.oauth_token_secret + "'"
import json
import db_init
import datetime
import time
from pony.orm import *
from dateutil import parser

from birdy.twitter import UserClient, TwitterApiError

import pass_tw  ## twitter credentials
#import unicodedata
#from unidecode import unidecode

client2 = UserClient(pass_tw.CONSUMER_KEY_2, pass_tw.CONSUMER_SECRET_2,
                     pass_tw.ACCESS_TOKEN_2, pass_tw.ACCESS_TOKEN_SECRET_2)

resource_timeline = client2.api.statuses.user_timeline


@db_session
def find_tweets_to_fecth():
    to_fetch = db_init.Tweet_Reply.select(
        lambda p: p.fetch_status == "To Fetch")[:]
    return to_fetch


@db_session
def update_tweets(list_tweets):
    print(len(list_tweets), " tweets do usuario")  #id_usuario
    for tweet in list_tweets:
        status = find_user_tweets(tweet.id_usuario, tweet.id)
Esempio n. 25
0
class TwitterHelper:

    # you're going to need https://github.com/inueni/birdy
    from birdy.twitter import StreamClient
    from birdy.twitter import UserClient

    # the usual Twitter OAuth stuff goes here. you know the drill
    CONSUMER_KEY = os.environ['BOT_CONSUMER_KEY']
    CONSUMER_SECRET = os.environ['BOT_CONSUMER_SECRET']
    ACCESS_TOKEN = os.environ['BOT_ACCESS_TOKEN']
    ACCESS_TOKEN_SECRET = os.environ['BOT_ACCESS_TOKEN_SECRET']

    streaming_client = StreamClient(CONSUMER_KEY, CONSUMER_SECRET,
                                    ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    rest_client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                             ACCESS_TOKEN_SECRET)

    @staticmethod
    def permalink(tweet_id, screen_name):
        return 'https://twitter.com/' + screen_name + '/statuses/' + tweet_id

    @staticmethod
    def recent_tweets(count, screen_name=None):
        return TwitterHelper.rest_client.api.statuses.user_timeline.get(
            screen_name=screen_name, count=count).data

    @staticmethod
    def raw_stream(raw_search_terms):
        return TwitterHelper.streaming_client.stream.statuses.filter.post(
            track=raw_search_terms).stream()

    @staticmethod
    def get_tweet(tweet_id):
        return TwitterHelper.rest_client.api.statuses.show.get(
            id=tweet_id).data

    @staticmethod
    def send_tweet(in_reply_to, text):
        if DEBUG:
            logging.info('Debug mode is on. Skipping sending tweet "' + text +
                         '"')
        else:
            TwitterHelper.rest_client.api.statuses.update.post(
                in_reply_to_status_id=in_reply_to, status=text)

    @staticmethod
    def fav_tweet(tweet_id):
        if DEBUG:
            logging.info('Debug mode is on. Skipping favoriting tweet ' +
                         tweet_id)
        else:
            TwitterHelper.rest_client.api.favorites.create.post(id=tweet_id)

    @staticmethod
    def send_dm(screen_name, text):
        if DEBUG:
            logging.info('Debug mode is on. Skipping sending DM "' + text +
                         '" to ' + screen_name)
        else:
            TwitterHelper.rest_client.api.direct_messages.new.post(
                screen_name=screen_name, text=text)
Esempio n. 26
0
from birdy.twitter import UserClient
import twittertokens

use_aeroplanes_api = False

client = UserClient(twittertokens.CONSUMER_KEY, twittertokens.CONSUMER_SECRET,
                    twittertokens.ACCESS_TOKEN,
                    twittertokens.ACCESS_TOKEN_SECRET)


def tweet(text):
    response = ''
    global client
    try:
        response = client.api.statuses.update.post(status=text)
    except Exception as e:
        print(e)
        print("failed to tweet : retry\n")
        try:
            response = client.api.statuses.update.post(status=text)
            print("tweet retry ok\n")
        except Exception as e:
            print(e)
            print("failed to tweet a second time\n")
    return response
Esempio n. 27
0
def fetch_twitter(twitter_handle, since):
    client = UserClient(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                        ACCESS_TOKEN_SECRET)
    response = client.api.statuses.user_timeline.get(
        screen_name=twitter_handle, since_id=since)
    return response.data