Jump to content

Manual talk:Pywikibot/Archive 3

About this board

Archives 


Please use one of the communication channels listed on Manual:Pywikibot/Communication rather than using this discussion board. There is very little traffic here, so it may take a while before you get a response.

Category:NG:Dev.Team_games

2
For Each element In group ... Next (talkcontribs)

Hi. I found that

   site = pywikibot.Site("en")
   page = pywikibot.Page(site, "Category:NG:Dev.Team_games")
   print(page.text)

works well, but

   site = pywikibot.Site("en")
   page = pywikibot.Page(site, "NG:Dev.Team_games", 14)
   print(page.text)

raises an error:

   NoUsernameError: Failed OAuth authentication for wikipedia:ng: The authorization headers in your request are for a user that does not exist here

I guess pywikibot treated the title as a interwiki. So how to make it parses namespace id (i.e. 14) first? Thanks.

(version 9.6.0)

Xqt (talkcontribs)
Reply to "Category:NG:Dev.Team_games"

pywikibot doesn't see scripts translations

2
Dimka665 (talkcontribs)

I installed pywikibot as package, downloaded `scripts` and `scripts/i18n`. Added `user_script_paths = ['scripts']` to `user-config.py`. When I run any script I got translation error. Pywikibot search translation in `pywikibot.scripts.i18n` only.

How to use standard scripts with package installed `pywikibot`?

Xqt (talkcontribs)

Add Sitelinks to Wikipedia with badge 'intentional sitelink to redirect'

2
Tidoni (talkcontribs)

Hi, i am trying to add a Sitelink to a Wikidata Entry, pointing to a site in a wikipedia project that is a redirect. When i add the page directly, the redirect gets resolved an the sitelink gets added as the page behind the redirect. I assume i have to somehow set the badge 'intentional sitelink to redirect'. I tried searching for a guide or documentation on that, but could not find it. Can someone point me to a page where this is described, or does someone know, if this even is a feature that is supported? Thanks in Advance

Matěj Suchánek (talkcontribs)

It should be possible using SiteLink:

from pywikibot import ItemPage, SiteLink
site = ...
repo = pywikibot.Site('wikidata')
item = ItemPage(repo, 'Q4115189')
link = SiteLink(title, site, [ItemPage(repo, 'Q70894304')])
item.setSitelink(link)

or that like.

Reply to "Add Sitelinks to Wikipedia with badge 'intentional sitelink to redirect'"
ColumbaBush (talkcontribs)

Hi @Xqt - thanks for all the work you've done on pywikibot, I've used template.py for simple replacements via https://en.wiktionary.org/wiki/User:ColumbaBushBot but now I wanted to do something more complicated

  1. detect if {{aii-verb}} exists
  2. extract its first argument
  3. and replace the aii-conj-verb template (ex. {{aii-conj-verb/G]}}, {{aii-conj-verb/C]}}, etc...) with {{aii-conj|<first argument from step 2>}}

An example of this would be this edit https://en.wiktionary.org/w/index.php?title=%DC%A5%DC%A2%DC%90&diff=prev&oldid=82304028

Can you recommend how I can use existing scripts to accomplish this, or perhaps even provide a code snippet to modify an existing script?

Thanks so much, your help is greatly appreciated

Reply to "Replacing templates"

How connect to own wiki?

3
Summary by Dimka665

You need to use this manual Manual:Pywikibot/Use on third-party wikis to specify own Family, create and use BotPasswords Manual:Pywikibot/BotPasswords

Dimka665 (talkcontribs)

How can I connect to my local private wiki on 127.0.0.1:8080?


site = pywikibot.Site(url='http://127.0.0.1:8080')

page = pywikibot.Page(site, 'Main_Page')


raises SiteDefinitionError: Invalid AutoFamily('127.0.0.1:8080')

Framawiki (talkcontribs)
Dimka665 (talkcontribs)

Edits made by Pywikibot edits not showing up in Recent Changes

5
Summary by Framawiki

continues on Topic:Xplxuznmiib8p0j4

Lost Student (talkcontribs)

As the title says, I cannot see the edits (mostly new page creation) in Recent Changes, even with all filters removed. I can only see the edits when I go to the User Contributions page of the user account (which is in the Bots user group).

Here is the setup of my wiki:

Installed software

Product Version
MediaWiki 1.39.4
PHP 7.4.33 (fpm-fcgi)
MariaDB 10.4.20-MariaDB-1:10.4.20+maria~buster-log
ICU 65.1

One big reason I want my edits to show up is in case I need to delete all the pages created in a run (which is probably 200-300 pages), and Mass Delete only works on edits that show up in Recent Changes--so Mass Delete doesn't see any of these new pages.

Is there a setting somewhere in the Pywikibot configuration to change this behavior? Thanks!

Framawiki (talkcontribs)

Hi, indeed if you remove all filters from recentchanges, and see No active filters. All contributions are shown (like on this link) you should see all changes made on your wiki, including ones made by pywikibot.

If it's not the case that would be a bug in mediawiki itself rather than pywikibot, as pwb is this an API customer doing it's job (you see the edit on the website on some places, so they were well sent by pwb to mediawiki). You can then open a topic on Project:Support desk.

Lost Student (talkcontribs)

Thanks for the quick reply. I verified that no filters are applied at the Recent Changes and still nothing shows up, yet I know there are edits that were successfully made (such as here, for example--there are hundreds more made by the same user in the last 7 days).

I will go ahead and open a topic at the Support desk.

Framawiki (talkcontribs)

indeed I don't see them on your site the way they are usually. Maybe there's a reason why edicts aren't saved in the "recentchanges" table, but only in "revisions" table, while they should be in both as far i know, if you want to look in the database.

Will be interesting to see the other answers on support desk too :)

Lost Student (talkcontribs)

@Framawiki, after doing more investigation and trials, it looks like no edits are showing up in Recent Changes, even ones made manually by a non-bot account. So this certainly has nothing to do with Pywikibot.

Get wd item from wikipedia page in bulk

3
Framawiki (talkcontribs)

Hello, calling pywikibot.ItemPage.fromPage(page) for each page takes a long time.

I'm using wikidata.preloadpages(list) to get page content in bulk, it works well, is there similar preload function for ItemPage.fromPage()?

Thanks!

Matěj Suchánek (talkcontribs)

There is DataSite.preload_entities. Note that it doesn't maintain the implicit relationship between pages and items.

Framawiki (talkcontribs)

if there is preloadpages, that's logical that preload_entities exists too, thanks Matěj!

Reply to "Get wd item from wikipedia page in bulk"

unable to work on items with pywikibot

5
Keystester (talkcontribs)

I have my family file, user-config.py and user-password.py in the directory that i am running the following script from

```

import os, sys

import pywikibot as pwb

pwb.config.register_families_folder(os.getcwd())

pwb.login.ClientLoginManager().login()

os.environ['PYWIKIBOT_DIR'] = os.getcwd()

site = pwb.Site()

repo = site.data_repository()

pg = pwb.ItemPage(repo, 'Q10')

pg.get()

```

i get the following error `AttributeError: DataSite instance has no attribute 'entity_sources' `.


But when i use `pg=pwb.Page(repo, 'Main Page'); print(pg.text) `, i get an output.


How do i get pywikibot to work with items on my wikidata instance ?

Xqt (talkcontribs)

Seems your wikibase family file does not define the entity_sources method. Refer wikidata_family.py or commons_family.py as a sample. Maybe we should add a abstract base class for repository families to give a better message.

Keystester (talkcontribs)

They don't have an entity_sources method either.


Edit: commons_family.py has it but wikidata_family.py's method only has a 'return {}'. I will try modifying my family file

Keystester (talkcontribs)

adding the following to my family file got it working.

```

def entity_sources(self, code):

return {}

```

Would have been nice if the documentation for third party wiki's had this mentioned

Xqt (talkcontribs)
Reply to "unable to work on items with pywikibot"

Error handling with Pywikibot

4
Yann (talkcontribs)

Hi, I upload files on Commons with Pywikibot (see https://commons.wikimedia.org/w/index.php?title=Special:ListFiles/YannBot&ilshowall=1 ). It works but I get a lot of errors, mainly due to time out from server side. Now it would OK if I could just tell the bot to start again if the upload fails. I use a bash script to generate all the needed data, but the output is always true whatever happened. How to do error handling? Thanks,

$PYTHON ~/core_stable/pwb.py upload "$filename" $sim $chunk -noverify -filename:"$uploadname" -keep -abortonwarn -descfile:"$desc"

Whym (talkcontribs)

As far as I can see, it does exit successfully upon server side errors at least. If you want to change that, I think you can submit a feature request (or even better, a patch to the source code) at phabricator.

Yann (talkcontribs)

I don't know Python enough to propose a patch. See phab:T338969.

Whym (talkcontribs)

If you already created the task, that's a good start. It doesn't have to be a "feature request" per se, as long as the problem is correctly described. Other users/developers may or may not re-categorize it later.

Reply to "Error handling with Pywikibot"

Replace script and fix option

13
Summary by Speravir

The cause for the error messages was on user side: I mistakenly added a comma at a place where it does not belong.

Speravir (talkcontribs)

@Xqt, I do not know whether this is a bug or an issue on my side, therefore here and not in Phabricator:

I’ve added this to user-fixes.py:

fixes['ampCode'] = {
    'generator': [
        r'-ns:0',
        r'-search:insource:"%26" insource:/%26/',
    ],
    'regex': False,
    'msg': {
        '_default': 'Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]',
    },
    'replacements': [
        (r' %26 ', ' & '),
    ]
}

and then started Pywikibot with this (Windows) command line (user is pre-configured):

pwb replace -simulate -lang:de -fix:ampCode -log:fix-ampCode.log

This resulted in this error message:

2023-05-24 00:40:34            http.py,  123 in              flush: VERBOSE  Traceback (most recent call last):
  File "C:\Programs\Netz\pywikibot\pwb.py", line 39, in <module>
    sys.exit(main())
             ^^^^^^
  File "C:\Programs\Netz\pywikibot\pwb.py", line 35, in main
    runpy.run_path(str(path), run_name='__main__')
  File "<frozen runpy>", line 291, in run_path
  File "<frozen runpy>", line 98, in _run_module_code
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 514, in <module>
    main()
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 498, in main
    if not execute():
           ^^^^^^^^^
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 485, in execute
    run_python_file(filename, script_args, module)
  File "C:\Programs\Netz\pywikibot\pywikibot\scripts\wrapper.py", line 147, in run_python_file
    exec(compile(source, filename, 'exec', dont_inherit=True),
  File "C:\Programs\Netz\pywikibot\scripts\replace.py", line 1113, in <module>
    main()
  File "C:\Programs\Netz\pywikibot\scripts\replace.py", line 1008, in main
    if not fix['replacements']:
           ~~~^^^^^^^^^^^^^^^^
TypeError: tuple indices must be integers or slices, not str
2023-05-24 00:40:34            http.py,  132 in              flush: CRITICAL Exiting due to uncaught exception TypeError: tuple indices must be integers or slices, not str

Used Pywikibot version is:

Release version: 8.1.2
setuptools version: 65.5.0
mwparserfromhell version: 0.6.3
wikitextparser version: 0.51.1
requests version: 2.28.1

With explicit command line options the task worked then, the call was:

pwb replace -simulate -lang:de -ns:0 -search:"insource:\"%26\" insource:/ %26 /" -summary:"Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]" -log:fix-ampCode.log " %26 " " & "
Sakura emad (talkcontribs)

CHATGPT generated Answer:

Hi there! It seems that there is an issue with the replacements field in your code snippet. The error message indicates that "tuple indices must be integers or slices, not str." To fix this, please replace the parentheses with square brackets in the replacements field to define a list of tuples. Here's the corrected code snippet:

fixes['ampCode'] = {
    'generator': [
        r'-ns:0',
        r'-search:insource:"%26" insource:/%26/',
    ],
    'regex': False,
    'msg': {
        '_default': 'Bot-Änderung: überflüss. Kodierung für [[Und-Zeichen]] ersetzt, vgl. [[Spezial:Diff/233908956|Anfrage]]',
    },
    'replacements': [
        [r' %26 ', ' & '],
    ]
}

Speravir (talkcontribs)

No, that is not the reason:

  1. Inspite I wondered about this change (see next item), I tested it and the error message did not disappear.
  2. Though it could be outdated on Manual:Pywikibot/user-fixes.py, the syntax with parentheses is still visible there.
  3. Also, I actually had copied older entries and adjusted them to new task. Back in the past all had worked fine.
Sakura emad (talkcontribs)

: ) New Answer:

If correcting the replacements field did not resolve the issue, here are a few additional suggestions to investigate further:

Check for any recent changes or updates in the Pywikibot library or related dependencies that could be causing compatibility issues. It's possible that there might be a newer version or a specific configuration that is causing the error.

Double-check the command line arguments and options being used to start Pywikibot. Ensure that all necessary arguments are provided correctly, and there are no missing or incorrect options in the command.

Verify if you have the latest version of Pywikibot installed. While you mentioned version 8.1.2, it's worth checking if there are any newer releases available that might include bug fixes or improvements related to the issue you are facing.

I recommend reaching out to the Pywikibot community or forums for assistance. They have extensive experience with the library and might be able to provide specific guidance or insights based on similar issues they have encountered.

Xqt (talkcontribs)

Could you please add the following lines in front of line 1008 in replace.py:

from pprint import pprint
pprint(fix)

Seems that the replace.py script found an evaluated fixes entry different from that given above. The fix itself is read as tuple instead a dict somehow.  @xqt 04:24, 31 May 2023 (UTC)

Speravir (talkcontribs)

With how much indentation? I did it this way:

if isinstance(fix['msg'], str): # line 1007
    from pprint import pprint
    pprint(fix)
    set_summary = i18n.twtranslate(site, str(fix['msg']))

The error message remains.

I also have deleted the whole pywikibot (without my user scripts and config, but unintentionally the logs) and then re-extracted the zip file and then temporarily uninstalled mwparserfromhell, because I noticed the subdirectory in pywikibot. No success at all.

Side question: Can I without any risk add -simulate as generator option into user-fixes.py?

Xqt (talkcontribs)

> With how much indentation? I did it this way:

Seems you have updated the script in meantime. What you should do is the following: Replace the following code

       if not fix['replacements']:
           pywikibot.warning(f'No replacements defined for fix {fix_name!r}')
           continue

with

       from pprint import pprint
       print(type(fix))
       pprint(fix)
       if not fix['replacements']:
           pywikibot.warning(f'No replacements defined for fix {fix_name!r}')
           continue

The reason is that fix seems not to be a dict but a tuple. Maybe you have added a comma at the end of the ampCode fix in your fixes.py.  @xqt 11:57, 2 June 2023 (UTC)

Speravir (talkcontribs)

> “Maybe you have added a comma at the end of the ampCode fix in your fixes.py.“

Oh. My. God. This is sooo embarrassing! Auf Deutsch: Ich möchte im Boden versinken!

Yes, this was my simple, but that extensive mistake.

On one hand I am glad not having opened a Phabricator task, but on the other hand (again) so much stress and effort for such a tiny cause. Nethertheless thank you, Xqt, for having the right idea!

Just for the record and for comparison: With the addition of the print code this will be displayed in the terminal (but not the log) as first lines after the command input:

  • in case of defunct user-fix.py with spurious comma (obviously changed code for test case):
<class 'tuple'>                                                                                                      
({'generator': ['-ns:0', '-search:insource:"eszett"'],                                                               
  'msg': {'_default': 'Test Pywikibot, Replace-Skript'},                                                            
  'regex': False,                                                                                                    
  'replacements': [('eszett', 'ß')]},)
  • in correct working state without this comma:
<class 'dict'>                                                                                                       
{'generator': ['-ns:0', '-search:insource:"eszett"'],                                                                
 'msg': {'_default': 'Test Pywikibot, Replace-Skript'},                                                             
 'regex': False,                                                                                                     
 'replacements': [('eszett', 'ß')]}
Xqt (talkcontribs)

> the print code this will be displayed in the terminal (but not the log)

Yes this is intentional. print and pprint does not go throught the ui wrapper but directly to the terminal. I usually use them for debugging. Schönes Wochenende wünsch' ich.  @xqt 09:51, 3 June 2023 (UTC)

Xqt (talkcontribs)

> Side question: Can I without any risk add -simulate as generator option into user-fixes.py?

This does not work because generator options are only taken as pagegenerators options. It may contains generators and filters, see generator options and filter options. -simulate is a global option and must be given with the replace.py script or the pwb wrapper script.  @xqt 11:13, 2 June 2023 (UTC)
Speravir (talkcontribs)

Thanks, I will have a look.

Reply to "Replace script and fix option"