Initial work to Support Tweepy 4

This commit is contained in:
Manuel Cortez 2021-09-26 03:58:25 -05:00
parent 0c27427843
commit d8fca3b31a
No known key found for this signature in database
GPG Key ID: 262CC30FA01B5CBF
17 changed files with 124 additions and 198 deletions

View File

@ -21,7 +21,7 @@ from audio_services import youtube_utils
from controller.buffers.base import base from controller.buffers.base import base
from sessions.twitter import compose, utils, reduce from sessions.twitter import compose, utils, reduce
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from tweepy.error import TweepError from tweepy.errors import TweepyException
from tweepy.cursor import Cursor from tweepy.cursor import Cursor
from pubsub import pub from pubsub import pub
from sessions.twitter.long_tweets import twishort, tweets from sessions.twitter.long_tweets import twishort, tweets
@ -140,7 +140,7 @@ class BaseBuffer(base.Buffer):
try: try:
tweet = self.session.twitter.get_status(id=tweet_id, include_ext_alt_text=True, tweet_mode="extended") tweet = self.session.twitter.get_status(id=tweet_id, include_ext_alt_text=True, tweet_mode="extended")
tweet.full_text = utils.expand_urls(tweet.full_text, tweet.entities) tweet.full_text = utils.expand_urls(tweet.full_text, tweet.entities)
except TweepError as e: except TweepyException as e:
utils.twitter_error(e) utils.twitter_error(e)
return return
if message != None: if message != None:
@ -151,7 +151,7 @@ class BaseBuffer(base.Buffer):
try: try:
tweet = self.session.twitter.get_status(id=l, include_ext_alt_text=True, tweet_mode="extended") tweet = self.session.twitter.get_status(id=l, include_ext_alt_text=True, tweet_mode="extended")
tweet.full_text = utils.expand_urls(tweet.full_text, tweet.entities) tweet.full_text = utils.expand_urls(tweet.full_text, tweet.entities)
except TweepError as e: except TweepyException as e:
utils.twitter_error(e) utils.twitter_error(e)
return return
l = tweets.is_long(tweet) l = tweets.is_long(tweet)
@ -191,7 +191,7 @@ class BaseBuffer(base.Buffer):
log.debug("Retrieved %d items from the cursored search on function %s." %(len(val), self.function)) log.debug("Retrieved %d items from the cursored search on function %s." %(len(val), self.function))
user_ids = [item.message_create["sender_id"] for item in val] user_ids = [item.message_create["sender_id"] for item in val]
self.session.save_users(user_ids) self.session.save_users(user_ids)
except TweepError as e: except TweepyException as e:
log.error("Error %s: %s" % (e.api_code, e.reason)) log.error("Error %s: %s" % (e.api_code, e.reason))
return return
number_of_items = self.session.order_buffer(self.name, val) number_of_items = self.session.order_buffer(self.name, val)
@ -229,7 +229,7 @@ class BaseBuffer(base.Buffer):
last_id = self.session.db[self.name][-1].id last_id = self.session.db[self.name][-1].id
try: try:
items = getattr(self.session.twitter, self.function)(max_id=last_id, count=self.session.settings["general"]["max_tweets_per_call"], *self.args, **self.kwargs) items = getattr(self.session.twitter, self.function)(max_id=last_id, count=self.session.settings["general"]["max_tweets_per_call"], *self.args, **self.kwargs)
except TweepError as e: except TweepyException as e:
log.error("Error %s: %s" % (e.api_code, e.reason)) log.error("Error %s: %s" % (e.api_code, e.reason))
return return
if items == None: if items == None:
@ -611,13 +611,13 @@ class BaseBuffer(base.Buffer):
items = self.session.db[self.name] items = self.session.db[self.name]
try: try:
if self.name == "direct_messages" or self.name == "sent_direct_messages": if self.name == "direct_messages" or self.name == "sent_direct_messages":
self.session.twitter.destroy_direct_message(id=self.get_right_tweet().id) self.session.twitter.delete_direct_message(id=self.get_right_tweet().id)
items.pop(index) items.pop(index)
else: else:
self.session.twitter.destroy_status(id=self.get_right_tweet().id) self.session.twitter.destroy_status(id=self.get_right_tweet().id)
items.pop(index) items.pop(index)
self.buffer.list.remove_item(index) self.buffer.list.remove_item(index)
except TweepError: except TweepyException:
self.session.sound.play("error.ogg") self.session.sound.play("error.ogg")
self.session.db[self.name] = items self.session.db[self.name] = items

View File

@ -10,7 +10,7 @@ import logging
from controller import messages from controller import messages
from sessions.twitter import compose, utils from sessions.twitter import compose, utils
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from tweepy.error import TweepError from tweepy.errors import TweepyException
from pubsub import pub from pubsub import pub
from . import base from . import base
@ -40,7 +40,7 @@ class DirectMessagesBuffer(base.BaseBuffer):
results = [i for i in items] results = [i for i in items]
items = results items = results
log.debug("Retrieved %d items for cursored search in function %s" % (len(items), self.function)) log.debug("Retrieved %d items for cursored search in function %s" % (len(items), self.function))
except TweepError as e: except TweepyException as e:
log.error("Error %s: %s" % (e.api_code, e.reason)) log.error("Error %s: %s" % (e.api_code, e.reason))
return return
if items == None: if items == None:

View File

@ -24,7 +24,7 @@ class ListBuffer(base.BaseBuffer):
super(ListBuffer, self).start_stream(mandatory, play_sound, avoid_autoreading) super(ListBuffer, self).start_stream(mandatory, play_sound, avoid_autoreading)
def get_user_ids(self): def get_user_ids(self):
for i in Cursor(self.session.twitter.list_members, list_id=self.list_id, include_entities=False, skip_status=True, count=5000).items(): for i in Cursor(self.session.twitter.get_list_members, list_id=self.list_id, include_entities=False, skip_status=True, count=5000).items():
if i.id not in self.users: if i.id not in self.users:
self.users.append(i.id) self.users.append(i.id)

View File

@ -14,7 +14,7 @@ import output
import config import config
import logging import logging
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from tweepy.error import TweepError from tweepy.errors import TweepyException
from pubsub import pub from pubsub import pub
from sessions.twitter import compose from sessions.twitter import compose
from . import base from . import base
@ -125,7 +125,7 @@ class PeopleBuffer(base.BaseBuffer):
val = results val = results
val.reverse() val.reverse()
log.debug("Retrieved %d items from cursored search in function %s" % (len(val), self.function)) log.debug("Retrieved %d items from cursored search in function %s" % (len(val), self.function))
except TweepError as e: except TweepyException as e:
log.error("Error %s: %s" % (e.api_code, e.reason)) log.error("Error %s: %s" % (e.api_code, e.reason))
return return
number_of_items = self.session.order_people(self.name, val) number_of_items = self.session.order_people(self.name, val)
@ -155,7 +155,7 @@ class PeopleBuffer(base.BaseBuffer):
results = [i for i in items] results = [i for i in items]
items = results items = results
log.debug("Retrieved %d items from cursored search in function %s" % (len(items), self.function)) log.debug("Retrieved %d items from cursored search in function %s" % (len(items), self.function))
except TweepError as e: except TweepyException as e:
log.error("Error %s: %s" % (e.api_code, e.reason)) log.error("Error %s: %s" % (e.api_code, e.reason))
return return
if items == None: if items == None:

View File

@ -13,17 +13,17 @@ import widgetUtils
import output import output
import logging import logging
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from tweepy.error import TweepError from tweepy.errors import TweepyException
from pubsub import pub from pubsub import pub
from controller.buffers import base from controller.buffers import base
log = logging.getLogger("controller.buffers.twitter.trends") log = logging.getLogger("controller.buffers.twitter.trends")
class TrendsBuffer(base.Buffer): class TrendsBuffer(base.Buffer):
def __init__(self, parent, name, session, account, trendsFor, *args, **kwargs): def __init__(self, parent, name, sessionObject, account, trendsFor, *args, **kwargs):
super(TrendsBuffer, self).__init__(parent=parent, session=session) super(TrendsBuffer, self).__init__(parent=parent, sessionObject=sessionObject)
self.trendsFor = trendsFor self.trendsFor = trendsFor
self.session = session self.session = sessionObject
self.account = account self.account = account
self.invisible = True self.invisible = True
self.buffer = buffers.trendsPanel(parent, name) self.buffer = buffers.trendsPanel(parent, name)
@ -44,8 +44,8 @@ class TrendsBuffer(base.Buffer):
if self.execution_time == 0 or current_time-self.execution_time >= 180 or mandatory == True: if self.execution_time == 0 or current_time-self.execution_time >= 180 or mandatory == True:
self.execution_time = current_time self.execution_time = current_time
try: try:
data = self.session.twitter.trends_place(id=self.trendsFor) data = self.session.twitter.get_place_trends(id=self.trendsFor)
except TweepError as err: except TweepyException as err:
log.error("Error %s: %s" % (err.api_code, err.reason)) log.error("Error %s: %s" % (err.api_code, err.reason))
if not hasattr(self, "name_"): if not hasattr(self, "name_"):
self.name_ = data[0]["locations"][0]["name"] self.name_ = data[0]["locations"][0]["name"]

View File

@ -3,7 +3,7 @@ import widgetUtils
import output import output
import logging import logging
from wxUI.dialogs import lists from wxUI.dialogs import lists
from tweepy.error import TweepError from tweepy.errors import TweepyException
from sessions.twitter import compose, utils from sessions.twitter import compose, utils
from pubsub import pub from pubsub import pub
@ -49,7 +49,7 @@ class listsController(object):
new_list = self.session.twitter.create_list(name=name, description=description, mode=mode) new_list = self.session.twitter.create_list(name=name, description=description, mode=mode)
self.session.db["lists"].append(new_list) self.session.db["lists"].append(new_list)
self.dialog.lista.insert_item(False, *compose.compose_list(new_list)) self.dialog.lista.insert_item(False, *compose.compose_list(new_list))
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
log.exception("error %s: %s" % (e.api_code, e.reason)) log.exception("error %s: %s" % (e.api_code, e.reason))
dialog.destroy() dialog.destroy()
@ -70,7 +70,7 @@ class listsController(object):
self.session.twitter.update_list(list_id=list.id, name=name, description=description, mode=mode) self.session.twitter.update_list(list_id=list.id, name=name, description=description, mode=mode)
self.session.get_lists() self.session.get_lists()
self.dialog.populate_list(self.get_all_lists(), True) self.dialog.populate_list(self.get_all_lists(), True)
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
dialog.destroy() dialog.destroy()
@ -82,7 +82,7 @@ class listsController(object):
self.session.twitter.destroy_list(list_id=list) self.session.twitter.destroy_list(list_id=list)
self.session.db["lists"].pop(self.dialog.get_item()) self.session.db["lists"].pop(self.dialog.get_item())
self.dialog.lista.remove_item(self.dialog.get_item()) self.dialog.lista.remove_item(self.dialog.get_item())
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
def open_list_as_buffer(self, *args, **kwargs): def open_list_as_buffer(self, *args, **kwargs):
@ -97,7 +97,7 @@ class listsController(object):
list = self.session.twitter.subscribe_list(list_id=list_id) list = self.session.twitter.subscribe_list(list_id=list_id)
item = utils.find_item(list.id, self.session.db["lists"]) item = utils.find_item(list.id, self.session.db["lists"])
self.session.db["lists"].append(list) self.session.db["lists"].append(list)
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
def unsubscribe(self, *args, **kwargs): def unsubscribe(self, *args, **kwargs):
@ -106,5 +106,5 @@ class listsController(object):
try: try:
list = self.session.twitter.unsubscribe_list(list_id=list_id) list = self.session.twitter.unsubscribe_list(list_id=list_id)
self.session.db["lists"].remove(list) self.session.db["lists"].remove(list)
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))

View File

@ -29,7 +29,7 @@ from sessions.twitter import session as session_
from pubsub import pub from pubsub import pub
import sound import sound
import output import output
from tweepy.error import TweepError from tweepy.errors import TweepyException
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from mysc.repeating_timer import RepeatingTimer from mysc.repeating_timer import RepeatingTimer
from mysc import restart from mysc import restart
@ -335,21 +335,21 @@ class Controller(object):
elif i == 'mentions': elif i == 'mentions':
pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Mentions"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="mentions_timeline", name="mentions", sessionObject=session, account=session.db["user_name"], sound="mention_received.ogg", tweet_mode="extended")) pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Mentions"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="mentions_timeline", name="mentions", sessionObject=session, account=session.db["user_name"], sound="mention_received.ogg", tweet_mode="extended"))
elif i == 'dm': elif i == 'dm':
pub.sendMessage("createBuffer", buffer_type="DirectMessagesBuffer", session_type=session.type, buffer_title=_("Direct messages"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="list_direct_messages", name="direct_messages", sessionObject=session, account=session.db["user_name"], bufferType="dmPanel", compose_func="compose_direct_message", sound="dm_received.ogg")) pub.sendMessage("createBuffer", buffer_type="DirectMessagesBuffer", session_type=session.type, buffer_title=_("Direct messages"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_direct_messages", name="direct_messages", sessionObject=session, account=session.db["user_name"], bufferType="dmPanel", compose_func="compose_direct_message", sound="dm_received.ogg"))
elif i == 'sent_dm': elif i == 'sent_dm':
pub.sendMessage("createBuffer", buffer_type="SentDirectMessagesBuffer", session_type=session.type, buffer_title=_("Sent direct messages"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function=None, name="sent_direct_messages", sessionObject=session, account=session.db["user_name"], bufferType="dmPanel", compose_func="compose_direct_message")) pub.sendMessage("createBuffer", buffer_type="SentDirectMessagesBuffer", session_type=session.type, buffer_title=_("Sent direct messages"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function=None, name="sent_direct_messages", sessionObject=session, account=session.db["user_name"], bufferType="dmPanel", compose_func="compose_direct_message"))
elif i == 'sent_tweets': elif i == 'sent_tweets':
pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Sent tweets"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="user_timeline", name="sent_tweets", sessionObject=session, account=session.db["user_name"], screen_name=session.db["user_name"], tweet_mode="extended")) pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Sent tweets"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="user_timeline", name="sent_tweets", sessionObject=session, account=session.db["user_name"], screen_name=session.db["user_name"], tweet_mode="extended"))
elif i == 'favorites': elif i == 'favorites':
pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Likes"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="favorites", name="favourites", sessionObject=session, account=session.db["user_name"], sound="favourite.ogg", tweet_mode="extended")) pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Likes"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_favorites", name="favourites", sessionObject=session, account=session.db["user_name"], sound="favourite.ogg", tweet_mode="extended"))
elif i == 'followers': elif i == 'followers':
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Followers"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="followers", name="followers", sessionObject=session, account=session.db["user_name"], sound="update_followers.ogg", screen_name=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Followers"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_followers", name="followers", sessionObject=session, account=session.db["user_name"], sound="update_followers.ogg", screen_name=session.db["user_name"]))
elif i == 'friends': elif i == 'friends':
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Following"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="friends", name="friends", sessionObject=session, account=session.db["user_name"], screen_name=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Following"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_friends", name="friends", sessionObject=session, account=session.db["user_name"], screen_name=session.db["user_name"]))
elif i == 'blocks': elif i == 'blocks':
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Blocked users"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="blocks", name="blocked", sessionObject=session, account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Blocked users"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_blocks", name="blocked", sessionObject=session, account=session.db["user_name"]))
elif i == 'muted': elif i == 'muted':
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Muted users"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="mutes", name="muted", sessionObject=session, account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Muted users"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, function="get_mutes", name="muted", sessionObject=session, account=session.db["user_name"]))
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="timelines", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="timelines", account=session.db["user_name"]))
timelines_position =self.view.search("timelines", session.db["user_name"]) timelines_position =self.view.search("timelines", session.db["user_name"])
for i in session.settings["other_buffers"]["timelines"]: for i in session.settings["other_buffers"]["timelines"]:
@ -357,15 +357,15 @@ class Controller(object):
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Likes timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="favs_timelines", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Likes timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="favs_timelines", account=session.db["user_name"]))
favs_timelines_position =self.view.search("favs_timelines", session.db["user_name"]) favs_timelines_position =self.view.search("favs_timelines", session.db["user_name"])
for i in session.settings["other_buffers"]["favourites_timelines"]: for i in session.settings["other_buffers"]["favourites_timelines"]:
pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Likes for {}").format(i,), parent_tab=favs_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="favorites", name="%s-favorite" % (i,), sessionObject=session, account=session.db["user_name"], bufferType=None, sound="favourites_timeline_updated.ogg", user_id=i, tweet_mode="extended")) pub.sendMessage("createBuffer", buffer_type="BaseBuffer", session_type=session.type, buffer_title=_("Likes for {}").format(i,), parent_tab=favs_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="get_favorites", name="%s-favorite" % (i,), sessionObject=session, account=session.db["user_name"], bufferType=None, sound="favourites_timeline_updated.ogg", user_id=i, tweet_mode="extended"))
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Followers timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="followers_timelines", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Followers timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="followers_timelines", account=session.db["user_name"]))
followers_timelines_position =self.view.search("followers_timelines", session.db["user_name"]) followers_timelines_position =self.view.search("followers_timelines", session.db["user_name"])
for i in session.settings["other_buffers"]["followers_timelines"]: for i in session.settings["other_buffers"]["followers_timelines"]:
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Followers for {}").format(i,), parent_tab=followers_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="followers", name="%s-followers" % (i,), sessionObject=session, account=session.db["user_name"], sound="new_event.ogg", user_id=i)) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_("Followers for {}").format(i,), parent_tab=followers_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="get_followers", name="%s-followers" % (i,), sessionObject=session, account=session.db["user_name"], sound="new_event.ogg", user_id=i))
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Following timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="friends_timelines", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Following timelines"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="friends_timelines", account=session.db["user_name"]))
friends_timelines_position =self.view.search("friends_timelines", session.db["user_name"]) friends_timelines_position =self.view.search("friends_timelines", session.db["user_name"])
for i in session.settings["other_buffers"]["friends_timelines"]: for i in session.settings["other_buffers"]["friends_timelines"]:
pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_(u"Friends for {}").format(i,), parent_tab=friends_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="friends", name="%s-friends" % (i,), sessionObject=session, account=session.db["user_name"], sound="new_event.ogg", user_id=i)) pub.sendMessage("createBuffer", buffer_type="PeopleBuffer", session_type=session.type, buffer_title=_(u"Friends for {}").format(i,), parent_tab=friends_timelines_position, start=False, kwargs=dict(parent=self.view.nb, function="get_friends", name="%s-friends" % (i,), sessionObject=session, account=session.db["user_name"], sound="new_event.ogg", user_id=i))
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Lists"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="lists", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Lists"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="lists", account=session.db["user_name"]))
lists_position =self.view.search("lists", session.db["user_name"]) lists_position =self.view.search("lists", session.db["user_name"])
for i in session.settings["other_buffers"]["lists"]: for i in session.settings["other_buffers"]["lists"]:
@ -373,9 +373,9 @@ class Controller(object):
pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Searches"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="searches", account=session.db["user_name"])) pub.sendMessage("createBuffer", buffer_type="EmptyBuffer", session_type="base", buffer_title=_("Searches"), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="searches", account=session.db["user_name"]))
searches_position =self.view.search("searches", session.db["user_name"]) searches_position =self.view.search("searches", session.db["user_name"])
for i in session.settings["other_buffers"]["tweet_searches"]: for i in session.settings["other_buffers"]["tweet_searches"]:
pub.sendMessage("createBuffer", buffer_type="SearchBuffer", session_type=session.type, buffer_title=_(u"Search for {}").format(i), parent_tab=searches_position, start=False, kwargs=dict(parent=self.view.nb, function="search", name="%s-searchterm" % (i,), sessionObject=session, account=session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", q=i, tweet_mode="extended")) pub.sendMessage("createBuffer", buffer_type="SearchBuffer", session_type=session.type, buffer_title=_(u"Search for {}").format(i), parent_tab=searches_position, start=False, kwargs=dict(parent=self.view.nb, function="search_tweets", name="%s-searchterm" % (i,), sessionObject=session, account=session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", q=i, tweet_mode="extended"))
for i in session.settings["other_buffers"]["trending_topic_buffers"]: for i in session.settings["other_buffers"]["trending_topic_buffers"]:
pub.sendMessage("createBuffer", buffer_type="TrendsBuffer", session_type=session.type, buffer_title=_("Trending topics for %s") % (buffer.name_), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="%s_tt" % (i,), sessionObject=session, account=session.db["user_name"], trendsFor=i, sound="trends_updated.ogg")) pub.sendMessage("createBuffer", buffer_type="TrendsBuffer", session_type=session.type, buffer_title=_("Trending topics for %s") % (i), parent_tab=root_position, start=False, kwargs=dict(parent=self.view.nb, name="%s_tt" % (i,), sessionObject=session, account=session.db["user_name"], trendsFor=i, sound="trends_updated.ogg"))
def set_buffer_positions(self, session): def set_buffer_positions(self, session):
"Sets positions for buffers if values exist in the database." "Sets positions for buffers if values exist in the database."
@ -420,7 +420,7 @@ class Controller(object):
buffer.session.settings["other_buffers"]["tweet_searches"].append(term) buffer.session.settings["other_buffers"]["tweet_searches"].append(term)
buffer.session.settings.write() buffer.session.settings.write()
args = {"lang": dlg.get_language(), "result_type": dlg.get_result_type()} args = {"lang": dlg.get_language(), "result_type": dlg.get_result_type()}
pub.sendMessage("createBuffer", buffer_type="SearchBuffer", session_type=buffer.session.type, buffer_title=_("Search for {}").format(term), parent_tab=searches_position, start=True, kwargs=dict(parent=self.view.nb, function="search", name="%s-searchterm" % (term,), sessionObject=buffer.session, account=buffer.session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", q=term, tweet_mode="extended", **args)) pub.sendMessage("createBuffer", buffer_type="SearchBuffer", session_type=buffer.session.type, buffer_title=_("Search for {}").format(term), parent_tab=searches_position, start=True, kwargs=dict(parent=self.view.nb, function="search_tweets", name="%s-searchterm" % (term,), sessionObject=buffer.session, account=buffer.session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", q=term, tweet_mode="extended", **args))
else: else:
log.error("A buffer for the %s search term is already created. You can't create a duplicate buffer." % (term,)) log.error("A buffer for the %s search term is already created. You can't create a duplicate buffer." % (term,))
return return
@ -548,7 +548,7 @@ class Controller(object):
if listBuffer != None: listBuffer.get_user_ids() if listBuffer != None: listBuffer.get_user_ids()
buff.session.db["lists"].pop(older_list) buff.session.db["lists"].pop(older_list)
buff.session.db["lists"].append(list) buff.session.db["lists"].append(list)
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
def remove_from_list(self, *args, **kwargs): def remove_from_list(self, *args, **kwargs):
@ -576,7 +576,7 @@ class Controller(object):
if listBuffer != None: listBuffer.get_user_ids() if listBuffer != None: listBuffer.get_user_ids()
buff.session.db["lists"].pop(older_list) buff.session.db["lists"].pop(older_list)
buff.session.db["lists"].append(list) buff.session.db["lists"].append(list)
except TweepError as e: except TweepyException as e:
output.speak("error %s: %s" % (e.api_code, e.reason)) output.speak("error %s: %s" % (e.api_code, e.reason))
def list_manager(self, *args, **kwargs): def list_manager(self, *args, **kwargs):
@ -745,7 +745,7 @@ class Controller(object):
users = [buff.session.get_user(tweet.message_create["sender_id"]).screen_name] users = [buff.session.get_user(tweet.message_create["sender_id"]).screen_name]
else: else:
users = utils.get_all_users(tweet, buff.session) users = utils.get_all_users(tweet, buff.session)
dlg = dialogs.utils.addAliasDialog(_("Add an user alias"), users) dlg = dialogs.userAliasDialogs.addAliasDialog(_("Add an user alias"), users)
if dlg.get_response() == widgetUtils.OK: if dlg.get_response() == widgetUtils.OK:
user, alias = dlg.get_user() user, alias = dlg.get_user()
if user == "" or alias == "": if user == "" or alias == "":
@ -881,7 +881,7 @@ class Controller(object):
if usr.id_str in buff.session.settings["other_buffers"]["favourites_timelines"]: if usr.id_str in buff.session.settings["other_buffers"]["favourites_timelines"]:
commonMessageDialogs.timeline_exist() commonMessageDialogs.timeline_exist()
return return
tl = buffers.twitter.BaseBuffer(self.view.nb, "favorites", "%s-favorite" % (usr.id_str,), buff.session, buff.session.db["user_name"], bufferType=None, sound="favourites_timeline_updated.ogg", user_id=usr.id_str, tweet_mode="extended") tl = buffers.twitter.BaseBuffer(self.view.nb, "get_favorites", "%s-favorite" % (usr.id_str,), buff.session, buff.session.db["user_name"], bufferType=None, sound="favourites_timeline_updated.ogg", user_id=usr.id_str, tweet_mode="extended")
try: try:
tl.start_stream(play_sound=False) tl.start_stream(play_sound=False)
except ValueError: except ValueError:
@ -900,7 +900,7 @@ class Controller(object):
if usr.id_str in buff.session.settings["other_buffers"]["followers_timelines"]: if usr.id_str in buff.session.settings["other_buffers"]["followers_timelines"]:
commonMessageDialogs.timeline_exist() commonMessageDialogs.timeline_exist()
return return
tl = buffers.twitter.PeopleBuffer(self.view.nb, "followers", "%s-followers" % (usr.id_str,), buff.session, buff.session.db["user_name"], sound="new_event.ogg", user_id=usr.id_str) tl = buffers.twitter.PeopleBuffer(self.view.nb, "get_followers", "%s-followers" % (usr.id_str,), buff.session, buff.session.db["user_name"], sound="new_event.ogg", user_id=usr.id_str)
try: try:
tl.start_stream(play_sound=False) tl.start_stream(play_sound=False)
except ValueError: except ValueError:
@ -919,7 +919,7 @@ class Controller(object):
if usr.id_str in buff.session.settings["other_buffers"]["friends_timelines"]: if usr.id_str in buff.session.settings["other_buffers"]["friends_timelines"]:
commonMessageDialogs.timeline_exist() commonMessageDialogs.timeline_exist()
return return
tl = buffers.twitter.PeopleBuffer(self.view.nb, "friends", "%s-friends" % (usr.id_str,), buff.session, buff.session.db["user_name"], sound="new_event.ogg", user_id=usr.id_str) tl = buffers.twitter.PeopleBuffer(self.view.nb, "get_friends", "%s-friends" % (usr.id_str,), buff.session, buff.session.db["user_name"], sound="new_event.ogg", user_id=usr.id_str)
try: try:
tl.start_stream(play_sound=False) tl.start_stream(play_sound=False)
except ValueError: except ValueError:
@ -939,7 +939,7 @@ class Controller(object):
buffer = self.get_current_buffer() buffer = self.get_current_buffer()
id = buffer.get_right_tweet().id id = buffer.get_right_tweet().id
user = buffer.session.get_user(buffer.get_right_tweet().user).screen_name user = buffer.session.get_user(buffer.get_right_tweet().user).screen_name
search = buffers.twitter.ConversationBuffer(self.view.nb, "search", "%s-searchterm" % (id,), buffer.session, buffer.session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", since_id=id, q="@{0}".format(user,)) search = buffers.twitter.ConversationBuffer(self.view.nb, "search_tweets", "%s-searchterm" % (id,), buffer.session, buffer.session.db["user_name"], bufferType="searchPanel", sound="search_updated.ogg", since_id=id, q="@{0}".format(user,))
search.tweet = buffer.get_right_tweet() search.tweet = buffer.get_right_tweet()
search.start_stream(start=True) search.start_stream(start=True)
pos=self.view.search("searches", buffer.session.db["user_name"]) pos=self.view.search("searches", buffer.session.db["user_name"])
@ -1341,7 +1341,7 @@ class Controller(object):
i.start_stream() i.start_stream()
else: else:
i.start_stream(play_sound=False) i.start_stream(play_sound=False)
except TweepError as err: except TweepyException as err:
log.exception("Error %s starting buffer %s on account %s, with args %r and kwargs %r due to the following reason: %s" % (err.api_code, i.name, i.account, i.args, i.kwargs, err.reason)) log.exception("Error %s starting buffer %s on account %s, with args %r and kwargs %r due to the following reason: %s" % (err.api_code, i.name, i.account, i.args, i.kwargs, err.reason))
# Determine if this error was caused by a block applied to the current user (IE permission errors). # Determine if this error was caused by a block applied to the current user (IE permission errors).
errors_allowed = [130] errors_allowed = [130]
@ -1369,34 +1369,34 @@ class Controller(object):
try: try:
if sessions.sessions[i].is_logged == False: continue if sessions.sessions[i].is_logged == False: continue
sessions.sessions[i].check_connection() sessions.sessions[i].check_connection()
except TweepError: # We shouldn't allow this function to die. except TweepyException: # We shouldn't allow this function to die.
pass pass
def create_new_buffer(self, buffer, account, create): def create_new_buffer(self, buffer, account, create):
buff = self.search_buffer("home_timeline", account) buff = self.search_buffer("home_timeline", account)
if create == True: if create == True:
if buffer == "favourites": if buffer == "favourites":
favourites = buffers.twitter.BaseBuffer(self.view.nb, "favorites", "favourites", buff.session, buff.session.db["user_name"], tweet_mode="extended") favourites = buffers.twitter.BaseBuffer(self.view.nb, "get_favorites", "favourites", buff.session, buff.session.db["user_name"], tweet_mode="extended")
self.buffers.append(favourites) self.buffers.append(favourites)
self.view.insert_buffer(favourites.buffer, name=_(u"Likes"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"])) self.view.insert_buffer(favourites.buffer, name=_(u"Likes"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"]))
favourites.start_stream(play_sound=False) favourites.start_stream(play_sound=False)
if buffer == "followers": if buffer == "followers":
followers = buffers.twitter.PeopleBuffer(self.view.nb, "followers", "followers", buff.session, buff.session.db["user_name"], screen_name=buff.session.db["user_name"]) followers = buffers.twitter.PeopleBuffer(self.view.nb, "get_followers", "followers", buff.session, buff.session.db["user_name"], screen_name=buff.session.db["user_name"])
self.buffers.append(followers) self.buffers.append(followers)
self.view.insert_buffer(followers.buffer, name=_(u"Followers"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"])) self.view.insert_buffer(followers.buffer, name=_(u"Followers"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"]))
followers.start_stream(play_sound=False) followers.start_stream(play_sound=False)
elif buffer == "friends": elif buffer == "friends":
friends = buffers.twitter.PeopleBuffer(self.view.nb, "friends", "friends", buff.session, buff.session.db["user_name"], screen_name=buff.session.db["user_name"]) friends = buffers.twitter.PeopleBuffer(self.view.nb, "get_friends", "friends", buff.session, buff.session.db["user_name"], screen_name=buff.session.db["user_name"])
self.buffers.append(friends) self.buffers.append(friends)
self.view.insert_buffer(friends.buffer, name=_(u"Friends"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"])) self.view.insert_buffer(friends.buffer, name=_(u"Friends"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"]))
friends.start_stream(play_sound=False) friends.start_stream(play_sound=False)
elif buffer == "blocked": elif buffer == "blocked":
blocks = buffers.twitter.PeopleBuffer(self.view.nb, "blocks", "blocked", buff.session, buff.session.db["user_name"]) blocks = buffers.twitter.PeopleBuffer(self.view.nb, "get_blocks", "blocked", buff.session, buff.session.db["user_name"])
self.buffers.append(blocks) self.buffers.append(blocks)
self.view.insert_buffer(blocks.buffer, name=_(u"Blocked users"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"])) self.view.insert_buffer(blocks.buffer, name=_(u"Blocked users"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"]))
blocks.start_stream(play_sound=False) blocks.start_stream(play_sound=False)
elif buffer == "muted": elif buffer == "muted":
muted = buffers.twitter.PeopleBuffer(self.view.nb, "mutes", "muted", buff.session, buff.session.db["user_name"]) muted = buffers.twitter.PeopleBuffer(self.view.nb, "get_mutes", "muted", buff.session, buff.session.db["user_name"])
self.buffers.append(muted) self.buffers.append(muted)
self.view.insert_buffer(muted.buffer, name=_(u"Muted users"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"])) self.view.insert_buffer(muted.buffer, name=_(u"Muted users"), pos=self.view.search(buff.session.db["user_name"], buff.session.db["user_name"]))
muted.start_stream(play_sound=False) muted.start_stream(play_sound=False)
@ -1547,7 +1547,7 @@ class Controller(object):
if i.session != None and i.session.is_logged == True: if i.session != None and i.session.is_logged == True:
try: try:
i.start_stream(mandatory=True) i.start_stream(mandatory=True)
except TweepError as err: except TweepyException as err:
log.exception("Error %s starting buffer %s on account %s, with args %r and kwargs %r due to the following reason: %s" % (err.api_code, i.name, i.account, i.args, i.kwargs, err.reason)) log.exception("Error %s starting buffer %s on account %s, with args %r and kwargs %r due to the following reason: %s" % (err.api_code, i.name, i.account, i.args, i.kwargs, err.reason))
# Determine if this error was caused by a block applied to the current user (IE permission errors). # Determine if this error was caused by a block applied to the current user (IE permission errors).
errors_allowed = [130] errors_allowed = [130]
@ -1657,5 +1657,5 @@ class Controller(object):
try: try:
if sessions.sessions[i].is_logged == False: continue if sessions.sessions[i].is_logged == False: continue
sessions.sessions[i].check_streams() sessions.sessions[i].check_streams()
except TweepError: # We shouldn't allow this function to die. except TweepyException: # We shouldn't allow this function to die.
pass pass

View File

@ -8,7 +8,7 @@ class trendingTopicsController(object):
self.countries = {} self.countries = {}
self.cities = {} self.cities = {}
self.dialog = trends.trendingTopicsDialog() self.dialog = trends.trendingTopicsDialog()
self.information = session.twitter.trends_available() self.information = session.twitter.available_trends()
self.split_information() self.split_information()
widgetUtils.connect_event(self.dialog.country, widgetUtils.RADIOBUTTON, self.get_places) widgetUtils.connect_event(self.dialog.country, widgetUtils.RADIOBUTTON, self.get_places)
widgetUtils.connect_event(self.dialog.city, widgetUtils.RADIOBUTTON, self.get_places) widgetUtils.connect_event(self.dialog.city, widgetUtils.RADIOBUTTON, self.get_places)

View File

@ -6,7 +6,7 @@ import output
from wxUI.dialogs import update_profile, show_user from wxUI.dialogs import update_profile, show_user
import logging import logging
log = logging.getLogger("controller.user") log = logging.getLogger("controller.user")
from tweepy.error import TweepError from tweepy.errors import TweepyException
from sessions.twitter import utils from sessions.twitter import utils
class profileController(object): class profileController(object):
@ -24,7 +24,7 @@ class profileController(object):
else: else:
try: try:
self.get_data(screen_name=self.user) self.get_data(screen_name=self.user)
except TweepError as err: except TweepyException as err:
if err.api_code == 50: if err.api_code == 50:
wx.MessageDialog(None, _(u"That user does not exist"), _(u"Error"), wx.ICON_ERROR).ShowModal() wx.MessageDialog(None, _(u"That user does not exist"), _(u"Error"), wx.ICON_ERROR).ShowModal()
if err.api_code == 63: if err.api_code == 63:
@ -44,7 +44,7 @@ class profileController(object):
def get_data(self, screen_name): def get_data(self, screen_name):
self.data = self.session.twitter.get_user(screen_name=screen_name) self.data = self.session.twitter.get_user(screen_name=screen_name)
if screen_name != self.session.db["user_name"]: if screen_name != self.session.db["user_name"]:
self.friendship_status = self.session.twitter.show_friendship(source_screen_name=self.session.db["user_name"], target_screen_name=screen_name) self.friendship_status = self.session.twitter.get_friendship(source_screen_name=self.session.db["user_name"], target_screen_name=screen_name)
def fill_profile_fields(self): def fill_profile_fields(self):
self.dialog.set_name(self.data.name) self.dialog.set_name(self.data.name)
@ -83,11 +83,11 @@ class profileController(object):
if self.file != None: if self.file != None:
try: try:
self.session.twitter.update_profile_image(image=self.file) self.session.twitter.update_profile_image(image=self.file)
except TweepError as e: except TweepyException as e:
output.speak(u"Error %s. %s" % (e.api_code, e.reason)) output.speak(u"Error %s. %s" % (e.api_code, e.reason))
try: try:
self.session.twitter.update_profile(name=name, description=description, location=location, url=url) self.session.twitter.update_profile(name=name, description=description, location=location, url=url)
except TweepError as e: except TweepyException as e:
output.speak(u"Error %s. %s" % (e.api_code, e.reason)) output.speak(u"Error %s. %s" % (e.api_code, e.reason))
def get_user_info(self): def get_user_info(self):

View File

@ -3,7 +3,7 @@ import widgetUtils
import output import output
from wxUI.dialogs import userActions from wxUI.dialogs import userActions
from pubsub import pub from pubsub import pub
from tweepy.error import TweepError from tweepy.errors import TweepyException
from extra import autocompletionUsers from extra import autocompletionUsers
class userActionsController(object): class userActionsController(object):
@ -29,43 +29,43 @@ class userActionsController(object):
def follow(self, user): def follow(self, user):
try: try:
self.session.twitter.create_friendship(screen_name=user ) self.session.twitter.create_friendship(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def unfollow(self, user): def unfollow(self, user):
try: try:
id = self.session.twitter.destroy_friendship(screen_name=user ) id = self.session.twitter.destroy_friendship(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def mute(self, user): def mute(self, user):
try: try:
id = self.session.twitter.create_mute(screen_name=user ) id = self.session.twitter.create_mute(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def unmute(self, user): def unmute(self, user):
try: try:
id = self.session.twitter.destroy_mute(screen_name=user ) id = self.session.twitter.destroy_mute(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def report(self, user): def report(self, user):
try: try:
id = self.session.twitter.report_spam(screen_name=user ) id = self.session.twitter.report_spam(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def block(self, user): def block(self, user):
try: try:
id = self.session.twitter.create_block(screen_name=user ) id = self.session.twitter.create_block(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def unblock(self, user): def unblock(self, user):
try: try:
id = self.session.twitter.destroy_block(screen_name=user ) id = self.session.twitter.destroy_block(screen_name=user )
except TweepError as err: except TweepyException as err:
output.speak("Error %s: %s" % (err.api_code, err.reason), True) output.speak("Error %s: %s" % (err.api_code, err.reason), True)
def ignore_client(self, user): def ignore_client(self, user):

View File

@ -17,7 +17,7 @@ from sessions.twitter import session
from . import manager from . import manager
import config_utils import config_utils
import config import config
from tweepy.error import TweepError from tweepy.errors import TweepyException
log = logging.getLogger("sessionmanager.sessionManager") log = logging.getLogger("sessionmanager.sessionManager")
class sessionManagerController(object): class sessionManagerController(object):
@ -83,7 +83,7 @@ class sessionManagerController(object):
if i not in config.app["sessions"]["ignored_sessions"]: if i not in config.app["sessions"]["ignored_sessions"]:
try: try:
s.login() s.login()
except TweepError: except TweepyException:
self.show_auth_error(s.settings["twitter"]["user_name"]) self.show_auth_error(s.settings["twitter"]["user_name"])
continue continue
sessions.sessions[i] = s sessions.sessions[i] = s

View File

@ -10,7 +10,7 @@ import output
import application import application
from pubsub import pub from pubsub import pub
import tweepy import tweepy
from tweepy.error import TweepError from tweepy.errors import TweepyException
from tweepy.models import User as UserModel from tweepy.models import User as UserModel
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
from keys import keyring from keys import keyring
@ -199,7 +199,7 @@ class Session(base.baseSession):
try: try:
val = getattr(self.twitter, call_name)(*args, **kwargs) val = getattr(self.twitter, call_name)(*args, **kwargs)
finished = True finished = True
except TweepError as e: except TweepyException as e:
output.speak(e.reason) output.speak(e.reason)
val = None val = None
if e.error_code != 403 and e.error_code != 404: if e.error_code != 403 and e.error_code != 404:
@ -218,7 +218,7 @@ class Session(base.baseSession):
def search(self, name, *args, **kwargs): def search(self, name, *args, **kwargs):
""" Search in twitter, passing args and kwargs as arguments to the Twython function.""" """ Search in twitter, passing args and kwargs as arguments to the Twython function."""
tl = self.twitter.search(*args, **kwargs) tl = self.twitter.search_tweets(*args, **kwargs)
tl.reverse() tl.reverse()
return tl return tl
@ -271,12 +271,12 @@ class Session(base.baseSession):
# @_require_login # @_require_login
def get_lists(self): def get_lists(self):
""" Gets the lists that the user is subscribed to and stores them in the database. Returns None.""" """ Gets the lists that the user is subscribed to and stores them in the database. Returns None."""
self.db["lists"] = self.twitter.lists_all(reverse=True) self.db["lists"] = self.twitter.get_lists(reverse=True)
# @_require_login # @_require_login
def get_muted_users(self): def get_muted_users(self):
""" Gets muted users (oh really?).""" """ Gets muted users (oh really?)."""
self.db["muted_users"] = self.twitter.mutes_ids() self.db["muted_users"] = self.twitter.get_muted_ids()
# @_require_login # @_require_login
def get_stream(self, name, function, *args, **kwargs): def get_stream(self, name, function, *args, **kwargs):
@ -417,7 +417,7 @@ class Session(base.baseSession):
log.debug("Requesting user id {} as it is not present in the users database.".format(id)) log.debug("Requesting user id {} as it is not present in the users database.".format(id))
try: try:
user = self.twitter.get_user(id=id) user = self.twitter.get_user(id=id)
except TweepError as err: except TweepyException as err:
user = UserModel(None) user = UserModel(None)
user.screen_name = "deleted_user" user.screen_name = "deleted_user"
user.id = id user.id = id
@ -483,13 +483,13 @@ class Session(base.baseSession):
return return
log.debug("TWBlue will get %d new users from Twitter." % (len(users_to_retrieve))) log.debug("TWBlue will get %d new users from Twitter." % (len(users_to_retrieve)))
try: try:
users = self.twitter.lookup_users(user_ids=users_to_retrieve, tweet_mode="extended") users = self.twitter.lookup_users(user_id=users_to_retrieve, tweet_mode="extended")
users_db = self.db["users"] users_db = self.db["users"]
for user in users: for user in users:
users_db[user.id_str] = user users_db[user.id_str] = user
log.debug("Added %d new users" % (len(users))) log.debug("Added %d new users" % (len(users)))
self.db["users"] = users_db self.db["users"] = users_db
except TweepError as err: except TweepyException as err:
if hasattr(err, "api_code") and err.api_code == 17: # Users not found. if hasattr(err, "api_code") and err.api_code == 17: # Users not found.
log.error("The specified users {} were not found in twitter.".format(user_ids)) log.error("The specified users {} were not found in twitter.".format(user_ids))
# Creates a deleted user object for every user_id not found here. # Creates a deleted user object for every user_id not found here.
@ -523,9 +523,8 @@ class Session(base.baseSession):
def start_streaming(self): def start_streaming(self):
if config.app["app-settings"]["no_streaming"]: if config.app["app-settings"]["no_streaming"]:
return return
self.stream_listener = streaming.StreamListener(twitter_api=self.twitter, user=self.db["user_name"], user_id=self.db["user_id"], muted_users=self.db["muted_users"]) self.stream = streaming.Stream(twitter_api=self.twitter, user=self.db["user_name"], user_id=self.db["user_id"], muted_users=self.db["muted_users"], consumer_key=keyring.get("api_key"), consumer_secret=keyring.get("api_secret"), access_token=self.settings["twitter"]["user_key"], access_token_secret=self.settings["twitter"]["user_secret"], chunk_size=1025)
self.stream = streaming.Stream(auth = self.auth, listener=self.stream_listener, chunk_size=1025) self.stream_thread = call_threaded(self.stream.filter, follow=self.stream.users, stall_warnings=True)
self.stream_thread = call_threaded(self.stream.filter, follow=self.stream_listener.users, stall_warnings=True)
def stop_streaming(self): def stop_streaming(self):
if config.app["app-settings"]["no_streaming"]: if config.app["app-settings"]["no_streaming"]:
@ -554,7 +553,7 @@ class Session(base.baseSession):
status._json = {**status._json, **status._json["extended_tweet"]} status._json = {**status._json, **status._json["extended_tweet"]}
# Sends status to database, where it will be reduced and changed according to our needs. # Sends status to database, where it will be reduced and changed according to our needs.
buffers_to_send = [] buffers_to_send = []
if status.user.id_str in self.stream_listener.users: if status.user.id_str in self.stream.users:
buffers_to_send.append("home_timeline") buffers_to_send.append("home_timeline")
if status.user.id == self.db["user_id"]: if status.user.id == self.db["user_id"]:
buffers_to_send.append("sent_tweets") buffers_to_send.append("sent_tweets")

View File

@ -12,17 +12,17 @@ from pubsub import pub
log = logging.getLogger("sessions.twitter.streaming") log = logging.getLogger("sessions.twitter.streaming")
class StreamListener(tweepy.StreamListener): class Stream(tweepy.Stream):
def __init__(self, twitter_api, user, user_id, muted_users=[], *args, **kwargs): def __init__(self, twitter_api, user, user_id, muted_users=[], *args, **kwargs):
super(StreamListener, self).__init__(*args, **kwargs) super(Stream, self).__init__(*args, **kwargs)
log.debug("Starting streaming listener for account {}".format(user)) log.debug("Starting streaming listener for account {}".format(user))
self.started = False self.started = False
self.users = [] self.users = []
self.api = twitter_api self.api = twitter_api
self.user = user self.user = user
self.user_id = user_id self.user_id = user_id
friends = self.api.friends_ids() friends = self.api.get_friend_ids()
log.debug("Retrieved {} friends to add to the streaming listener.".format(len(friends))) log.debug("Retrieved {} friends to add to the streaming listener.".format(len(friends)))
self.users.append(str(self.user_id)) self.users.append(str(self.user_id))
log.debug("Got {} muted users.".format(len(muted_users))) log.debug("Got {} muted users.".format(len(muted_users)))
@ -45,78 +45,3 @@ class StreamListener(tweepy.StreamListener):
return return
if status.user.id_str in self.users: if status.user.id_str in self.users:
pub.sendMessage("newStatus", status=status, user=self.user) pub.sendMessage("newStatus", status=status, user=self.user)
class Stream(tweepy.Stream):
def _run(self):
# Authenticate
url = "https://%s%s" % (self.host, self.url)
# Connect and process the stream
error_counter = 0
resp = None
exc_info = None
while self.running:
if self.retry_count is not None:
if error_counter > self.retry_count:
# quit if error count greater than retry count
break
try:
auth = self.auth.apply_auth()
resp = self.session.request('POST',
url,
data=self.body,
timeout=self.timeout,
stream=True,
auth=auth,
verify=self.verify,
proxies = self.proxies)
if resp.status_code != 200:
if self.listener.on_error(resp.status_code) is False:
break
error_counter += 1
if resp.status_code == 420:
self.retry_time = max(self.retry_420_start,
self.retry_time)
time.sleep(self.retry_time)
self.retry_time = min(self.retry_time * 2,
self.retry_time_cap)
else:
error_counter = 0
self.retry_time = self.retry_time_start
self.snooze_time = self.snooze_time_step
self.listener.on_connect()
self._read_loop(resp)
except (requests.ConnectionError, requests.Timeout, ssl.SSLError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.ProtocolError) as exc:
# This is still necessary, as a SSLError can actually be
# thrown when using Requests
# If it's not time out treat it like any other exception
if isinstance(exc, ssl.SSLError):
if not (exc.args and 'timed out' in str(exc.args[0])):
exc_info = sys.exc_info()
break
if self.listener.on_timeout() is False:
break
if self.running is False:
break
time.sleep(self.snooze_time)
self.snooze_time = min(self.snooze_time + self.snooze_time_step,
self.snooze_time_cap)
except Exception as exc:
exc_info = sys.exc_info()
# any other exception is fatal, so kill loop
break
# cleanup
self.running = False
if resp:
resp.close()
self.new_session()
if exc_info:
# call a handler first so that the exception can be logged.
self.listener.on_exception(exc_info[1])
six.reraise(*exc_info)

View File

@ -6,7 +6,7 @@ import logging
import requests import requests
import time import time
import sound import sound
from tweepy.error import TweepError from tweepy.errors import TweepyException
log = logging.getLogger("twitter.utils") log = logging.getLogger("twitter.utils")
""" Some utilities for the twitter interface.""" """ Some utilities for the twitter interface."""
@ -159,7 +159,7 @@ def if_user_exists(twitter, user):
try: try:
data = twitter.get_user(screen_name=user) data = twitter.get_user(screen_name=user)
return data return data
except TweepError as err: except TweepyException as err:
if err.api_code == 50: if err.api_code == 50:
return None return None
else: else:

View File

@ -1,3 +1,3 @@
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import unicode_literals from __future__ import unicode_literals
from . import baseDialog, trends, configuration, lists, message, search, find, show_user, update_profile, urlList, userSelection, utils, filterDialogs from . import baseDialog, trends, configuration, lists, message, search, find, show_user, update_profile, urlList, userSelection, utils, filterDialogs, userAliasDialogs

View File

@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
import wx
from . import baseDialog
class addAliasDialog(baseDialog.BaseWXDialog):
def __init__(self, title, users):
super(addAliasDialog, self).__init__(parent=None, id=wx.ID_ANY, title=title)
panel = wx.Panel(self)
userSizer = wx.BoxSizer()
self.cb = wx.ComboBox(panel, -1, choices=users, value=users[0], size=wx.DefaultSize)
self.cb.SetFocus()
self.autocompletion = wx.Button(panel, -1, _(u"&Autocomplete users"))
userSizer.Add(wx.StaticText(panel, -1, _(u"User")), 0, wx.ALL, 5)
userSizer.Add(self.cb, 0, wx.ALL, 5)
userSizer.Add(self.autocompletion, 0, wx.ALL, 5)
aliasSizer = wx.BoxSizer(wx.HORIZONTAL)
aliasLabel = wx.StaticText(panel, wx.ID_ANY, _("Alias"))
self.alias = wx.TextCtrl(panel, wx.ID_ANY)
aliasSizer.Add(aliasLabel, 0, wx.ALL, 5)
aliasSizer.Add(self.alias, 0, wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
ok = wx.Button(panel, wx.ID_OK, _(u"OK"))
ok.SetDefault()
cancel = wx.Button(panel, wx.ID_CANCEL, _(u"Close"))
btnsizer = wx.BoxSizer()
btnsizer.Add(ok, 0, wx.ALL, 5)
btnsizer.Add(cancel, 0, wx.ALL, 5)
sizer.Add(userSizer, 0, wx.ALL, 5)
sizer.Add(aliasSizer, 0, wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALL, 5)
panel.SetSizer(sizer)
self.SetClientSize(sizer.CalcMin())
def get_user(self):
return (self.cb.GetValue(), self.alias.GetValue())

View File

@ -46,38 +46,4 @@ class selectUserDialog(baseDialog.BaseWXDialog):
self.SetClientSize(sizer.CalcMin()) self.SetClientSize(sizer.CalcMin())
def get_user(self): def get_user(self):
return self.cb.GetValue() return self.cb.GetValue()
class addAliasDialog(baseDialog.BaseWXDialog):
def __init__(self, title, users):
super(addAliasDialog, self).__init__(parent=None, id=wx.ID_ANY, title=title)
panel = wx.Panel(self)
userSizer = wx.BoxSizer()
self.cb = wx.ComboBox(panel, -1, choices=users, value=users[0], size=wx.DefaultSize)
self.cb.SetFocus()
self.autocompletion = wx.Button(panel, -1, _(u"&Autocomplete users"))
userSizer.Add(wx.StaticText(panel, -1, _(u"User")), 0, wx.ALL, 5)
userSizer.Add(self.cb, 0, wx.ALL, 5)
userSizer.Add(self.autocompletion, 0, wx.ALL, 5)
aliasSizer = wx.BoxSizer(wx.HORIZONTAL)
aliasLabel = wx.StaticText(panel, wx.ID_ANY, _("Alias"))
self.alias = wx.TextCtrl(panel, wx.ID_ANY)
aliasSizer.Add(aliasLabel, 0, wx.ALL, 5)
aliasSizer.Add(self.alias, 0, wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
ok = wx.Button(panel, wx.ID_OK, _(u"OK"))
ok.SetDefault()
# ok.Bind(wx.EVT_BUTTON, self.onok)
cancel = wx.Button(panel, wx.ID_CANCEL, _(u"Close"))
btnsizer = wx.BoxSizer()
btnsizer.Add(ok, 0, wx.ALL, 5)
btnsizer.Add(cancel, 0, wx.ALL, 5)
sizer.Add(userSizer, 0, wx.ALL, 5)
sizer.Add(aliasSizer, 0, wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALL, 5)
panel.SetSizer(sizer)
self.SetClientSize(sizer.CalcMin())
def get_user(self):
return (self.cb.GetValue(), self.alias.GetValue())