def updateSched(pipe): # KeyboardInterrupt is not a good thing to catch in here. signal.signal(signal.SIGINT, signal.SIG_IGN) config = ConfigParser.RawConfigParser() config.read("impetus.conf") creds = dict(config.items("twitter")) pipe.send(creds) t = Twython(creds["con_key"], creds["con_secret"], creds["access_token"], creds["access_secret"]) lastUpdate = safeConfGet(config, "alarm", "last_time") if lastUpdate: lastUpdate = dt.strptime(lastUpdate, "%Y-%m-%d %H:%M:%S.%f") else: lastUpdate = dt.min lastId = safeConfGet(config, "alarm", "last_id") while 1: if pipe.poll(): obj = pipe.recv() if isinstance(obj, dt): pipe.send(nextAlarm(obj, config)) elif obj == "teardown": break if dt.now() > lastUpdate + td(minutes=3): try: dms = t.get_direct_messages(since_id=lastId) if dms: dms.reverse() for dm in dms: processed = processDm(config, dm) if processed: lastId = processed config.set("alarm", "last_id", lastId) t.send_direct_message( screen_name=dm["sender_screen_name"], text="Command sent on %s has been processed." % dm["created_at"], ) except TwythonError: pass # Hrm. lastUpdate = dt.now() config.set("alarm", "last_time", lastUpdate) saveConfig(config) sleep(1) config.set("alarm", "last_id", lastId) config.set("alarm", "last_time", lastUpdate) cfg = open("impetus.conf", "w") config.write(cfg) cfg.close() pipe.close()
def check_dm_and_respond(): # get configs apiKey, apiSecret, accessToken, accessTokenSecret, receiverTwitterId = read_twitter_bot_config() # initialise Twython api = Twython(apiKey, apiSecret, accessToken, accessTokenSecret) # Get the last DM DMs = api.get_direct_messages(count=1, skip_status='true') # print(DMs) if 'events' in DMs and len(DMs['events']) > 0: msg = DMs['events'][0] if 'message_create' in msg and 'message_data' in msg['message_create'] and 'text' in msg['message_create'][ 'message_data']: text = msg['message_create']['message_data']['text'] text = text.lower() print('Received DM : {}'.format(text)) if 'ip' in text: output = subprocess.check_output("ifconfig | grep inet", shell=True) event_data = get_formatted_data(receiverTwitterId, str(output)) api.send_direct_message(**event_data) print('Sent IP address') if 'ifconfig' in text: output = subprocess.check_output("ifconfig", shell=True) event_data = get_formatted_data(receiverTwitterId, str(output)) api.send_direct_message(**event_data) print('Sent ifconfig') if 'wifi' in text or 'iwconfig' in text: output = subprocess.check_output("iwgetid", shell=True) event_data = get_formatted_data(receiverTwitterId, str(output)) api.send_direct_message(**event_data) else: print("Don't know how to handle this text") print("Done")
class TwitterBot: def __init__(self, name, con_k, con_s, acc_k, acc_s): self.name = name self.con_k = con_k self.con_s = con_s self.acc_k = acc_k self.acc_s = acc_s self.twitter = Twython(self.con_k, self.con_s, self.acc_k, self.acc_s) self.last_intervals = [] self.last_tweet = '' def get_dms(self): if self.twitter is not None: dms = self.twitter.get_direct_messages() return dms def update_image(self): if self.twitter is not None: with open('zf.png', 'rb') as image_file: encoded_string = base64.b64encode(image_file.read()) results = self.twitter.update_profile_image(image=encoded_string) return results def change_name(self, name): if self.twitter is not None: name = name.replace('"','') results = self.twitter.update_profile(name=name) return results def tweet(self, msg): if self.twitter is not None: # > 140 char detection if len(msg) > 140: msg = msg[0:139] syslog.syslog('%s is tweeting %s' % (self.name, msg)) try: self.twitter.update_status(status=msg) self.last_tweet = msg except Exception as e: syslog.syslog('%s error tweeting -> %s' % (self.name, str(e)))
def receive(self): dm_enable = self.param('receiving', 'dm') ids = self.param('receiving', 'ids') tweets = list() user_timeline = list() APP_KEY = self.param('receiving', 'key') APP_SECRET = self.param('receiving', 'secret') OAUTH_TOKEN = self.param('receiving', 'token') OAUTH_TOKEN_SECRET = self.param('receiving', 'tsecret') SCREEN_NAME = self.param('receiving', 'name') twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: if dm_enable: if len(ids) > 0: for dm_id in ids: dm = twitter.get_direct_message(id=dm_id) user_timeline.append(dm) else: user_timeline = twitter.get_direct_messages() else: if len(ids) > 0: for t_id in ids: tweet = twitter.show_status({'id': t_id}) user_timeline.append(tweet) else: user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME) for x in user_timeline: if 'text' in x: tweets.append(x['text']) except Exception as err: raise ExfilChannel("Error retrieving tweets: {0}".format(err)) return tweets
from twython import Twython, TwythonError twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) get_list = twitter.get_direct_messages() #Returns All Twitter DM information which is a lot in a list format dm_dict = get_list[0] #Sets get_list to a dictionary, the number in the list is the direct message retrieved #That means that 0 is the most recent and n-1 is the last DM revieved. #You can cycle through all the numbers and it will return the text and the sender id of each print dm_dict['text'] #Gets the text from the dictionary print dm_dict['sender']['id'] #Gets the ID of the sender
ACCESS_TOKEN_SECRET = a[3] file.close() return API_KEY, API_KEY_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET getApiKeys("keys.txt") try: time.sleep(1) twitter = Twython( getApiKeys("keys.txt")[0], getApiKeys("keys.txt")[1], getApiKeys("keys.txt")[2], getApiKeys("keys.txt")[3]) dms = twitter.get_direct_messages()["events"] except: print("Dms cannot be pulled at this moment") pullId = [] pullTxt = [] for x in range(len(dms)): anId = dms[x]["id"] someTxt = dms[x]["message_create"]["message_data"]["text"] pullId.append(anId) pullTxt.append(someTxt)
class TwythonAPITestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) def test_construct_api_url(self): """Test constructing a Twitter API url works as we expect""" url = 'https://api.twitter.com/1.1/search/tweets.json' constructed_url = self.api.construct_api_url(url, q='#twitter') self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter') def test_get(self): """Test Twython generic GET request works""" self.api.get('account/verify_credentials') def test_post(self): """Test Twython generic POST request works, with a full url and with just an endpoint""" update_url = 'https://api.twitter.com/1.1/statuses/update.json' status = self.api.post(update_url, params={'status': 'I love Twython!'}) self.api.post('statuses/destroy/%s' % status['id_str']) def test_get_lastfunction_header(self): """Test getting last specific header of the last API call works""" self.api.get('statuses/home_timeline') self.api.get_lastfunction_header('x-rate-limit-remaining') def test_get_lastfunction_header_not_present(self): """Test getting specific header that does not exist from the last call returns None""" self.api.get('statuses/home_timeline') header = self.api.get_lastfunction_header('does-not-exist') self.assertEqual(header, None) def test_get_lastfunction_header_no_last_api_call(self): """Test attempting to get a header when no API call was made raises a TwythonError""" self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made') def test_search_gen(self): """Test looping through the generator results works, at least once that is""" search = self.api.search_gen('twitter', count=1) counter = 0 while counter < 2: counter += 1 result = next(search) new_id_str = int(result['id_str']) if counter == 1: prev_id_str = new_id_str time.sleep(1) # Give time for another tweet to come into search if counter == 2: self.assertTrue(new_id_str > prev_id_str) def test_encode(self): """Test encoding UTF-8 works""" self.api.encode('Twython is awesome!') def test_html_for_tweet(self): """Test HTML for Tweet returns what we want""" tweet_text = self.api.html_for_tweet(test_tweet_object) self.assertEqual(test_tweet_html, tweet_text) def test_html_for_tweet_expanded_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, use_expanded_url=True) # Make sure full url is in HTML self.assertTrue('http://google.com' in tweet_text) def test_html_for_tweet_short_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, False) # Make sure HTML doesn't contain the display OR exapanded url self.assertTrue(not 'http://google.com' in tweet_text) self.assertTrue(not 'google.com' in tweet_text) def test_raise_error_on_bad_ssl_cert(self): """Test TwythonError is raised by a RequestException when an actual HTTP happens""" self.assertRaises(TwythonError, self.api.get, 'https://example.com') # Timelines def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man!') # Friends & Followers def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
# keep sleep mode on sleep_status = True psql.sendSQL("UPDATE sleep SET active = true;") print('sleep mode start activated') if sleep_status and now.hour == sleep_end.hour and now.minute == sleep_end.minute: # we are at the sleep end time, so turn on the heat rc.onAll(twitter) # turn off sleep mode sleep_status = 0 psql.sendSQL("UPDATE sleep SET active = false;") twitter.send_direct_message(text='Sleep Mode Off', screen_name=tc.ok_user_id) print('sleep mode end activated') # read direct messages try: direct_messages = twitter.get_direct_messages() direct_messages = direct_messages['events'] except: print('twitter GET rate limit error') direct_messages = [] num_messages = len(direct_messages) # see if there is a new direct message # print('found ' + str(num_messages) + ' messages') for i in range(num_messages): #sender_name = direct_messages[num_messages - i - 1]['sender_screen_name'] sender_name = direct_messages[num_messages - i -1]['message_create']['sender_id'] message_id = direct_messages[num_messages - i - 1]['id'] if sender_name == ok_user_name: #message = direct_messages[num_messages - i - 1]['text'].upper() message = direct_messages[num_messages - i - 1]['message_create']['message_data']['text'].upper()
class TwitterNetwork(CtbNetwork): def __init__(self, conf, ctb): CtbNetwork.__init__(self, "twitter") self.conf = conf self.ctb = ctb self.db = ctb.db self.user = conf.auth.user self.app_key = conf.auth.app_key self.app_secret = conf.auth.app_secret self.oauth_token = conf.auth.oauth_token self.oauth_token_secret = conf.auth.oauth_token_secret self.conn = None self.stream = None self.webhooks = None self.account_id = None self.last_db_msg_id = None self.last_db_msg_time = None @classmethod def _timestamp_utc(cls, dt): if isinstance(dt, basestring): dt = parse(dt) return calendar.timegm(dt.utctimetuple()) @classmethod def _timestamp_utc_now(cls): dt = datetime.utcnow() return calendar.timegm(dt.utctimetuple()) def get_account_id(self): # Function for fetching the bot's ID credentials = self.conn.request('account/verify_credentials') return credentials['id'] def get_user_id(self, name): # Function for fetching a users ID credentials = self.conn.lookup_user(screen_name=name) return credentials[0]['id'] def get_user_name(self, id): # Function for fetching a users ID credentials = self.conn.lookup_user(user_id=id) return credentials[0]['screen_name'] def get_last_msg_id(self): # Function to get last msg_id saved in DB sql = "SELECT msg_id FROM t_action WHERE created_utc=(SELECT MAX(created_utc) FROM t_action)" sqlrow = self.db.execute(sql).fetchone() return sqlrow['msg_id'] def get_last_db_action_time(self): # Function to get last action saved in DB sql = "SELECT created_utc, msg_id FROM t_action WHERE created_utc=(SELECT MAX(created_utc) FROM t_action)" sqlrow = self.db.execute(sql).fetchone() return sqlrow['created_utc'], sqlrow['msg_id'] def connect(self): """ Returns a Twitter stream object """ lg.debug('TwitterNetwork::connect(): connecting to Twitter...') self.conn = Twython(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret) self.stream = TwitterStreamer(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret, timeout=30) self.account_id = self.get_account_id() self.webhooks = TwitterWebHooks(self.conn, self.app_secret, self.account_id) self.conn.username = self.stream.username = self.webhooks.username = self.user self.stream.conn = self.conn self.stream.ctb = self.webhooks.ctb = self.ctb self.stream.last_event = self.stream.last_expiry = self.webhooks.last_event = self.webhooks.last_expiry = datetime.utcnow( ) def run_webhooks(self): lg.info("TwitterWebhooks::starting(): Start init") self.webhooks.run() def is_user_banned(self, user): return False def send_msg(self, user_to, subject, body, editor=None, msgobj=None): try: if msgobj: self.reply_msg(body, msgobj) else: lg.debug( "< TwitterNetwork::send_msg: sending direct message to %s: %s", user_to, body) id = self.get_user_id(user_to) event = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": id }, "message_data": { "text": body } } } } lg.debug(event) self.conn.send_direct_message(**event) lg.debug("< TwitterNetwork::send_msg to %s DONE", user_to) except TwythonError as e: lg.error("TwitterNetwork::send_msg: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::send_msg: traceback: %s", tb) return False else: return True def reply_msg(self, body, msgobj): try: if msgobj is None: pass elif msgobj.type == 'mention': body += ' #ReddCoin' lg.debug( "< TwitterNetwork::reply_msg: sending tweet to %s: %s", msgobj.author.name, body) self.conn.update_status(status=body[:280]) lg.debug("< TwitterNetwork::reply_msg to %s DONE", msgobj.author.name) elif msgobj.type == 'direct_message': lg.debug( "< TwitterNetwork::reply_msg: sending direct message to %s: %s", msgobj.author.name, body) id = self.get_user_id(msgobj.author.name) event = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": id }, "message_data": { "text": body } } } } lg.debug(event) self.conn.send_direct_message(**event) lg.debug("< TwitterNetwork::reply_msg to %s DONE", msgobj.author.name) except TwythonError as e: lg.error("TwitterNetwork::reply_msg: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::reply_msg: traceback: %s", tb) return False else: return True def _parse_mention(self, data): # ignore retweets if 'retweeted_status' in data: return None author_name = data['user']['screen_name'] if author_name == self.user or '@' + self.user not in data['text']: return None # we do allow the bot to issue commands msg = { 'created_utc': self._timestamp_utc_now(), 'author': { 'name': author_name }, 'type': 'mention' } msg['id'] = data['id_str'] + str( msg['created_utc'])[(30 - len(data['id_str'])):] text = data['text'] msg['body'] = text.replace('@' + self.user, '').strip() print(msg) action = ctb_action.eval_message(ctb_misc.DotDict(msg), self.ctb) return action def check_mentions(self, ctb): """ Evaluate new mentions in timeline """ lg.debug('> TwitterNetwork::check_mentions()') try: # Read the last timeline mentions from twitter since the last recorded event since_id = self.last_db_msg_id resp = self.conn.get_mentions_timeline(count=200, since_id=since_id) for tweet in resp: fields = ['created_at', 'id', 'user', 'entities', 'text'] if all(field in tweet for field in fields): # received a mention actions = self._parse_mention(tweet) if not actions: continue if not isinstance(actions, list): actions = [actions] for action in actions: if action: lg.info( "TwitterNetwork::check_mentions(): %s from %s", action.type, action.u_from.name) lg.debug( "TwitterNetwork::check_mentions(): comment body: <%s>", action.msg.body) action.do() except TwythonRateLimitError: lg.error( 'TwitterNetwork::check_mentions(): Twitter API Rate Limit Breached. Sleep 15m30s' ) time.sleep(15 * 60 + 30) lg.info("TwitterNetwork::check_mentions(): Web Hook endpoint starting") self.webhooks.run() def _parse_direct_message(self, event_data): recipient_id = event_data['message_create']['target']['recipient_id'] sender_id = event_data['message_create']['sender_id'] sender_screen_name = self.get_user_name(sender_id) message_text = event_data['message_create']['message_data']['text'] msg = { 'created_utc': self._timestamp_utc_now(), 'author': { 'name': sender_screen_name }, 'recipient_id': sender_id, 'type': 'direct_message' } msg['id'] = event_data['id'] + str( msg['created_utc'])[(30 - len(event_data['id'])):] text = event_data['message_create']['message_data']['text'] msg['body'] = text.replace('@' + self.user, '').strip() lg.debug(msg) action = ctb_action.eval_message(ctb_misc.DotDict(msg), self.ctb) return action def check_inbox(self, ctb): """ Evaluate new messages in inbox """ lg.debug('> TwitterNetwork::check_inbox()') try: if self.last_db_msg_time is None: self.last_db_msg_time, self.last_db_msg_id = self.get_last_db_action_time( ) #[self.last_db_msg_time, self.last_db_msg_id] since_time = self.last_db_msg_time resp = self.conn.get_direct_messages(count=200) for msg in resp['events']: msg_timestamp = int( msg['created_timestamp'] ) / 1000 # twitter timestamps in milliseconds if msg_timestamp > since_time: if msg['id'] != self.last_db_msg_id: if self.account_id != int( msg['message_create']['sender_id']): # received a direct message actions = self._parse_direct_message(msg) if not actions: continue if not isinstance(actions, list): actions = [actions] for action in actions: if action: lg.info( "TwitterNetwork::check_inbox(): %s from %s", action.type, action.u_from.name) lg.debug( "TwitterNetwork::check_inbox(): comment body: <%s>", action.msg.body) action.do() except TwythonError as e: lg.error("TwitterNetwork::check_inbox(): exception: %s", e) pass except TwythonRateLimitError: lg.warning( "TwitterNetwork::check_inbox(): Twitter API rate limit exceeded, sleeping for 15m30s seconds" ) time.sleep(15 * 60 + 30) pass except Exception as e: lg.error("TwitterNetwork::check_inbox(): %s", e) raise lg.debug("< TwitterNetwork::check_inbox() DONE") return True def invite(self, user): try: resp = self.conn.create_friendship(screen_name=user) except TwythonError as e: # either really failed (e.g. sent request before) or already friends lg.warning("TwitterNetwork::invite: failed to follow user %s: %s", user, e.msg) lg.error("TwitterNetwork::invite: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::invite: traceback: %s", tb) return False else: lg.debug( 'TwitterNetwork::invite(): just sent request to follow user %s', user) return True
class TwythonEndpointsTestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } # This is so we can hit coverage that Twython sets # User-Agent for us if none is supplied oauth2_client_args = { 'headers': {} } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) # Timelines @unittest.skip('skipping non-updated test') def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() @unittest.skip('skipping non-updated test') def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) @unittest.skip('skipping non-updated test') def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() @unittest.skip('skipping non-updated test') def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets @unittest.skip('skipping non-updated test') def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get \ deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) @unittest.skip('skipping non-updated test') def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') @unittest.skip('skipping non-updated test') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search @unittest.skip('skipping non-updated test') def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages @unittest.skip('skipping non-updated test') def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() @unittest.skip('skipping non-updated test') def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() @unittest.skip('skipping non-updated test') def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s\ ' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) @unittest.skip('skipping non-updated test') def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man! \ %s' % int(time.time())) # Friends & Followers @unittest.skip('skipping non-updated test') def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) @unittest.skip('skipping non-updated test') def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') @unittest.skip('skipping non-updated test') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() @unittest.skip('skipping non-updated test') def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() @unittest.skip('skipping non-updated test') def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) @unittest.skip('skipping non-updated test') def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users @unittest.skip('skipping non-updated test') def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() @unittest.skip('skipping non-updated test') def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() @unittest.skip('skipping non-updated test') def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') @unittest.skip('skipping non-updated test') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') @unittest.skip('skipping non-updated test') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') @unittest.skip('skipping non-updated test') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') @unittest.skip('skipping non-updated test') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() @unittest.skip('skipping non-updated test') def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() @unittest.skip('skipping non-updated test') def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') @unittest.skip('skipping non-updated test') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') @unittest.skip('skipping non-updated test') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') @unittest.skip('skipping non-updated test') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) @unittest.skip('skipping non-updated test') def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() @unittest.skip('skipping non-updated test') def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) @unittest.skip('skipping non-updated test') def test_list_mutes(self): """Test listing users who are muted by the authenticated user succeeds""" self.api.list_mutes() @unittest.skip('skipping non-updated test') def test_list_mute_ids(self): """Test listing user ids who are muted by the authenticated user succeeds""" self.api.list_mute_ids() @unittest.skip('skipping non-updated test') def test_create_mute(self): """Test muting a user succeeds""" self.api.create_mute(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_mute(self): """Test muting a user succeeds""" self.api.destroy_mute(screen_name='justinbieber') # Suggested Users @unittest.skip('skipping non-updated test') def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') @unittest.skip('skipping non-updated test') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() @unittest.skip('skipping non-updated test') def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites @unittest.skip('skipping non-updated test') def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() @unittest.skip('skipping non-updated test') def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists @unittest.skip('skipping non-updated test') def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed \ %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) @unittest.skip('skipping non-updated test') def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() @unittest.skip('skipping non-updated test') def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') @unittest.skip('skipping non-updated test') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches @unittest.skip('skipping non-updated test') def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() @unittest.skip('skipping non-updated test') def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo @unittest.skip('skipping non-updated test') def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') @unittest.skip('skipping non-updated test') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') @unittest.skip('skipping non-updated test') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') @unittest.skip('skipping non-updated test') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends @unittest.skip('skipping non-updated test') def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) @unittest.skip('skipping non-updated test') def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() @unittest.skip('skipping non-updated test') def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help @unittest.skip('skipping non-updated test') def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() @unittest.skip('skipping non-updated test') def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() @unittest.skip('skipping non-updated test') def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() @unittest.skip('skipping non-updated test') def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() @unittest.skip('skipping non-updated test') def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
consumer_key, consumer_secret, access_token, access_token_secret ) # Fetch direct messages from Twitter, if running first time fetch last 5 # messages else fetch from the last message id # try open the file that contains last message id last_read_message_id = "" try: fmessage = open("messageids", "r") last_read_message_id = pickle.load(fmessage) except (EOFError, IOError) as e: # File not available running first time, fetch 5 messages twitter_messages = twitter.get_direct_messages(count=5) else: # old message info fetched, fetch messages after the last one twitter_messages = twitter.get_direct_messages( since_id=last_read_message_id) finally: fmessage.close() # iterate over messages and apply logic # reset last message id if there are messages to iterate if len(twitter_messages) > 0: last_read_message_id = "" for message in twitter_messages: message_txt = message["text"] message_id = message["id"] message_senderhandle = str(message["sender_screen_name"])
print '---> Listen <---' if config.get('Enviroment','LAST_DM_ID'): # pedir somente os itens maiores que o id existente... current_val = config.get('Enviroment','LAST_DM_ID') print '--> variavel atual: '+str(current_val)+' <--' #print 'Valor atual = '+current_val else: # variavel nao existe. config.set('Enviroment','LAST_DM_ID',0) config.write(open(fileDefaults,'w')) #abort script. print '--> Nao existe variavel! <--' exit() #pegando pacote com as mensagens enviadas #print 'seguindo...' pkgReturnDM = api.get_direct_messages(since_id=current_val) print '--> Tamanho do pacote: '+str(len(pkgReturnDM))+' <--' for returnDM in pkgReturnDM: senderData = returnDM['sender'] entities = returnDM['entities'] print 'Sender ---->' + config.get('Enviroment','allow_sender') print 'senderData:' + str(senderData['id']) if str(senderData['id']) == config.get('Enviroment','allow_sender'): print returnDM['created_at'] print '--> Usuario OK! <--' command = returnDM['entities']['hashtags'][0]['text'] print '-> comando recebido: '+command+' <-' #Executar o comando da hashtag full_path = '/home/raspbot/raspLab/tweetBot/' cmd = 'python '+full_path+'raspTweet.py '+command print '[ '+cmd+' ]'
def get_user_messages(consumer_key, consumer_sec, access_tok, access_token_sec, username='******'): twitter = Twython(consumer_key, consumer_sec, access_tok, access_token_sec) # user_timeline = twitter.get_user_timeline(screen_name='HeteroT1') user_messages = twitter.get_direct_messages(screen_name=username) for message in user_messages: print("message - ", message)
class TwythonAPITestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': { } # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) def test_construct_api_url(self): """Test constructing a Twitter API url works as we expect""" url = 'https://api.twitter.com/1.1/search/tweets.json' constructed_url = self.api.construct_api_url(url, q='#twitter') self.assertEqual( constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter') def test_get(self): """Test Twython generic GET request works""" self.api.get('account/verify_credentials') def test_post(self): """Test Twython generic POST request works, with a full url and with just an endpoint""" update_url = 'https://api.twitter.com/1.1/statuses/update.json' status = self.api.post( update_url, params={'status': 'I love Twython! %s' % int(time.time())}) self.api.post('statuses/destroy/%s' % status['id_str']) def test_get_lastfunction_header(self): """Test getting last specific header of the last API call works""" self.api.get('statuses/home_timeline') self.api.get_lastfunction_header('x-rate-limit-remaining') def test_get_lastfunction_header_not_present(self): """Test getting specific header that does not exist from the last call returns None""" self.api.get('statuses/home_timeline') header = self.api.get_lastfunction_header('does-not-exist') self.assertEqual(header, None) def test_get_lastfunction_header_no_last_api_call(self): """Test attempting to get a header when no API call was made raises a TwythonError""" self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made') def test_cursor(self): """Test looping through the generator results works, at least once that is""" search = self.api.cursor(self.api.search, q='twitter', count=1) counter = 0 while counter < 2: counter += 1 result = next(search) new_id_str = int(result['id_str']) if counter == 1: prev_id_str = new_id_str time.sleep( 1) # Give time for another tweet to come into search if counter == 2: self.assertTrue(new_id_str > prev_id_str) def test_encode(self): """Test encoding UTF-8 works""" self.api.encode('Twython is awesome!') def test_html_for_tweet(self): """Test HTML for Tweet returns what we want""" tweet_text = self.api.html_for_tweet(test_tweet_object) self.assertEqual(test_tweet_html, tweet_text) def test_html_for_tweet_expanded_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, use_expanded_url=True) # Make sure full url is in HTML self.assertTrue('http://google.com' in tweet_text) def test_html_for_tweet_short_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, False) # Make sure HTML doesn't contain the display OR exapanded url self.assertTrue(not 'http://google.com' in tweet_text) self.assertTrue(not 'google.com' in tweet_text) def test_raise_error_on_bad_ssl_cert(self): """Test TwythonError is raised by a RequestException when an actual HTTP happens""" self.assertRaises(TwythonError, self.api.get, 'https://example.com') # Timelines def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline( screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status( status='Test post just to get deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man! %s' % int(time.time())) # Friends & Followers def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
class Tweety(object): """ Twitter client using Twython """ def __init__(self, app_key=TWITTER_APP_KEY, app_secret=TWITTER_APP_SECRET, oauth_token=TWITTER_OAUTH_TOKEN, oauth_token_secret=TWITTER_OAUTH_SECRET): try: self.twitter = Twython( app_key, app_secret, oauth_token, oauth_token_secret) self.cache = RedisCache({ 'server': REDIS_SERVER, 'port': REDIS_PORT, 'database': REDIS_DATABASE, 'key_prefix': 'domus-twitter' }) except TwythonAuthError: raise Exception("Unable to connect to twitter") def __get_friends(self): """ Using twitter get_friends and redis, gets a list of screen names :return:a list of twitter users """ results = self.cache.get('twitter_friends') if not results: try: results = [a['screen_name'] for a in self.twitter.get_friends_list()['users']] self.cache.store('twitter_friends',json.dumps(results), expires=120) except (TwythonError, TwythonRateLimitError): raise Exception('Unable to get followers list') else: results = json.loads(results) return results def tweet(self, message,to_friends=False): """ Writtes a twit :param message: what to tweet :param to_friends: send to all friends? :return: """ try: if to_friends: for a_friend in self.__get_friends(): mention = "@{} ".format(a_friend) available_chars = 140 - len(mention) self.twitter.update_status( status=(mention+message)[:available_chars] + ((mention+message)[(available_chars-2):] and '..')) else: self.twitter.update_status( status=message[:140] + (message[138:] and '..')) except (TwythonError, TwythonRateLimitError): raise Exception("Unable to post update") def dm(self, user, message): try: self.twitter.send_direct_message(screen_name=user, text=message) except TwythonError: raise Exception("Unable to send dm to {}".format(user)) def get_dms(self): """ Gets a list of dms. Stores the last id seen so the next request is for the new messages only. :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}} """ results = {} dms = [] last_id = self.cache.get('twitter_last_dm') if last_id: dms = self.twitter.get_direct_messages(count=100,since_id = last_id) else: dms = self.twitter.get_direct_messages(count=100) if dms: last_id = 0 for a_dm in dms: results[a_dm['id']] = {'from':a_dm['sender_screen_name'],'text': a_dm['text']} last_id = a_dm['id'] if a_dm['id'] > last_id else last_id self.cache.store('twitter_last_dm', last_id) return results def get_mentions(self): """ Gets a list of mentions. Stores the last id seen so the next request is for the new messages only. :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}} """ results = {} mentions = [] last_id = self.cache.get('twitter_last_mention') if last_id: mentions = self.twitter.get_mentions_timeline(count=100,since_id = last_id) else: mentions = self.twitter.get_mentions_timeline(count=100) if mentions: last_id = 0 for a_mention in mentions: results[a_mention['id']] = {'from':a_mention['user']['screen_name'],'text': a_mention['text']} last_id = a_mention['id'] if a_mention['id'] > last_id else last_id self.cache.store('twitter_last_mention', last_id) return results
class TwythonAPITestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret) # Timelines def test_get_mentions_timeline(self): '''Test returning mentions timeline for authenticated user succeeds''' self.api.get_mentions_timeline() def test_get_user_timeline(self): '''Test returning timeline for authenticated user and random user succeeds''' self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): '''Test returning a protected user timeline who you are following succeeds''' self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): '''Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError''' self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_get_home_timeline(self): '''Test returning home timeline for authenticated user succeeds''' self.api.get_home_timeline() # Tweets def test_get_retweets(self): '''Test getting retweets of a specific tweet succeeds''' self.api.get_retweets(id=test_tweet_id) def test_show_status(self): '''Test returning a single status details succeeds''' self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): '''Test updating and deleting a status succeeds''' status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_retweet(self): '''Test retweeting a status succeeds''' retweet = self.api.retweet(id='99530515043983360') self.api.destroy_status(id=retweet['id_str']) def test_retweet_twice(self): '''Test that trying to retweet a tweet twice raises a TwythonError''' retweet = self.api.retweet(id='99530515043983360') self.assertRaises(TwythonError, self.api.retweet, id='99530515043983360') # Then clean up self.api.destroy_status(id=retweet['id_str']) def test_get_oembed_tweet(self): '''Test getting info to embed tweet on Third Party site succeeds''' self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): '''Test getting ids for people who retweeted a tweet succeeds''' self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): '''Test searching tweets succeeds''' self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): '''Test getting the authenticated users direct messages succeeds''' self.api.get_direct_messages() def test_get_sent_messages(self): '''Test getting the authenticated users direct messages they've sent succeeds''' self.api.get_sent_messages() def test_send_get_and_destroy_direct_message(self): '''Test sending, getting, then destory a direct message succeeds''' message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d!') self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) def test_send_direct_message_to_non_follower(self): '''Test sending a direct message to someone who doesn't follow you fails''' self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man!') # Friends & Followers def test_get_user_ids_of_blocked_retweets(self): '''Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds''' self.api.get_user_ids_of_blocked_retweets(stringify_ids='true') def test_get_friends_ids(self): '''Test returning ids of users the authenticated user and then a random user is following succeeds''' self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') def test_get_followers_ids(self): '''Test returning ids of users the authenticated user and then a random user are followed by succeeds''' self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') def test_lookup_friendships(self): '''Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds''' self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') def test_get_incoming_friendship_ids(self): '''Test returning incoming friendship ids succeeds''' self.api.get_incoming_friendship_ids() def test_get_outgoing_friendship_ids(self): '''Test returning outgoing friendship ids succeeds''' self.api.get_outgoing_friendship_ids() def test_create_friendship(self): '''Test creating a friendship succeeds''' self.api.create_friendship(screen_name='justinbieber') def test_destroy_friendship(self): '''Test destroying a friendship succeeds''' self.api.destroy_friendship(screen_name='justinbieber') def test_update_friendship(self): '''Test updating friendships succeeds''' self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets='false') def test_show_friendships(self): '''Test showing specific friendship succeeds''' self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): '''Test getting list of users authenticated user then random user is following succeeds''' self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): '''Test getting list of users authenticated user then random user are followed by succeeds''' self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): '''Test getting the authenticated user account settings succeeds''' self.api.get_account_settings() def test_verify_credentials(self): '''Test representation of the authenticated user call succeeds''' self.api.verify_credentials() def test_update_account_settings(self): '''Test updating a user account settings succeeds''' self.api.update_account_settings(lang='en') def test_update_delivery_service(self): '''Test updating delivery settings fails because we don't have a mobile number on the account''' self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') def test_update_profile(self): '''Test updating profile succeeds''' self.api.update_profile(include_entities='true') def test_update_profile_colors(self): '''Test updating profile colors succeeds''' self.api.update_profile_colors(profile_background_color='3D3D3D') def test_list_blocks(self): '''Test listing users who are blocked by the authenticated user succeeds''' self.api.list_blocks() def test_list_block_ids(self): '''Test listing user ids who are blocked by the authenticated user succeeds''' self.api.list_block_ids() def test_create_block(self): '''Test blocking a user succeeds''' self.api.create_block(screen_name='justinbieber') def test_destroy_block(self): '''Test unblocking a user succeeds''' self.api.destroy_block(screen_name='justinbieber') def test_lookup_user(self): '''Test listing a number of user objects succeeds''' self.api.lookup_user(screen_name='twitter,justinbieber') def test_show_user(self): '''Test showing one user works''' self.api.show_user(screen_name='twitter') def test_search_users(self): '''Test that searching for users succeeds''' self.api.search_users(q='Twitter API') def test_get_contributees(self): '''Test returning list of accounts the specified user can contribute to succeeds''' self.api.get_contributees(screen_name='TechCrunch') def test_get_contributors(self): '''Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account''' self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) def test_remove_profile_banner(self): '''Test removing profile banner succeeds''' self.api.remove_profile_banner() def test_get_profile_banner_sizes(self): '''Test getting list of profile banner sizes fails because we have not uploaded a profile banner''' self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users def test_get_user_suggestions_by_slug(self): '''Test getting user suggestions by slug succeeds''' self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): '''Test getting user suggestions succeeds''' self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): '''Test getting status of suggested users succeeds''' self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): '''Test getting list of favorites for the authenticated user succeeds''' self.api.get_favorites() def test_create_and_destroy_favorite(self): '''Test creating and destroying a favorite on a tweet succeeds''' self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): '''Test show lists for specified user''' self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): '''Test timeline of tweets authored by members of the specified list succeeds''' self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): '''Test create a list, adding and removing members then deleting the list succeeds''' the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name='johncena,xbox') self.api.delete_list_members(list_id=list_id, screen_name='johncena,xbox') # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_memberships(self): '''Test list of lists the authenticated user is a member of succeeds''' self.api.get_list_memberships() def test_get_list_subscribers(self): '''Test list of subscribers of a specific list succeeds''' self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): '''Test subscribing, is a list sub and unsubbing to list succeeds''' self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): '''Test returning if specified user is member of a list succeeds''' # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): '''Test listing members of the specified list succeeds''' self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): '''Test getting specific list succeeds''' self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): '''Test collection of the lists the specified user is subscribed to succeeds''' self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): '''Test collection of lists the specified user owns succeeds''' self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): '''Test getting list of saved searches for authenticated user succeeds''' self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): '''Test getting list of saved searches for authenticated user succeeds''' saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): '''Test getting info about a geo location succeeds''' self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): '''Test reversing geocode succeeds''' self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): '''Test search for places that can be attached to a statuses/update succeeds''' self.api.search_geo(query='Toronto') def test_get_similar_places(self): '''Test locates places near the given coordinates which are similar in name succeeds''' self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): '''Test getting the top 10 trending topics for a specific WOEID succeeds''' self.api.get_place_trends(id=1) def test_get_available_trends(self): '''Test returning locations that Twitter has trending topic information for succeeds''' self.api.get_available_trends() def test_get_closest_trends(self): '''Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds''' self.api.get_closest_trends(lat='37', long='-122')
class TwitterCommunicationBot(AbstractCommunicationClient): def __init__(self): self._setupTwitter() self.mostRecentMessageId = self._loadMostRecentMessageId() self.sentMessages = [] def _setupTwitter(self): logging.info('Setting up twitter client') self.twitter = Twython(TW_CONS_KEY, TW_CONS_SECRET, TW_ACCESS_KEY, TW_ACCESS_SECRET) def _loadMostRecentMessageId(self): try: with open(MESSAGE_ID_FILE, 'r') as f: id = f.read() return int(id) except (ValueError, IOError) as e: logging.warn('Failed to read most recent message, ex %s', e.message) def _isRequiredFormat(self, request): items = request.split(' ') if len(items) == 3: if len(items[1]) == 3 and len(items[2]) == 3: try: datetime.datetime.strptime(items[0], '%H:%M') return True except Exception as _: pass return False def getNewServiceRequests(self): validServiceRequests = [] validRemoveRequests = [] @retry(self._setupTwitter) def _getMessages(): return self.twitter.get_direct_messages(since_id=self.mostRecentMessageId if self.mostRecentMessageId else None) messages = _getMessages() or [] for message in messages: self.mostRecentMessageId = message.get('id') if message.get('id') > ( self.mostRecentMessageId or 0) else self.mostRecentMessageId request = message.get('text') if 'STOP' in request: request = request.replace('STOP', '').strip() if self._isRequiredFormat(request): logging.info('Removing: %s', request) self._postDirectMessage(message.get('sender_id'), 'Removed! - %s' % request) validRemoveRequests.append(request) continue if self._isRequiredFormat(request): logging.info('Subscribing to: %s', request) self._postDirectMessage(message.get('sender_id'), 'Subscribed! - %s' % request) validServiceRequests.append(request) continue self._postDirectMessage(message.get('sender_id'), 'I received an invalid request: %s' % request) self._postDirectMessage(message.get('sender_id'), 'Valid message format is HH:MM STN DEST, using station CRS codes. For example, 13:24 HIT KGX') with open(MESSAGE_ID_FILE, 'w') as f: f.truncate() f.write(str(self.mostRecentMessageId)) return validServiceRequests, validRemoveRequests def _postDirectMessage(self, userId, message): try: self.twitter.send_direct_message(user_id=userId, text=message) except TwythonError as e: logging.warn('Twython error sending direct message: %s', e.msg) def _sendMessage(self, message): tweet = datetime.date.today().strftime('%d/%m/%y') + ': ' + message if tweet not in self.sentMessages: try: self.twitter.update_status(status=tweet) self.sentMessages.append(tweet) except TwythonError as e: logging.warn('Twython error posting tweet: %s', e.msg) else: logging.warn('Message already sent: %s', tweet)
class TwythonEndpointsTestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) # Timelines @unittest.skip('skipping non-updated test') def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() @unittest.skip('skipping non-updated test') def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) @unittest.skip('skipping non-updated test') def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() @unittest.skip('skipping non-updated test') def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets @unittest.skip('skipping non-updated test') def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) @unittest.skip('skipping non-updated test') def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') @unittest.skip('skipping non-updated test') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search @unittest.skip('skipping non-updated test') def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages @unittest.skip('skipping non-updated test') def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() @unittest.skip('skipping non-updated test') def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() @unittest.skip('skipping non-updated test') def test_send_get_and_destroy_direct_message(self): """Test sending, getting, then destory a direct message succeeds""" message = self.api.send_direct_message(screen_name=protected_twitter_1, text='Hey d00d! %s' % int(time.time())) self.api.get_direct_message(id=message['id_str']) self.api.destroy_direct_message(id=message['id_str']) @unittest.skip('skipping non-updated test') def test_send_direct_message_to_non_follower(self): """Test sending a direct message to someone who doesn't follow you fails""" self.assertRaises(TwythonError, self.api.send_direct_message, screen_name=protected_twitter_2, text='Yo, man! %s' % int(time.time())) # Friends & Followers @unittest.skip('skipping non-updated test') def test_get_user_ids_of_blocked_retweets(self): """Test that collection of user_ids that the authenticated user does not want to receive retweets from succeeds""" self.api.get_user_ids_of_blocked_retweets(stringify_ids=True) @unittest.skip('skipping non-updated test') def test_get_friends_ids(self): """Test returning ids of users the authenticated user and then a random user is following succeeds""" self.api.get_friends_ids() self.api.get_friends_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_ids(self): """Test returning ids of users the authenticated user and then a random user are followed by succeeds""" self.api.get_followers_ids() self.api.get_followers_ids(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_lookup_friendships(self): """Test returning relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided succeeds""" self.api.lookup_friendships(screen_name='twitter,ryanmcgrath') @unittest.skip('skipping non-updated test') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() @unittest.skip('skipping non-updated test') def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() @unittest.skip('skipping non-updated test') def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) @unittest.skip('skipping non-updated test') def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users @unittest.skip('skipping non-updated test') def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() @unittest.skip('skipping non-updated test') def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() @unittest.skip('skipping non-updated test') def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') @unittest.skip('skipping non-updated test') def test_update_delivery_service(self): """Test updating delivery settings fails because we don't have a mobile number on the account""" self.assertRaises(TwythonError, self.api.update_delivery_service, device='none') @unittest.skip('skipping non-updated test') def test_update_profile(self): """Test updating profile succeeds""" self.api.update_profile(include_entities='true') @unittest.skip('skipping non-updated test') def test_update_profile_colors(self): """Test updating profile colors succeeds""" self.api.update_profile_colors(profile_background_color='3D3D3D') @unittest.skip('skipping non-updated test') def test_list_blocks(self): """Test listing users who are blocked by the authenticated user succeeds""" self.api.list_blocks() @unittest.skip('skipping non-updated test') def test_list_block_ids(self): """Test listing user ids who are blocked by the authenticated user succeeds""" self.api.list_block_ids() @unittest.skip('skipping non-updated test') def test_create_block(self): """Test blocking a user succeeds""" self.api.create_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_block(self): """Test unblocking a user succeeds""" self.api.destroy_block(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_lookup_user(self): """Test listing a number of user objects succeeds""" self.api.lookup_user(screen_name='twitter,justinbieber') @unittest.skip('skipping non-updated test') def test_show_user(self): """Test showing one user works""" self.api.show_user(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_search_users(self): """Test that searching for users succeeds""" self.api.search_users(q='Twitter API') @unittest.skip('skipping non-updated test') def test_get_contributees(self): """Test returning list of accounts the specified user can contribute to succeeds""" self.api.get_contributees(screen_name='TechCrunch') @unittest.skip('skipping non-updated test') def test_get_contributors(self): """Test returning list of accounts that contribute to the authenticated user fails because we are not a Contributor account""" self.assertRaises(TwythonError, self.api.get_contributors, screen_name=screen_name) @unittest.skip('skipping non-updated test') def test_remove_profile_banner(self): """Test removing profile banner succeeds""" self.api.remove_profile_banner() @unittest.skip('skipping non-updated test') def test_get_profile_banner_sizes(self): """Test getting list of profile banner sizes fails because we have not uploaded a profile banner""" self.assertRaises(TwythonError, self.api.get_profile_banner_sizes) # Suggested Users @unittest.skip('skipping non-updated test') def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') @unittest.skip('skipping non-updated test') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() @unittest.skip('skipping non-updated test') def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites @unittest.skip('skipping non-updated test') def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() @unittest.skip('skipping non-updated test') def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists @unittest.skip('skipping non-updated test') def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) @unittest.skip('skipping non-updated test') def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() @unittest.skip('skipping non-updated test') def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') @unittest.skip('skipping non-updated test') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches @unittest.skip('skipping non-updated test') def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() @unittest.skip('skipping non-updated test') def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo @unittest.skip('skipping non-updated test') def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') @unittest.skip('skipping non-updated test') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') @unittest.skip('skipping non-updated test') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') @unittest.skip('skipping non-updated test') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends @unittest.skip('skipping non-updated test') def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) @unittest.skip('skipping non-updated test') def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() @unittest.skip('skipping non-updated test') def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help @unittest.skip('skipping non-updated test') def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() @unittest.skip('skipping non-updated test') def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() @unittest.skip('skipping non-updated test') def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() @unittest.skip('skipping non-updated test') def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() @unittest.skip('skipping non-updated test') def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
class TwitterPlotBot(Thread): """ Blueprint for the plot bot """ def __init__(self, apiKey, apiSecret, accessToken, accessTokenSecret, \ pauseCommand, resumeCommand, plotter, stopEvent, \ targetHandle='', tweetInterval=1000, maxCnt=10, \ dm=False): """ The ctor for 'PlotBot' apiKey, apiSecret Your application's twitter accessToken auth credentials accessTokenSecret pauseEvent Toggels the tweeting stopEvent Stops the tweeting (end of application) plotter The plotter object that will be used to generate graphs targetHandle Twitter handle to be included in the tweet tweetInterval Will tweet adter every 'tweetInterval' maxCnt Maximum number of direct messages to be read dm Send a direct message? """ super(TwitterPlotBot, self).__init__() self.apiKey = apiKey self.apiSecret = apiSecret self.accessToken = accessToken self.accessTokenSecret = accessTokenSecret self.plotter = plotter self.targetHandle = targetHandle self.tweetInterval = tweetInterval #if targetHandle != "": # self.dm = dm # Do direct messaging only if we have target handle #else: # self.dm = False # Sadly image upload does not seem to work (not supported by twitter API?) # Hence direct messaging stays disabled for now self.dm = False self.api = None self.pauseCommand = pauseCommand self.resumeCommand = resumeCommand self.stopEvent = stopEvent # Try and log in to twitter self.twitter = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) # Start the DataLogger thread and make the plotter ready self.plotter.begin() self.keepTweeting = True # Flag to indicate whether we want to tweet or not self.latestTweetCheck = datetime.datetime.utcnow() # Used check for the latest DM def __tweetPlot__(self, twtStr): """ This function is directly taken from the twython doc """ photo = Image.open(self.plotter.getOutPutFileName()) basewidth = 1000 #wpercent = (basewidth / float(photo.size[0])) #height = int((float(photo.size[1]) * float(wpercent))) height = 500 photo = photo.resize((basewidth, height), Image.ANTIALIAS) image_io = StringIO.StringIO() photo.save(image_io, format='PNG') # If you do not seek(0), the image will be at the end of the file and # unable to be read image_io.seek(0) response = self.twitter.upload_media(media=image_io) if self.dm == False: self.twitter.update_status(status=twtStr, media_ids=[response['media_id']]) else: self.twitter.send_direct_message(screen_name=self.targetHandle, text = twtStr, media_ids=[response['media_id']]) def run(self): """ The thread that tweets updates periodically """ while 1: if self.stopEvent.isSet(): self.plotter.stop() return # Check if we need to tweet or not if self.targetHandle != '': # Get the personal message from the master try: msgs = self.twitter.get_direct_messages(screen_id = self.targetHandle, count=10) except Exception, ex: print "Could not receive direct messages " print str(ex) self.keepTweeting = True continue # Below code is to make sure that the tweet that we interpret is the latest if len(msgs) != 0: # Check if any of the message is latest temp = time.strptime(msgs[0]['created_at'],'%a %b %d %H:%M:%S +0000 %Y') temp = mktime(temp) tweetTime = datetime.datetime.fromtimestamp(temp) # if not, just pass if tweetTime > self.latestTweetCheck: for msg in msgs: if msg['sender']['screen_name'].find(self.targetHandle.replace('@','')) >= 0: # Tweet from the master temp = time.strptime(msg['created_at'],'%a %b %d %H:%M:%S +0000 %Y') temp = mktime(temp) tweetTime = datetime.datetime.fromtimestamp(temp) if tweetTime > self.latestTweetCheck: self.latestTweetCheck = tweetTime if msg['text'].find(self.pauseCommand) >= 0: self.keepTweeting = False print "Tweet's on hold " elif msg['text'].find(self.resumeCommand) >= 0: self.keepTweeting = True print "Tweets will be tweeted" if self.keepTweeting: self.plotter.plot() if os.path.exists(self.plotter.getOutPutFileName()): print "Tweeting........." tweet = self.targetHandle + ' ' + tweetStrs[randint(0, len(tweetStrs)-1)] try: self.__tweetPlot__(tweet) except: print "Error while tweeting...." pass else: print "Not tweeting this cycle..." time.sleep(self.tweetInterval)