forked from SirComputer1/SCBot
/
sum_disc.py
1732 lines (1438 loc) · 68.8 KB
/
sum_disc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
This bot is used for summarize discussions spread over the whole wiki
including all namespaces. It checks several users (at request), sequential
(currently for the german wiki [de] only).
The bot will only change the user's discussion page by appending a summary
reports (that is also used as history for further runs).
The bot's operating procedure:
-retrieve user list from [[Benutzer:DrTrigonBot/Diene_Mir!]]
-check recent changes in [[Special:Contributions/<user>]]
(Spezial:Beiträge/...)
-retrieve history from file
-checking each listed Discussion on time of latest change
-checks relevancy by searching each heading with user signature in body, if
any found, checks them on changes and finally if the user signature is the
last one (or if there is any foreign signature behind it)
-appending history to local user history file (same as summary report, can
also be redirected on a page in the wiki if useful)
-appending summary report to [[Benutzer Diskussion:<user>]]
This bot code and 'wikipedaiAPI.py' work with UTC/GMT ONLY beacuse of DST!! For
output to wiki in 'parse_news' the time is localized first!
The code is still very much alpha level and the scope of what it can do is
still rather limited, only 1 part of speech, only 1 (different) Wiktionary
output formats, no langnames matrix.
After running the bot the first time for an user there will be a log file
used as history. By running the bot about once a week or once a month should
be sufficient the be up-to-date. The bot could also be runned continous e.g.
on the toolserver, at a very low speed, what should be fast enougth to check
the few number of users.
Entries can be changed (deleted for example when the discussion is finished)
that will cause no problem for the bot, because the entries are also written to
the history.
All other parameters will be ignored.
Syntax example:
python sum_disc.py
Default operating mode. Run for all users requested.
python sum_disc.py -compress_history:['User1','User2',...]
Loads history of User and strips all redundant information, e.g. old
entries from the file. (speeds up the reading and processing of history,
shrinks the file size and creates also a backup of old history)
python sum_disc.py -compress_history:[]
(same as before but processes ALL users)
python sum_disc.py -rollback_history:[number of runs to roll-back]
Loads old history entry of all Users, e.g. for debuging.
"""
## @package sum_disc
# @brief Summarize Discussions Robot
#
# @copyright Dr. Trigon, 2008-2011
# @copyright pywikibot team, 2013
#
# @section FRAMEWORK
#
# Python wikipedia robot framework, DrTrigonBot.
# @see http://pywikipediabot.sourceforge.net/
# @see http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
# @section LICENSE
#
# Distributed under the terms of the MIT license.
# @see http://de.wikipedia.org/wiki/MIT-Lizenz
#
__version__ = '$Id$'
#
import re
import time
import codecs
import os
import calendar
import copy
import string
import datetime
import hashlib
import locale
import logging
import urllib
from xml.etree.cElementTree import XML
# or if cElementTree not found, you can use BeautifulStoneSoup instead
import config
import pagegenerators
import userlib
import basic
# Splitting the bot into library parts
import wikipedia as pywikibot
from pywikibot import i18n, tools
_PS_warning = 1 # serious or no classified warnings/errors that should be reported
_PS_changed = 2 # changed page (if closed, will be removed)
_PS_unchanged = 3 # unchanged page
_PS_new = 4 # new page
_PS_closed = 5 # closed page (remove it from history)
_PS_maintmsg = 6 # maintenance message
_PS_notify = 7 # global wiki notification
_REGEX_eol = re.compile('\n')
bot_config = { # unicode values
'TemplateName': u'User:DrTrigonBot/SumDisc',
'userlist': u'User:DrTrigonBot/Diene_Mir!',
'maintenance_queue': u'User:DrTrigonBot/Maintenance',
'maintenance_page': u'User talk:DrTrigon#%s',
'queue_security': ([u'DrTrigon'], u'Bot: exec'),
# NON (!) unicode values
'data_path': '../data/sum_disc',
'logger_tmsp': True,
'backup_hist': True,
# regex values
'tmpl_params_regex': re.compile('(.*?)data=(.*?)\|timestamp=(.*)', re.S),
'page_regex': re.compile(r'Page\{\[\[(.*?)\]\]\}'),
# numeric values
'timeout': 15.0, # timeout for progress info display
# list values
# which lists are regex to compile ('backlinks_list' are no regex)
#'regex_compile': ['checkedit_list', 'checksign_list', 'ignorepage_list', ],
#'regex_compile': ['checkedit_list', 'ignorepage_list', 'ignorehead_list', 'matchhead_list', ],
'regex_compile': ['checkedit_list', 'ignorehead_list', 'matchhead_list'],
# which lists may contain variables to substitute
#'vars_subst': ['checkedit_list', 'checksign_list', 'ignorepage_list', 'backlinks_list', 'altsign_list' ],
'vars_subst': ['checkedit_list', 'ignorepage_list', 'backlinks_list',
'altsign_list'], # + 'ignorehead_list', 'matchhead_list' ?
# which lists should preserve/keep their defaults (instead of getting it overwritten by user settings)
'default_keep': ['checkedit_list', 'altsign_list'],
# which lists should be translated according to site's lang
'translate': ['notify_msg', 'parse_msg'],
# 'msg' moved to i18n (translatewiki.org), key names:
#'thirdparty-drtrigonbot-sum_disc-summary-head'
#'thirdparty-drtrigonbot-sum_disc-summary-add'
#'thirdparty-drtrigonbot-sum_disc-summary-mod'
#'thirdparty-drtrigonbot-sum_disc-summary-clean'
# bot paramater/options (modifiable by user)
'param_default': {
'checkedit_count': 500, # CHECK recent EDITs, a COUNT
## 'checkedit_count': 1000,
'reportchanged_switch': True, # REPORT CHANGED discussions, a SWITCH
'getbacklinks_switch': False, # GET BACKLINKS additionally, a SWITCH
'reportwarn_switch': True, # (not published yet)
'globwikinotify_switch': False, # GET OTHER WIKIS NOTIFICATIONS additionally, a SWITCH
'reportclosed_switch': True, # (not published yet)
'cleanup_count': -1, # DELETE/CLEAN-UP all older entries, a COUNT
'mainsignneeded_switch': True, # (not published yet; DRTRIGON-99)
# LIST of talks/discussions to SEARCH, a LIST
'checkedit_list': [
'^(.*?Diskussion:.*)',
u'^(Wikipedia:Löschkandidaten/.*)',
u'^(Wikipedia:Qualitätssicherung/.*)',
u'^(Wikipedia:Löschprüfung)',
'^(Wikipedia:Fragen zur Wikipedia)',
'^(Portal:.*)',
'^(Wikipedia:WikiProjekt.*)',
'^(Wikipedia:Redaktion.*)',
'^(Wikipedia:Auskunft)',
u'^(Wikipedia:Café)',
u'^(Wikipedia:Verbesserungsvorschläge)', # macht ev. probleme wegen level 1 überschr.
'^(Wikipedia:Tellerrand)',
'^(Wikipedia:Urheberrechtsfragen)',
'^(Wikipedia:Vandalismusmeldung)',
u'^(Wikipedia:Administratoren/Anfragen)',
u'^(Wikipedia:Administratoren/Notizen)',
#u'^(Wikipedia:Administratoren/.*)',
u'^(Wikipedia:Diskussionen über Bilder)',
u'^(Wikipedia:Fotowerkstatt)', # [F46]
u'^(Wikipedia:Bilderwünsche)',
u'^(Wikipedia:Grafikwerkstatt)',
u'^(Wikipedia:Grafikwerkstatt/Grafikwünsche)',
u'^(Wikipedia:Kartenwerkstatt)',
u'^(Wikipedia:Kartenwerkstatt/Kartenwünsche)',
u'^(Wikipedia:Bots/.*)', # DRTRIGON-11
u'^(Wikipedia:Redundanz/.*)', # (Wunsch von Flominator)
],
# LIST of SIGNATUREs REGEX to USE, a LIST (DRTRIGON-89)
# ev. sogar [\]\|/#] statt nur [\]\|/] ...?! dann kann Signatur auch links auf Unterabschn. enth.
# liefert leider aber auch falsch positive treffer... wobei seiten, die mal die aufmerksamkeit geweckt
# haben (auf RecentChanges-Liste waren) und links in user-namensraum enthalten, sind auch interessant!!
# (und eher selten, etwa 1 pro user bei ca. 100 in history)
'checksign_list': [u'--\s?\[\[%(ns)s:%(usersig)s[\]\|/]'],
# LIST of SIGNATUREs to USE, a LIST
'altsign_list': [u'%(username)s'],
# LIST of PAGEs to IGNORE, a LIST
# Alles mit '.*/Archiv.*' könnte man ruhig ausschließen - da passiert ja eh nichts
# und der Bot muss sich nicht mit so großen Seiten rumschlagen. -- Merlissimo 14:03, 31. Jan. 2009 (CET)
# (sofern auf diesen Seiten nichts geändert wird, tauchen sie gar nicht auf...)
'ignorepage_list': [u'(.*?)/Archiv'], # + weitere
# LIST of SIGNATUREs to USE, a LIST
'backlinks_list': [u'%(userdiscpage)s', u'%(userpage)s'],
# (hidden)
#userResultPage: default is NOT DEFINED - this is a SPECIAL PARAM it is not
# thought to be used explicit, it is defined by the page link (implicit).
# (not officially published yet: LIST of HEADs to IGNORE, a LIST)
'ignorehead_list': [u'(.*?) \(erl.\)'],
# (not published yet: LIST of HEADs to PROCESS ONLY, a LIST)
'matchhead_list': [],
# (hidden)
'notify_msg': {
_PS_changed: 'thirdparty-drtrigonbot-sum_disc-notify-changed',
_PS_new: 'thirdparty-drtrigonbot-sum_disc-notify-new',
_PS_closed: 'thirdparty-drtrigonbot-sum_disc-notify-closed',
_PS_maintmsg: 'thirdparty-drtrigonbot-sum_disc-notify-maintmsg',
_PS_notify: 'thirdparty-drtrigonbot-sum_disc-notify-notify',
},
# (hidden)
'parse_msg': {
u'*': 'thirdparty-drtrigonbot-sum_disc-parse',
_PS_closed: 'thirdparty-drtrigonbot-sum_disc-parse-closed',
_PS_notify: 'thirdparty-drtrigonbot-sum_disc-parse-notify',
_PS_warning: 'thirdparty-drtrigonbot-sum_disc-parse-warning',
u'start': 'thirdparty-drtrigonbot-sum_disc-parse-start',
u'end': 'thirdparty-drtrigonbot-sum_disc-parse-end', # ev. '~~~ um ~~~~~'
u'nonhuman': 'thirdparty-drtrigonbot-sum_disc-parse-nonhuman',
},
},
}
# debug switches
_debug_switch = {
#'user': lambda user: (user.name() != u'DrTrigon'),
'user': lambda user: False,
#'page': lambda page: (page.title() != u'...'),
'page': lambda page: False,
}
docuReplacements = {
'¶ms;': u''
#'¶ms;': pagegenerators.parameterHelp
}
class SumDiscBot(basic.AutoBasicBot):
'''
Robot which will check your latest edits for discussions and your old
discussions against recent changes, pages to check are provided by a
list. (iterable like generators)
'''
#http://de.wikipedia.org/w/index.php?limit=50&title=Spezial:Beiträge&contribs=user&target=DrTrigon&namespace=3&year=&month=-1
#http://de.wikipedia.org/wiki/Spezial:Beiträge/DrTrigon
rollback = 0
_param_default = bot_config['param_default'] # same ref, no copy
_global_warn = []
_REGEX_subster_tag = u'<!--SUBSTER-%(var)s-->'
def __init__(self):
'''Constructor of SumDiscBot(); setup environment, initialize needed consts and objects.'''
pywikibot.output(u'\03{lightgreen}* Initialization of bot:\03{default}')
basic.AutoBasicBot.__init__(self)
# modification of timezone to be in sync with wiki
os.environ['TZ'] = 'Europe/Amsterdam'
time.tzset()
pywikibot.output(u'Setting process TimeZone (TZ): %s' % str(time.tzname)) # ('CET', 'CEST')
# init constants
self._bot_config = bot_config
# convert e.g. namespaces to corret language
self._bot_config['TemplateName'] = pywikibot.Page(self.site, self._bot_config['TemplateName']).title()
self._template_regex = re.compile(
'\{\{' + self._bot_config['TemplateName'] + '(.*?)\}\}', re.S)
lang = locale.locale_alias.get(self.site.lang,
locale.locale_alias['en']).split('.')[0]
# use e.g. 'de_DE.UTF-8', 'de_DE.utf8' (thus no decode('latin-1') anymore!)
locale.setlocale(locale.LC_TIME, lang + '.UTF-8')
# init constants
self._userListPage = pywikibot.Page(self.site, bot_config['userlist'])
#print [item[0] for item in self._getUsers()] # enhance 'ignorepage_list'
pywikibot.output(u'\03{lightred}** Receiving User List (wishes): %s\03{default}' % self._userListPage)
self._user_list = self.loadUsersConfig(self._userListPage)
# [JIRA: DRTRIGON-8, DRTRIGON-32]
# (this is a possible but dangerous solution, could
# inhibit notifications between the bot users disc. pages)
#bot_user_ignorepage = []
#for user in self._user_list:
# _userPage = pywikibot.Page(self.site, u'Benutzer_Diskussion:%s' % user.name())
# if _userPage.isRedirectPage():
# _userPage = _userPage.getRedirectTarget()
# self.loadMode(_userPage)
# if self._mode:
# bot_user_ignorepage.append(self._tmpl_data)
# elif (u'userResultPage' in user.param):
# bot_user_ignorepage.append(u'Benutzer:%s' % user.param['userResultPage'])
#if 'ignorepage_list' in bot_config['regex_compile']:
# bot_user_ignorepage = [re.compile(item) for item in bot_user_ignorepage]
#self._param_default['ignorepage_list'] += bot_user_ignorepage
pywikibot.output(u'\03{lightred}** Receiving Job Queue (Maintenance Messages)\03{default}')
page = pywikibot.Page(self.site, bot_config['maintenance_queue'])
self.maintenance_msg = self.loadJobQueue(page,
bot_config['queue_security'],
reset=(not pywikibot.simulate))
self._wday = time.gmtime().tm_wday
# init variable/dynamic objects
## @todo re-write some functions to be pagegenerators and use pagegenerators.CombinedPageGenerator()
# and others to combine and use them
# \n[ JIRA: ticket? ]
# @todo limitted backlinks: try to take the most recent ones
# \n[ JIRA: ticket? ]
def run(self):
'''Run SumDiscBot().'''
pywikibot.output(
u'\03{lightgreen}* Processing User List (wishes):\03{default}')
for user in self._user_list: # may be try with PreloadingGenerator?!
if _debug_switch['user'](user):
pywikibot.warning(u'\03{lightyellow}=== ! '
u'USER WILL BE SKIPPED ! ===\03{default}')
continue
# set user and init params
self.setUser(user)
self.pages = SumDiscPages(self.site, self._param)
pywikibot.output('\03{lightred}** Processing User: %s\03{default}'
% self._user)
# get operating mode
self.loadMode(self._userPage,
regex_compile=('ignorepage_list' in
bot_config['regex_compile']))
# get history entries
self.loadHistory(rollback=self.rollback)
# (HistoryPageGenerator)
# check special pages for latest contributions
self.checkRecentEdits()
# RecentEditsPageGenerator
# get the backlinks to user disc page
# (limitted backlinks: some return >> 500 backlinks, thus check only once a week ALL/2000 those)
if self._param['getbacklinks_switch']:
self.getUserBacklinks()
# all pages served from here ARE CURRENTLY
# SIGNED (have a Signature at the moment)
# UserBacklinksPageGenerator
# get global wiki notifications (toolserver/merl)
if self._param['globwikinotify_switch']:
self.AddGlobWikiNotify()
# check for news to report and those on relevancy
# (disc-thread oriented version)
self.getLatestRelevantNews()
# CombinedPageGenerator from previous 2 (or 3) generators
# feed this generator into a DuplicateFilterPageGenerator
# and pass this (maybe with GlobalWikiNotificationsPageGen)
# to getLatestRelevantNews
# [ JIRA: ticket? ]
# gehen auch in jede history... werden aber bei compress entfernt
self.AddMaintenanceMsg()
# post results to users Discussion page (with comments for history)
self.postDiscSum()
# free the memory again
del self.pages
pywikibot.output(u'\03{lightgreen}* Processing Warnings:\03{default}')
# warnings/exceptions are printed to log, could be get by panel.py from there!
# (separate and explicit warning handling not used anymore)
#for warning in self._global_warn: # output all warnings to log (what about a special wiki page?)
# pywikibot.warning("%s: %s" % warning)
def compressHistory(self, users=[]):
"""Read history, and re-write new history without any duplicates.
@param users: List of users supported by bot (and thus in history).
@type users: list
Load, truncate and re-write history in files.
"""
if not users:
users = [item for item in self._user_list]
pywikibot.output(u'* Compressing of histories:')
if bot_config['backup_hist']:
timestmp = pywikibot.Timestamp.now().strftime(pywikibot.Timestamp.mediawikiTSFormat)[:-6]
pathname = pywikibot.config.datafilepath(
self._bot_config['data_path'], timestmp, '') # according to 'setUser'
import shutil
for user in users:
self.setUser(user)
try:
begin = float(os.path.getsize(self._datfilename))
except OSError: # OSError: [Errno 2] No such file or directory
continue
# backup old history
if bot_config['backup_hist']:
dst = os.path.join(pathname, os.path.basename(self._datfilename))
shutil.copyfile(self._datfilename, dst)
# truncate history (drop old entries)
self.pages = SumDiscPages(self.site, self._param)
self.loadHistory()
# write new history
os.remove(self._datfilename)
self.putHistory(self.pages.hist)
end = float(os.path.getsize(self._datfilename))
pywikibot.output(u'\03{lightred}** History of %s compressed and '
u'written. (%s %%)\03{default}'
% (user.name(), (end / begin) * 100))
## @since 10332
# @remarks common interface to bot user settings on wiki
def loadUsersConfig(self, page):
"""Get user list from wiki page, e.g. [[Benutzer:DrTrigonBot/Diene_Mir!]].
@param page: Wiki page containing user list and config.
@type page: page
Returns a list with entries: (user, param)
This list may be empty.
"""
#users = {}
final_users = []
for item in self._REGEX_eol.split(self.load(page)):
item = re.split(u',', item, maxsplit=1)
if (len(item) > 1): # for compatibility with 'subster.py' (if needed)
item[1] = re.compile(
(self._REGEX_subster_tag
% {u'var': u'.*?'}), re.S | re.I).sub(u'', item[1])
try:
param = eval(item[1])
except:
param = {}
item = item[0]
try:
if not (item[0] == u'*'):
continue
except:
continue
item = item[1:]
item = re.sub(u'[\[\]]', u'', item)
item = re.split(u':', item, maxsplit=1)[-1] # remove 'Benutzer(in)?:', 'User:', ...
subitem = re.split(u'\/', item) # recognize extended user entries with ".../..."
if len(subitem) > 1:
param[u'userResultPage'] = item # save extended user info (without duplicates)
item = subitem[0]
#users[item] = param # drop duplicates directly
user = userlib.User(self.site, item)
user.param = param
final_users.append(user)
return final_users
def setUser(self, user):
"""
set all internal user info
input: user [tuple] (see _getUsers(...) for format)
self-objects
bot_config
returns: self._user [string (unicode)]
returns: self._userPage [page]
returns: self._param [dict]
keys are: parameters/options [string] (see 'sum_disc_conf.py')
format: (differs from param to param)
returns: self._datfilename [string]
"""
# modified due: http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot/ToDo-Liste (id 30, 28, 17)
# defaults settings
# thanks to http://mail.python.org/pipermail/python-list/2005-September/339147.html
# and http://docs.python.org/library/copy.html
self._user = user
self._userPage = self._user.getUserTalkPage()
userdiscpage = self._userPage.title()
#self._param = dict(self._param_default)
self._param = copy.deepcopy(self._param_default)
# user settings
# (wenn nötig smooth update: alle keys mit namen '_list' einzeln updaten, dann werden sie ergänzt statt überschrieben)
self._param.update(user.param)
# re-add defaults to lists in self._param else they are overwritten
for key in bot_config['default_keep']:
if key in user.param:
self._param[key] += copy.deepcopy(self._param_default[key])
self._param['ignorepage_list'].append(self._userPage.title()) # disc-seite von user IMMER ausschliessen
if 'userResultPage' in self._param: # user with extended info (extra page to use)
self._userPage = pywikibot.Page(self.site, u'Benutzer:%s'
% self._param['userResultPage'])
self._param['ignorepage_list'].append(self._userPage.title())
self._datfilename = pywikibot.config.datafilepath(
self._bot_config['data_path'], 'sum_disc-%s-%s-%s.dat'
% (self.site.family.name, self.site.lang,
self._user.name())).encode('utf-8')
# substitute variables for use in user defined parameters/options
param_vars = {'username': self._user.name(),
'userpage': self._user.getUserPage().title(),
'userdiscpage': userdiscpage,
}
for item in bot_config['vars_subst']:
self._param[item] = [subitem % param_vars
for subitem in self._param[item]]
# pre-compile regex
# (probably try to pre-compile 'self._param_default' once in __init__ and reuse the unchanged ones here)
for item in bot_config['regex_compile']:
self._param[item] = map(re.compile, self._param[item])
# translate according to site's lang
for item in bot_config['translate']:
for key in self._param[item]:
self._param[item][key] = i18n.twtranslate(self.site,
self._param[item][key])
#{})
# generate all possible signatures and drop duplicates
ns_list = self.site.family.namespace(self.site.lang, 2, all=True)
ns_list += self.site.family.namespace(self.site.lang, 3, all=True)
signs = set()
#for user in self._param['altsign_list']:
for check in self._param['checksign_list']:
for ns in ns_list:
signs.add(check % {'ns': ns, 'usersig': '%(usersig)s'})
self._param['checksign_list'] = list(signs)
## @since 10332
# @remarks needed by sum_disc
def loadMode(self, page, regex_compile=False):
"""Get operating mode from user's disc page by searching for the
template.
@param page: The user (page) for which the data should be retrieved.
@param regex_compile: If True the value added to the ignore_list will
be compiled first.
Sets self._mode and self._tmpl_data which represent the settings how to
report news to the user. Sets self._content also which is the touched
page content to notify the user. The self._param is modified too.
"""
templates = self.loadTemplates(page, self._bot_config['TemplateName'])
self._mode = False
self._tmpl_data = u''
if templates:
tmpl = templates[0]
# enhanced: with template
self._mode = True
self._tmpl_data = tmpl[u'data']
if regex_compile:
self._tmpl_data = re.compile(self._tmpl_data)
#if hasattr(self, '_param'): # [JIRA: DRTRIGON-8, DRTRIGON-32]
self._param['ignorepage_list'].append(self._tmpl_data)
# update template and content
tmpl[u'timestamp'] = u'--~~~~'
tmpl_text = pywikibot.glue_template_and_params(
(self._bot_config['TemplateName'], tmpl))
tmpl_pos = self._template_regex.search(self._content)
self._content = (self._content[:tmpl_pos.start()] + tmpl_text +
self._content[tmpl_pos.end():])
## @todo the error correctors 'old history' and 'notify tag error' can be removed if
# they do not appear in bot logs anymore!
# \n[ JIRA: e.g. DRTRIGON-68 ]
def loadHistory(self, rollback=0):
"""Read history, and restore the page objects with sum_disc_data.
@param rollback: Number of history entries to go back (re-use older
history).
@type rollback: int
Returns nothing, but feeds to self.pages class instance.
"""
buf = self._loadFile()
buf = bot_config['page_regex'].sub('[]', buf)
buf = _REGEX_eol.split(buf)
# modified due: http://de.wikipedia.org/wiki/Benutzer:DrTrigonBot/ToDo-Liste (id 17)
# merge everything to one history
news = {}
usage = {}
rollback_buf = []
hist = {}
for item in buf:
if len(item.strip()) == 0:
continue
news_item = eval(item)
#news.update(news_item)
# news.update BUT APPEND the heading data in the last tuple arg
for key in news_item.keys():
# old history format
# (after compression not needed anymore and can thus be removed in the future)
if (len(news_item[key]) == 5):
news_item[key] += (_PS_unchanged,)
usage['old history'] = True
# notify tag error
# (origin could be 'old history' but is not clear, but can be
# removed in the future, eg. after comp.)
if (news_item[key][0] == u'Notification') and (
news_item[key][5] != _PS_notify):
news_item[key] = news_item[key][:-1] + (_PS_notify,)
usage['notify tag error'] = True
if key in news: # APPEND the heading data in the last tuple arg
if news_item[key][5] in [_PS_closed]:
del news[key]
else:
heads = news[key][4]
heads.update(news_item[key][4])
#news[key] = (news_item[key][0], news_item[key][1], news_item[key][2], news_item[key][3], heads, news_item[key][5])
news[key] = news_item[key][:4] + (heads,
news_item[key][5])
else:
news[key] = news_item[key]
rollback_buf.append(copy.deepcopy(news))
if rollback_buf:
rollback_buf.reverse()
i = min([rollback, (len(rollback_buf) - 1)])
hist = rollback_buf[i]
del rollback_buf
usage['rollback'] = i
# feed data to pages
self.pages.hist = hist
pywikibot.output(
u'\03{lightpurple}*** History recieved %s\03{default}' % str(usage))
def putHistory(self, data_dict):
"""Write history.
Returns nothing but the history file gets filled with archived entries.
"""
# extract important data from page list
buf = {}
for key in data_dict.keys():
buf[key] = data_dict[key].sum_disc_data
# write new history
self._appendFile(str(buf))
pywikibot.output(u'\03{lightpurple}*** History updated\03{default}')
def _loadFile(self):
'''
load data (history) file
input: self-objects
returns: file content [string]
'''
# unicode text schreiben, danke an http://www.amk.ca/python/howto/unicode
try:
datfile = codecs.open(self._datfilename,
encoding=config.textfile_encoding, mode='r')
#datfile = open(self._datfilename, mode='rb')
buf = datfile.read()
datfile.close()
return buf
except:
return u''
def _appendFile(self, data):
'''
append data (history) to file
input: data
self-objects
returns: (appends data to the data/history file, nothing else)
'''
# könnte history dict mit pickle speichern (http://www.thomas-guettler.de/vortraege/python/einfuehrung.html#link_12.2)
# verwende stattdessen aber wiki format! (bleibt human readable und kann in wiki umgeleitet werden bei bedarf)
datfile = codecs.open(self._datfilename,
encoding=config.textfile_encoding, mode='a+')
#datfile = codecs.open(self._datfilename, encoding='zlib', mode='a+b')
datfile.write(u'\n\n' + data)
#datfile.write(data)
datfile.close()
def checkRecentEdits(self):
"""Check wiki on recent contributions of specific user.
Returns nothing, but feeds to self.pages class instance.
"""
check_list = self._param['checkedit_list']
count = self._param['checkedit_count']
# thanks to http://www.amk.ca/python/howto/regex/ and http://bytes.com/forum/thread24382.html
#usersumList = [p.title() for p in pagegenerators.UserContributionsGenerator(self._user.name(), number = count)]
usersumList = [p[0].title() for p in
self._user.contributions(limit=count)]
work = {}
for item in usersumList:
#item = item[0]
for check in check_list:
match = check.search(item)
if match:
#work[match.group(1)] = ()
name = match.group(1)
page = pywikibot.Page(self.site, name)
page.sum_disc_data = ()
work[name] = page
break # should only match one of the possibilities, anyway just add it once!
pywikibot.output(u'\03{lightpurple}*** Latest %i Contributions '
u'checked\03{default}' % len(usersumList))
# feed data to pages
self.pages.update_work(work)
## @todo generate a time sorted backling list and use the 2000 newest ones!
# \n[ JIRA: DRTRIGON-8 ]
def getUserBacklinks(self):
"""Check wiki on backlinks to specific user.
Returns nothing, but feeds to self.pages class instance.
"""
check_list = self._param['checkedit_list']
userbacklinksList = []
for item in self._param['backlinks_list']:
page = pywikibot.Page(self.site, item) # important for the generator to use the API
#userbacklinksList += [p.title() for p in pagegenerators.ReferringPageGenerator(page, withTemplateInclusion=False)]
userbacklinksList += [p.title() for p in
page.getReferences(
withTemplateInclusion=False)]
userbacklinksList = list(set(userbacklinksList)) # drop duplicates
work = {}
count = 0
# (some return >> 500 backlinks, thus check
# only once a week ALL/2000 those, else limit)
if (self._wday == 6): # So
#max_count = len(userbacklinksList)
max_count = 2000
else:
max_count = 500
for item in userbacklinksList:
count += 1
# drop the rest if limited
if (len(work) > max_count):
break
#item = item[0]
for check in check_list:
match = check.search(item)
if match:
#work[match.group(1)] = ()
name = match.group(1)
page = pywikibot.Page(self.site, name)
page.sum_disc_data = ()
work[name] = page
break # should only match one of the possibilities, anyway just add it once!
pywikibot.output(u'\03{lightpurple}*** %i Backlinks to user checked '
u'(limited to %i)\03{default}'
% (len(userbacklinksList), max_count))
# feed data to pages
self.pages.update_work(work)
## @todo speed up by catching all pages (used the same day) to disk, look into diskcache.py (@ref diskcache)
# \n[ JIRA: ticket? (think about it!) ]
# @todo preloading does not use API yet, should be done within pywikipedia framework
# \n[ JIRA: ticket? ]
# @todo wikipedia.Page.getVersionHistory() is not able to check page exceptions always and
# crashes sometimes, u'Benutzer Diskussion:MerlBot' for example
# \n[ JIRA: ticket? ]
def getLatestRelevantNews(self):
"""Check latest contributions on recent news and check relevancy of
page by splitting it into sections and searching each for specific
users signature, this is all done by PageSections class.
Returns nothing, but feeds to self.pages class instance.
"""
# check for news to report
hist = self.pages.hist
work = self.pages.work
self.pages.start_promotion()
gen1 = pagegenerators.PagesFromTitlesGenerator(work.keys())
gen2 = pagegenerators.RegexFilterPageGenerator(
gen1,
self._param['ignorepage_list'],
inverse=True,
ignore_namespace=False)
# Preloads _contents and _versionhistory / [ JIRA: ticket? ]
# WithoutInterwikiPageGenerator,
#gen3 = pagegenerators.PreloadingGenerator(gen2)
gen3 = tools.ThreadedGenerator(
target=pagegenerators.PreloadingGenerator, args=(gen2, ), qsize=60)
self._th_gen = gen3
#gen4 = pagegenerators.RedirectFilterPageGenerator(gen3)
# lets hope that no generator loses pages... (since sometimes this may happen)
for page in gen3:
if _debug_switch['page'](page):
pywikibot.warning(u'\03{lightyellow}=== ! PAGE WILL BE SKIPPED '
u'! ===\03{default}')
continue
name = page.title()
#print ">>>", name, "<<<"
page.sum_disc_data = work[name].sum_disc_data
# get history (was preloaded)
#actual = actual_dict[page.sectionFreeTitle()]
# use preloaded with revCount=1
try:
actual = page.getVersionHistory(revCount=1)
# check page exceptions / [ JIRA: ticket? ]
if hasattr(page, u'_getexception'):
raise page._getexception
except pywikibot.NoPage:
pywikibot.output(u'Problem accessing not available (deleted) '
u'page at %s, skipping...'
% page.title(asLink=True))
continue
except pywikibot.IsRedirectPage:
pywikibot.output(
u'Problem using redirect page at %s, skipping...'
% page.title(asLink=True))
continue
# actual/new status of page, has something changed?
news = False
if name in hist:
if (not (hist[name].sum_disc_data[3] == actual[0][1])):
# discussion has changed, some news?
self.pages.edit_news(page,
sum_disc_data=(
self._param['notify_msg'][_PS_changed],
None, # obsolete (and recursive)
actual[0][2],
actual[0][1],
hist[name].sum_disc_data[4],
_PS_changed))
news = True
else:
# nothing new to report (but keep for history and update it)
self.pages.edit_oth(page,
sum_disc_data=(
hist[name].sum_disc_data[0],
None, # obsolete (and recursive)
actual[0][2],
actual[0][1],
hist[name].sum_disc_data[4],
_PS_unchanged))
else:
# new discussion, some news?
self.pages.edit_news(page,
sum_disc_data=(
self._param['notify_msg'][_PS_new],
None, # obsolete (and recursive)
actual[0][2],
actual[0][1],
{},
_PS_new))
news = True
# checkRelevancy: Check relevancy of page by splitting it into sections and searching
# (date in page history has changed)
if not news:
continue
self.pages.promote_page() # hist -> news
try:
entries = PageSections(page, self._param, self._user)
(page, page_rel, page_signed) = entries.check_rel()
# update sum_disc_data in page (checksums, relevancies, ...)
self.pages.edit_news(page)
self.pages.edit_hist(page)
# if page is not relevant, don't list discussion
if not page_rel:
self.pages.promote_page_irrel(page, page_signed)
# free the memory again
del entries
except pywikibot.IsRedirectPage:
self.pages.promote_page_irrel(page, False)
pywikibot.output(u'Problem using redirect page at %s, tagging '
u'irrelevant...' % page.title(asLink=True))
gen3.stop()
del self._th_gen
self.pages.end_promotion()
pywikibot.output(u'\03{lightpurple}*** Latest News searched and '
u'relevancy of threads checked\03{default}')
def AddGlobWikiNotify(self):
"""Check if there are any global wiki notifications and add them to
every users news.
Returns nothing, but feeds to self.pages class instance.
"""
hist = self.pages.hist
# get global wiki notifications (toolserver/merl)
if pywikibot.simulate:
pywikibot.warning(u'\03{lightyellow}=== ! TOOLSERVER ACCESS WILL '
u'BE SKIPPED ! ===\03{default}')
globalnotify = []
else:
globalnotify = self._globalnotifications()
# check for GlobalWikiNotifications to report
localinterwiki = self.site.language()
count = 0
try:
if hasattr(self, '_skip_globwikinotify'):
raise pywikibot.MaxTriesExceededError
for (page, data) in globalnotify:
count += 1
# skip to local disc page, since this is the only page the user
# should watch itself
if (page.site().language() == localinterwiki) and \
(page.site().family.name == u'wikipedia'):
pywikibot.warning(
u'skipping global wiki notify to local wiki %s'
% page.title(asLink=True))
continue
# actual/new status of page, has something changed?
if (data[u'link'] in hist.keys()) and (
data[u'timestamp'] ==
hist[data[u'link']].sum_disc_data[3]):
continue
#data = page.globalwikinotify
self.pages.edit_oth(page,
sum_disc_data=(
self._param['notify_msg'][_PS_notify],
None, # obsolete (and recursive)
data['user'],
data['timestamp'],
{u'': ('', True, u'')},
_PS_notify),