"""Special bot library containing BaseUnlinkBot.Do not import classes directly from here but from specialbots."""## (C) Pywikibot team, 2003-2024## Distributed under the terms of the MIT license.#from__future__importannotationsfrompywikibot.botimportAutomaticTWSummaryBot,ExistingPageBotfrompywikibot.bot_choiceimport(AlwaysChoice,ChoiceException,InteractiveReplace,UnhandledAnswer,)frompywikibot.editorimportTextEditorfrompywikibot.textlibimportreplace_linksclassEditReplacementError(ChoiceException,UnhandledAnswer):"""The text should be edited and replacement should be restarted."""def__init__(self)->None:"""Initializer."""super().__init__('edit','e',stop=True)
[docs]classInteractiveUnlink(InteractiveReplace):"""An implementation which just allows unlinking."""def__init__(self,bot)->None:"""Create default settings."""super().__init__(old_link=bot.pageToUnlink,new_link=False,default='u')self._always=AlwaysChoice(self,'unlink all pages','a')self._always.always=bot.opt.alwaysself.additional_choices=[AlwaysChoice(self,'unlink all on page','p'),self._always,EditReplacementError()]self._bot=botself.context=100self.context_change=100
[docs]defhandle_answer(self,choice):"""Handle choice and store in bot's options."""answer=super().handle_answer(choice)self._bot.opt.always=self._always.alwaysreturnanswer
[docs]classBaseUnlinkBot(ExistingPageBot,AutomaticTWSummaryBot):"""A basic bot unlinking a given link from the current page."""use_redirects=Falsedef__init__(self,**kwargs)->None:"""Redirect all parameters and add namespace as an available option."""self.available_options.update({'namespaces':[],# Which namespaces should be processed?# default to [] which means all namespaces will be processed})super().__init__(**kwargs)def_create_callback(self):"""Create a new callback instance for replace_links."""returnInteractiveUnlink(self)
[docs]defunlink(self,target_page)->None:"""Unlink all links linking to the target page."""text=self.current_page.textwhileTrue:unlink_callback=self._create_callback()try:text=replace_links(text,unlink_callback,target_page.site)exceptEditReplacementError:new_text=TextEditor().edit(unlink_callback.current_text,jumpIndex=unlink_callback.current_range[0])# if user didn't press Canceltext=new_textorunlink_callback.current_textelse:breakself.put_current(text)