本文整理汇总了Python中Actions类的典型用法代码示例。如果您正苦于以下问题:Python Actions类的具体用法?Python Actions怎么用?Python Actions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Actions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clear_sub
def clear_sub(credentials, sub, num=20):
"""Removes all* old posts from a sub (use with care)
* up to 900
:param credentials:
:param sub:
:return:
"""
num = min(num, 900)
if num < 0:
num = int(1e6)
mypraw = create_multiprocess_praw(credentials)
sub = get_subreddit(credentials, mypraw, sub)
old_stream = p.helpers.submission_stream(mypraw, sub, limit=num)
results = []
try:
#delete all old posts
for i in range(num):
try:
post = old_stream.next()
Actions.remove_post(post, delete=True)
print("# {} deleted...".format(i))
except AttributeError:
# Post or Comment may have been deleted between retrieving it
# and accessing its fields
pass
except AssertionError, e:
logging.log(logging.DEBUG, str(e) + "\nNo Posts!")
示例2: update_mods
def update_mods(self, author=None):
"""
Update the internal mod-list (who can execute queries)
:param author: if specified, the bot will respond to this user to let them know success/failure
:return: None
"""
try:
mlist = [mod.name for mod in Actions.get_mods(self.praw, self.sub)]
if mlist is None or not len(mlist):
return False
# only update if it's valid
self.mod_list = mlist
self.last_mod_update = datetime.datetime.now()
if author is not None:
Actions.send_message(self.praw, author, u"RE: Modlist update", u"Success!")
return True
except Exception, e:
if author is not None:
Actions.send_message(self.praw, author, u"RE: Modlist update",
u"Error encountered, please try again later.")
logging.error(u"Could not update moderator list!")
self.log_error()
if __debug__:
logging.exception(e)
return False
示例3: __info
def __info(self, author, subject, text):
try:
limit = 10
#first find a limit if it exists
match = self.limit_match.search(subject)
if match:
limit = int(match.group(1))
#we must figure out the case
if self.list_command.search(subject):
return self.__info_list(author, subject, text)
elif self.channel_command.search(subject):
return self.__info_channels(author, subject, text, limit)
elif self.user_command.search(subject):
return self.__info_user(author, subject, text, limit)
else:
return Actions.send_message(self.praw,
author,
u'Message text not recognized',
u'Message w/ \n'
u'subject: {}\n'.format(subject) +
u'and body: {}\n'.format(text) +
u'not recognized, please consult documentation or help.')
except Exception as e:
logging.exception(e)
Actions.send_message(self.praw,
author, u'Re: {}'.format(subject),
u'An error occured processing the following text, please file a bug report with'
u' /u/arghdos: \n{}'.format(text))
示例4: make_post
def make_post(sub, post, comment):
try:
#make post and comment
post = Actions.make_post_url(sub, post.title, post.url)
Actions.make_comment(post, comment)
except Exception, e:
print str(e)
示例5: __init__
def __init__( self, parent ):
Qt.QWidget.__init__( self, parent )
# Actions
#
Actions.createGraphEditorActions( self )
# Menus
#
#menuBar = Qt.QMenuBar( self )
#
#fileMenu = menuBar.addMenu( 'File' )
#viewMenu = menuBar.addMenu( 'View' )
#
#fileMenu.addAction( Actions.graphEditor.loadDynamicNode )
#viewMenu.addAction( Actions.graphEditor.frameAll )
# Graph editor
#
graphEditor = Cellule.appli.createGraphEditor( Cellule.fromSIP( self ) )
graphEditorSIP = Cellule.toSIP( graphEditor, Qt.QWidget )
# Layout
#
layout = Qt.QVBoxLayout( self )
#layout.addWidget( menuBar )
layout.addWidget( graphEditorSIP )
示例6: __info_user
def __info_user(self, author, subject, text, limit):
# check that we have text
lines = [l.strip() for l in self.line_splitter.split(text) if l is not None and len(l.strip())]
if not len(lines):
Actions.send_message(self.praw, author, u"RE: info user",
u"No users specified in text: \n{}".format(text))
return False
invalid_users = []
valid_users = []
#now go through the lines and make sure they're all usernames
for line in lines:
match = self.user_name_match.search(line)
if not match:
invalid_users.append(line)
else:
valid_users.append(match.group(1))
if not len(valid_users):
if len(invalid_users):
message = u'The following were not recognized as usernames: \n{}'.format(u', '.join(invalid_users))
else:
message = u"No users specified in text: ".format(text)
Actions.send_message(self.praw, author, u"RE: info user", message)
return False
valid_users = list(set(valid_users))
return_string = self.__create_table((u'Date',
u'Link', u'Submitter', u'Channel', u'Domain', u'Deleted', u'Exception'))
#with our list of usernames, query DB for submissions
with DataBaseWrapper(self.owner.database_file, False) as db:
for user in valid_users:
#val is (short_url, channel_id, domain, date_added, processed, exception
val = db.get_reddit(submitter=user, return_channel_id=True, return_domain=True, return_processed=True,
return_exception=True, sort_by_new=True, limit=limit, return_dateadded=True)
if val is not None and len(val):
for submission in val:
return_string += self.__table_entry((
str(submission[3]),
u'http://redd.it/{}'.format(submission[0][submission[0].index('t3_')+ 3:]),
user,
submission[1], submission[2],
u'True' if submission[4] == 1 else u'False',
u'True' if submission[5] == 0 and submission[4] == 1 else u'False'))
else:
return_string += self.__table_entry((u'Not Found', user, u'N/A', u'N/A', u'N/A', u'N/A'))
if invalid_users:
return_string += u'\n\n'
return_string += u"The following were not recognized as users:\n"
return_string += u'\n'.join(invalid_users)
return_string += u'\n\n'
return_string += u'Note: Deletions and Exceptions are processed every {:.1} day(s),'.format(
self.policy.Historial_Scan_Period / (24.0 * 60.0 * 60.0)) + \
u' and thus may not be updated within that time window.'
return Actions.send_message(self.praw, author, u'Re: User Info query', return_string)
示例7: scan
def scan(self, limit=None):
"""Scans the sub.
:param limit: If None, the limit in the policy will be used
:return: True if self.last_seen was reached, False otherwise
"""
lim = limit if limit else self.policy.Posts_To_Load
# first ask for posts
posts = self.get_posts(lim)
if posts is None:
return scan_result.Error
found_old = False
post_data = []
for post in posts:
try:
if not post.is_self:
post_data.append((
post.created_utc, post.name, post.url,
Actions.get_username(post), post))
except socket.error, e:
if e.errno == 10061:
logging.critical("praw-multiprocess not started!")
else:
logging.error(str(e))
return scan_result.Error
except (HTTPError, NotFound) as e:
# bad resolve
logging.warn('Bad resolve for post {}'.format(post))
示例8: historical_scan
def historical_scan(self, goto):
posts = self.get_historial_posts(goto)
if posts is not None and len(posts):
post_data = [(post.created_utc, post.name, post.url, Actions.get_username(post), post) for post in posts if not post.is_self]
self.__process_post_list(post_data)
return scan_result.FoundOld
return scan_result.Error
示例9: check_exception
def check_exception(self, post):
try:
#check for link flair
if post.link_flair_css_class is None:
return True
except:
pass
try:
#check for removal reason
if post.removal_reason is not None:
return True
except:
pass
#check top level comments for specific keyword matches
try:
success = True
#check comments
for comment in post.comments:
#test comment
if not Actions.is_deleted(comment) and comment.distinguished == 'moderator':
#test keyword
for exception in self.policy.exception_list:
if re.search(exception, comment.body):
return True
return False
except Exception, e:
success = False
time.sleep(1)
示例10: __init__
def __init__(self, file_paths, platform):
"""
ActionHandler constructor.
Create the main window, setup the message handler, import the preferences,
and connect all of the action handlers. Finally, enter the gtk main loop and block.
@param file_paths a list of flow graph file passed from command line
@param platform platform module
"""
self.clipboard = None
for action in Actions.get_all_actions(): action.connect('activate', self._handle_action)
#setup the main window
self.main_window = MainWindow(platform)
self.main_window.connect('delete-event', self._quit)
self.main_window.connect('key-press-event', self._handle_key_press)
self.get_page = self.main_window.get_page
self.get_flow_graph = self.main_window.get_flow_graph
self.get_focus_flag = self.main_window.get_focus_flag
#setup the messages
Messages.register_messenger(self.main_window.add_report_line)
Messages.send_init(platform)
#initialize
self.init_file_paths = file_paths
Actions.APPLICATION_INITIALIZE()
#enter the mainloop
gtk.main()
示例11: run
def run(self):
while True:
if not self.check_status():
break
# see if we need to update mods
if datetime.datetime.now() - self.last_mod_update > self.policy.Mod_Update_Period:
if __debug__:
logging.info(u"Blacklist Query updating mod list...")
self.update_mods()
if __debug__:
logging.info(u"Modlist updated to: {}".format(u", ".join(self.mod_list)))
# get unread
unread = Actions.get_unread(self.praw, limit=self.policy.Unread_To_Load)
try:
messages = [message for message in unread]
if __debug__:
logging.info(u"Blacklist query processing {} messages...".format(len(messages)))
for message in messages:
self.process_message(message)
if __debug__:
logging.info(u"Blacklist query processing message from user {}.\nSubject:{}\nBody:{}".
format(message.author.name if message.author.name is not None else u"DELETED",
message.subject, message.body))
except Exception, e:
logging.error(u"Error on retrieving unread messages")
if __debug__:
logging.exception(e)
self.log_error()
self.message_cache = []
# and wait (min of 30s to prevent return of cached answers on default PRAW install)
time.sleep(max(self.policy.Blacklist_Query_Period, 30))
示例12: get_posts
def get_posts(self, lim):
# first ask for posts
try:
posts = self.sub.mod.log(action="removelink", limit=lim)
posts = [posts.next().target_fullname for i in range(lim)]
return Actions.get_by_ids(self.praw, posts)
except Exception, e:
logging.error(str(e))
if __debug__:
logging.exception(e)
示例13: __init__
def __init__(self, platform, action_handler_callback):
"""
MainWindow contructor
Setup the menu, toolbar, flowgraph editor notebook, block selection window...
"""
self._platform = platform
gen_opts = platform.get_block('options').get_param('generate_options')
generate_mode_default = gen_opts.get_value()
generate_modes = [
(o.get_key(), o.get_name(), o.get_key() == generate_mode_default)
for o in gen_opts.get_options()]
# load preferences
Preferences.load(platform)
#setup window
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
vbox = gtk.VBox()
self.hpaned = gtk.HPaned()
self.add(vbox)
#create the menu bar and toolbar
self.add_accel_group(Actions.get_accel_group())
self.menu_bar = Bars.MenuBar(generate_modes, action_handler_callback)
vbox.pack_start(self.menu_bar, False)
self.tool_bar = Bars.Toolbar(generate_modes, action_handler_callback )
vbox.pack_start(self.tool_bar, False)
vbox.pack_start(self.hpaned)
#create the notebook
self.notebook = gtk.Notebook()
self.page_to_be_closed = None
self.current_page = None
self.notebook.set_show_border(False)
self.notebook.set_scrollable(True) #scroll arrows for page tabs
self.notebook.connect('switch-page', self._handle_page_change)
#setup containers
self.flow_graph_vpaned = gtk.VPaned()
#flow_graph_box.pack_start(self.scrolled_window)
self.flow_graph_vpaned.pack1(self.notebook)
self.hpaned.pack1(self.flow_graph_vpaned)
self.btwin = BlockTreeWindow(platform, self.get_flow_graph);
self.hpaned.pack2(self.btwin, False) #dont allow resize
#create the reports window
self.text_display = TextDisplay()
#house the reports in a scrolled window
self.reports_scrolled_window = gtk.ScrolledWindow()
self.reports_scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.reports_scrolled_window.add(self.text_display)
self.reports_scrolled_window.set_size_request(-1, DEFAULT_REPORTS_WINDOW_WIDTH)
self.flow_graph_vpaned.pack2(self.reports_scrolled_window, False) #dont allow resize
#load preferences and show the main window
self.resize(*Preferences.main_window_size())
self.flow_graph_vpaned.set_position(Preferences.reports_window_position())
self.hpaned.set_position(Preferences.blocks_window_position())
self.show_all()
self.reports_scrolled_window.hide()
self.btwin.hide()
示例14: test_send_message
def test_send_message(reddit, credentials):
if a.send_message(reddit, credentials['ALTUSER'], "test", "testmessage"):
print "Test Message Send: Passed"
return True
else:
print "Test Message Send: Failed"
return False
示例15: test_approve_post
def test_approve_post(post):
print "Approve Post:"
if a.approve_post(post):
print "Passed"
return True
print "Failed"
return False