jenkins-bot has submitted this change and it was merged.
Change subject: [IMPROV] TouchBot: Use new functionality
......................................................................
[IMPROV] TouchBot: Use new functionality
The TouchBot doesn't need to overwrite run() and can let the underlying
Bot class handle it. This also separates touching and purging into two
separate bots.
Change-Id: I4151d3bd298eb87933a22a9d3f72343c5f5c0e46
---
M scripts/touch.py
M tox.ini
2 files changed, 41 insertions(+), 34 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/touch.py b/scripts/touch.py
index 42d112e..359d320 100755
--- a/scripts/touch.py
+++ b/scripts/touch.py
@@ -13,10 +13,10 @@
-purge Do not touch but purge the page
-redir specifies that the bot should work on redirect pages;
- otherwise, they will be skipped.
+ otherwise, they will be skipped. Cannot be used with -purge.
"""
#
-# (C) Pywikibot team, 2009-2014
+# (C) Pywikibot team, 2009-2015
#
# Distributed under the terms of the MIT license.
#
@@ -36,39 +36,44 @@
"""Page touch bot."""
def __init__(self, generator, **kwargs):
+ """Initialize a TouchBot instance with the options and generator."""
self.availableOptions.update({
'redir': False, # include redirect pages
- 'purge': False, # purge only
})
- super(TouchBot, self).__init__(**kwargs)
- self.generator = generator
+ super(TouchBot, self).__init__(generator=generator, **kwargs)
- def run(self):
- for page in self.generator:
- if self.getOption('purge'):
- pywikibot.output(u'Page %s%s purged'
- % (page.title(asLink=True),
- "" if page.purge() else " not"))
- continue
- try:
- # get the page, and save it using the unmodified text.
- # whether or not getting a redirect throws an exception
- # depends on the variable self.touch_redirects.
- page.get(get_redirect=self.getOption('redir'))
- page.save("Pywikibot touch script")
- except pywikibot.NoPage:
- pywikibot.error(u"Page %s does not exist."
- % page.title(asLink=True))
- except pywikibot.IsRedirectPage:
- pywikibot.warning(u"Page %s is a redirect; skipping."
- % page.title(asLink=True))
- except pywikibot.LockedPage:
- pywikibot.error(u"Page %s is locked."
- % page.title(asLink=True))
- except pywikibot.PageNotSaved:
- pywikibot.error(u"Page %s not saved."
- % page.title(asLink=True))
+ def treat(self, page):
+ """Touch the given page."""
+ try:
+ # get the page, and save it using the unmodified text.
+ # whether or not getting a redirect throws an exception
+ # depends on the variable self.touch_redirects.
+ page.get(get_redirect=self.getOption('redir'))
+ page.save("Pywikibot touch script")
+ except pywikibot.NoPage:
+ pywikibot.error(u"Page %s does not exist."
+ % page.title(asLink=True))
+ except pywikibot.IsRedirectPage:
+ pywikibot.warning(u"Page %s is a redirect; skipping."
+ % page.title(asLink=True))
+ except pywikibot.LockedPage:
+ pywikibot.error(u"Page %s is locked."
+ % page.title(asLink=True))
+ except pywikibot.PageNotSaved:
+ pywikibot.error(u"Page %s not saved."
+ % page.title(asLink=True))
+
+
+class PurgeBot(pywikibot.Bot):
+
+ """Purge each page on the generator."""
+
+ def treat(self, page):
+ """Purge the given page."""
+ pywikibot.output(u'Page %s%s purged'
+ % (page.title(asLink=True),
+ "" if page.purge() else " not"))
def main(*args):
@@ -87,16 +92,17 @@
local_args = pywikibot.handle_args(args)
genFactory = pagegenerators.GeneratorFactory()
+ bot_class = TouchBot
for arg in local_args:
- if genFactory.handleArg(arg):
- continue
- if arg.startswith("-"):
+ if arg == '-purge':
+ bot_class = PurgeBot
+ elif not genFactory.handleArg(arg) and arg.startswith("-"):
options[arg[1:].lower()] = True
gen = genFactory.getCombinedGenerator()
if gen:
preloadingGen = pagegenerators.PreloadingGenerator(gen)
- bot = TouchBot(preloadingGen, **options)
+ bot = bot_class(generator=preloadingGen, **options)
pywikibot.Site().login()
bot.run()
else:
diff --git a/tox.ini b/tox.ini
index 412f9a0..9ffefe0 100644
--- a/tox.ini
+++ b/tox.ini
@@ -89,6 +89,7 @@
scripts/spamremove.py \
scripts/states_redirect.py \
scripts/template.py \
+ scripts/touch.py \
scripts/transferbot.py \
scripts/unusedfiles.py \
scripts/upload.py \
--
To view, visit https://gerrit.wikimedia.org/r/210016
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I4151d3bd298eb87933a22a9d3f72343c5f5c0e46
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: set_redirect_target method for ItemPage objects
......................................................................
set_redirect_target method for ItemPage objects
It lets people to set a redirect page
Bug: T77971
Change-Id: Iedf546ff2f7045ce175cf75603a94a4f53308595
---
M pywikibot/page.py
M pywikibot/site.py
2 files changed, 51 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
XZise: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 9c71b95..a1b3c68 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -3368,6 +3368,15 @@
data = {'aliases': aliases}
self.editEntity(data, **kwargs)
+ def set_redirect_target(self, target_page, create=False, force=False,
+ keep_section=False, save=True, **kwargs):
+ """
+ Set target of a redirect for a Wikibase page.
+
+ Has not been implemented in the Wikibase API yet, except for ItemPage.
+ """
+ raise NotImplementedError
+
class ItemPage(WikibasePage):
@@ -3697,6 +3706,29 @@
"""
self.repo.mergeItems(fromItem=self, toItem=item, **kwargs)
+ def set_redirect_target(self, target_page, create=False, force=False,
+ keep_section=False, save=True, **kwargs):
+ """
+ Make the item redirect to another item.
+
+ You need to define an extra argument to make this work, like save=True
+ @param target_page: target of the redirect, this argument is required.
+ @type target_page: pywikibot.Item or string
+ @param force: if true, it sets the redirect target even the page
+ is not redirect.
+ @type force: bool
+ """
+ if isinstance(target_page, basestring):
+ target_page = pywikibot.ItemPage(self.repo, target_page)
+ elif self.repo != target_page.repo:
+ raise pywikibot.InterwikiRedirectPage(self, target_page)
+ if self.exists() and not self.isRedirectPage() and not force:
+ raise pywikibot.IsNotRedirectPage(self)
+ if not save or keep_section or create:
+ raise NotImplementedError
+ self.repo.set_redirect_target(
+ from_item=self, to_item=target_page)
+
class Property():
diff --git a/pywikibot/site.py b/pywikibot/site.py
index bbac719..ebaa8cf 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -5876,6 +5876,25 @@
data = req.submit()
return data
+ def set_redirect_target(self, from_item, to_item):
+ """
+ Make a redirect to another item.
+
+ @param to_item: title of target item.
+ @type to_item: pywikibot.ItemPage
+ @param from_item: Title of the item to be redirected.
+ @type from_item: pywikibot.ItemPage
+ """
+ params = {
+ 'action': 'wbcreateredirect',
+ 'from': from_item.getID(),
+ 'to': to_item.getID(),
+ 'token': self.tokens['edit']
+ }
+ req = api.Request(site=self, **params)
+ data = req.submit()
+ return data
+
def createNewItemFromPage(self, page, bot=True, **kwargs):
"""
Create a new Wikibase item for a provided page.
--
To view, visit https://gerrit.wikimedia.org/r/190160
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Iedf546ff2f7045ce175cf75603a94a4f53308595
Gerrit-PatchSet: 13
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Deprecate UserActionRefuse and User.sendMail
......................................................................
Deprecate UserActionRefuse and User.sendMail
UserActionRefuse is present tense, which is strange for an exception.
UserActionRefuse is used for both user permissions and target preference
to not accept email.
Create new exceptions UserRightsError and NotEmailableError for the two
scenarios.
Change-Id: I4d6e21d0c7dc7db8d3878a3f67861631d6d21331
---
M pywikibot/__init__.py
M pywikibot/exceptions.py
M pywikibot/page.py
M scripts/checkimages.py
4 files changed, 77 insertions(+), 23 deletions(-)
Approvals:
John Vandenberg: Looks good to me, but someone else must approve
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 21b4dbf..d6ea7ec 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -41,7 +41,7 @@
Error, InvalidTitle, BadTitle, NoPage, SectionError,
SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily,
UnknownExtension,
- NoUsername, UserBlocked, UserActionRefuse,
+ NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
PageSaveRelatedError, PageNotSaved, OtherPageSaveError,
LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
@@ -750,3 +750,7 @@
'PageNotFound', pywikibot.exceptions.DeprecatedPageNotFoundError,
warning_message=('{0}.{1} is deprecated, and no longer '
'used by pywikibot; use http.fetch() instead.'))
+wrapper._add_deprecated_attr(
+ 'UserActionRefuse', pywikibot.exceptions._EmailUserError,
+ warning_message='UserActionRefuse is deprecated; '
+ 'use UserRightsError and/or NotEmailableError')
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index 7684d9f..4a30d02 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -6,7 +6,7 @@
- NoUsername: Username is not in user-config.py, or it is invalid.
- UserBlocked: Username or IP has been blocked
- AutoblockUser: requested action on a virtual autoblock user not valid
- - UserActionRefuse: requested user action, such as email user, refused
+ - UserRightsError: insufficient rights for requested action
- BadTitle: Server responded with BadTitle
- InvalidTitle: Invalid page title
- CaptchaError: Captcha is asked and config.solve_captcha == False
@@ -23,8 +23,9 @@
- IsRedirectPage: Page is a redirect page
- IsNotRedirectPage: Page is not a redirect page
- CircularRedirect: Page is a circular redirect
- - InterwikiRedirectPage: Page is a redirect to another site.
+ - InterwikiRedirectPage: Page is a redirect to another site
- SectionError: The section specified by # does not exist
+ - NotEmailableError: The target user has disabled email
PageSaveRelatedError: page exceptions within the save operation on a Page
(alias: PageNotSaved).
@@ -463,9 +464,18 @@
pass
-class UserActionRefuse(Error):
+class UserRightsError(Error):
- """User action was refused."""
+ """Insufficient user rights to perform an action."""
+
+ pass
+
+
+class NotEmailableError(PageRelatedError):
+
+ """This user is not emailable."""
+
+ message = "%s is not emailable."
pass
@@ -503,9 +513,21 @@
pass
+(a)pywikibot.tools.deprecated
+class _EmailUserError(UserRightsError, NotEmailableError):
+
+ """Email related error."""
+
+ pass
+
+
wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__)
wrapper._add_deprecated_attr('UploadWarning', pywikibot.data.api.UploadWarning)
wrapper._add_deprecated_attr('PageNotFound', DeprecatedPageNotFoundError,
warning_message='{0}.{1} is deprecated, and no '
'longer used by pywikibot; use '
'http.fetch() instead.')
+wrapper._add_deprecated_attr(
+ 'UserActionRefuse', _EmailUserError,
+ warning_message='UserActionRefuse is deprecated; '
+ 'use UserRightsError and/or NotEmailableError')
diff --git a/pywikibot/page.py b/pywikibot/page.py
index c724519..159ba82 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -45,8 +45,11 @@
from pywikibot.family import Family
from pywikibot.site import Namespace
from pywikibot.exceptions import (
- AutoblockUser, UserActionRefuse,
- SiteDefinitionError
+ AutoblockUser,
+ _EmailUserError,
+ NotEmailableError,
+ SiteDefinitionError,
+ UserRightsError,
)
from pywikibot.tools import (
UnicodeMixin, DotReadableDict,
@@ -2789,13 +2792,8 @@
return Page(Link(self.title(withNamespace=False) + subpage,
self.site, defaultNamespace=3))
- def sendMail(self, subject, text, ccme=False):
+ def send_email(self, subject, text, ccme=False):
"""Send an email to this user via MediaWiki's email interface.
-
- Return True on success, False otherwise.
- This method can raise an UserActionRefuse exception in case this user
- doesn't allow sending email to him or the currently logged in bot
- doesn't have the right to send emails.
@param subject: the subject header of the mail
@type subject: unicode
@@ -2803,12 +2801,16 @@
@type text: unicode
@param ccme: if True, sends a copy of this email to the bot
@type ccme: bool
+ @raises NotEmailableError: the user of this User is not emailable
+ @raises UserRightsError: logged in user does not have 'sendemail' right
+ @return: operation successful indicator
+ @rtype: bool
"""
if not self.isEmailable():
- raise UserActionRefuse('This user is not mailable')
+ raise NotEmailableError('%s is not mailable' % self.username)
if not self.site.has_right('sendemail'):
- raise UserActionRefuse('You don\'t have permission to send mail')
+ raise UserRightsError('You don\'t have permission to send mail')
params = {
'action': 'emailuser',
@@ -2822,16 +2824,40 @@
mailrequest = pywikibot.data.api.Request(site=self.site, **params)
maildata = mailrequest.submit()
- if 'error' in maildata:
- code = maildata['error']['code']
- if code == u'usermaildisabled ':
- pywikibot.output(u'User mail has been disabled')
- elif 'emailuser' in maildata:
+ if 'emailuser' in maildata:
if maildata['emailuser']['result'] == u'Success':
- pywikibot.output(u'Email sent.')
return True
return False
+ @deprecated('send_email')
+ def sendMail(self, subject, text, ccme=False):
+ """Send an email to this user via MediaWiki's email interface.
+
+ Outputs 'Email sent' if the email was sent.
+
+ @param subject: the subject header of the mail
+ @type subject: unicode
+ @param text: mail body
+ @type text: unicode
+ @param ccme: if True, sends a copy of this email to the bot
+ @type ccme: bool
+ @raises _EmailUserError: logged in user does not have 'sendemail' right
+ or the target has disabled receiving emails
+ @return: operation successful indicator
+ @rtype: bool
+ """
+ if not self.isEmailable():
+ raise _EmailUserError('This user is not mailable')
+
+ if not self.site.has_right('sendemail'):
+ raise _EmailUserError('You don\'t have permission to send mail')
+
+ if self.send_email(subject, text, ccme=ccme):
+ pywikibot.output('Email sent.')
+ return True
+ else:
+ return False
+
def block(self, expiry, reason, anononly=True, nocreate=True,
autoblock=True, noemail=False, reblock=False):
"""
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index 71da9ec..28d6ade 100755
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -97,6 +97,8 @@
from pywikibot import pagegenerators as pg
from pywikibot import i18n
+
+from pywikibot.exceptions import NotEmailableError
from pywikibot.family import Family
from pywikibot.tools import deprecated
@@ -830,8 +832,8 @@
% self.luser, emailText)
emailClass = pywikibot.User(self.site, self.luser)
try:
- emailClass.sendMail(emailSubj, text_to_send)
- except pywikibot.UserActionRefuse:
+ emailClass.send_email(emailSubj, text_to_send)
+ except NotEmailableError:
pywikibot.output("User is not mailable, aborted")
return
--
To view, visit https://gerrit.wikimedia.org/r/180713
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I4d6e21d0c7dc7db8d3878a3f67861631d6d21331
Gerrit-PatchSet: 11
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>