Source

wikibots / commonsbot.py

The default branch has multiple heads

  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
#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
    CommonsNotification Bot
        by ErrantX
   
   Version: r97
   
   Watches commons for Speedy nominations and image deletions and 
   notifies various places on Wikipedia if the images are used there.
   
"""
import os
import urllib2, urllib
import logging
import time, datetime
import json
import pywikibot
from pywikibot import catlib, pagegenerators
from pywikibot.data import api
import botconfig
import notifo
import re

__VERSION__ = "r97"
__AUTHOR__ = "ErrantX"
__BOTUSER__ = "CommonsNotificationBot"

def load_nominated_cats():
    # deletion cats
    nominated = []
    cat = catlib.Category(commons,'Category:Deletion requests')  
    for sub in cat.subcategories():
        if sub.title(withNamespace=False) not in ["Non-media deletion requests"," Incomplete deletion requests "]:
            nominated.append(DeletionCategory(sub.title(withNamespace=False),"nominated"))
    return nominated
    
def load_unsourced_cats():
    # deletion cats
    nominated = []
    cat = catlib.Category(commons,'Category:Media without a source')  
    for sub in cat.subcategories():
        if sub.title(withNamespace=False) not in ["Media without a source as of unknown date"]:
            nominated.append(DeletionCategory(sub.title(withNamespace=False),"nominated"))
    return nominated
    
def load_en_cats():
    # deletion cats
    enCSD = []
    cat = catlib.Category(wikipedia,'Category:Candidates for speedy deletion as files with unacceptable licenses')  
    for sub in cat.subcategories():
        enCSD.append(EnDeletionCategory(sub.title(withNamespace=False),"speedy"))
    cat = catlib.Category(wikipedia,'Category:Wikipedia files with unknown copyright status')
    for sub in cat.subcategories():
        if sub.title(withNamespace=False) not in ["All Wikipedia files with unknown source","Wikipedia files with unknown source for deletion in dispute"]:
            enCSD.append(EnDeletionCategory(sub.title(withNamespace=False),"speedy"))
    cat = catlib.Category(wikipedia,'Category:Wikipedia files with no non-free use rationale')
    for sub in cat.subcategories():
        if sub.title(withNamespace=False) not in ["All Wikipedia files with no non-free use rationale","Wikipedia files that transclude the Non-free media rationale template with no Purpose specified","Publicity photographs with missing fair-use rationale"]:
            enCSD.append(EnDeletionCategory(sub.title(withNamespace=False),"speedy"))
    cat = catlib.Category(wikipedia,'Category:Wikipedia files missing permission')  
    for sub in cat.subcategories():
        enCSD.append(EnDeletionCategory(sub.title(withNamespace=False),"speedy"))
    return enCSD    

def bot_summary(text):
    return "%s ([[User_talk:ErrantX|feedback]], Version [[User:%s/changelog|%s]])" % (text,__BOTUSER__,__VERSION__)

def is_dev():
    # is this bot in dev mode
    return (config.get("root","mode") == "development")
    
def fix_commons_links(text):
    # fixes links to commons
    return text.replace("[[","[[commons:").replace("=","{{=}}")
    
def get_page_prefix():
    #Checks for development mode; if activated then returns a prefix to make sure the bot operates in user space
    if is_dev():
        return "User:%s/%s/" % (__BOTUSER__,__VERSION__)
    return ""   
     
def get_usernamespace():
    # returns the bots user namespace WITHOUT trailing slash
    return "User:%s" % __BOTUSER__
    
def write_tracking_log():
    global tracking_log_written
    text = ""
    for image in tracked_images:
        if not tracked_images[image].expired():
            text += tracked_images[image].logentry()
    # write it locally first
    try:
        local_log = open(tracking_log_file, "w")
        local_log.write(text)
        local_log.close()
    except:
        logging.error("Unable to write tracking log: %s " % tracking_log_file)
    # only write the tracking log every hour
    if (int(time.time()) - tracking_log_written) > 7200:
        if is_dev():
            page = pywikibot.Page(wikipedia,"%s%s" % (get_page_prefix(),config.get("pages","tracking_log")))
        else:
            page = pywikibot.Page(wikipedia,"%s/%s" % (get_usernamespace(),config.get("pages","tracking_log")))
        page.put(text,"Updating log file")
        tracking_log_written = int(time.time())
        logging.info("Wrote MediaWiki tracking log")
    
def load_tracking_log():
    if is_dev():
        page = pywikibot.Page(wikipedia,"%s%s" % (get_page_prefix(),config.get("pages","tracking_log")))
    else:
        page = pywikibot.Page(wikipedia,"%s/%s" % (get_usernamespace(),config.get("pages","tracking_log")))

    try:
        if os.path.isfile(tracking_log_file):
            local = int(os.stat(tracking_log_file).st_mtime)
        else:
            local = False
        remote = int(time.mktime(time.strptime(page.editTime(),"%Y-%m-%dT%H:%M:%SZ")))
        if local == False or remote > local:
            logging.info("Loading remote tracking data")
            log = page.get()
        else:
            logging.info("Loading local tracking data")
            fp = open(tracking_log_file,"r")
            log = fp.read()
            fp.close()
        for entry in log.split("\n"):
            name = entry.split("|")
            if len(name) == 7:
                image = Image(name[0])
                image.parselog(entry)
                if not image.expired():
                    tracked_images[image.nicetitle()] = image
        logging.info("Loaded %s entries" % len(tracked_images))
    except IOError:
        pass

def mark_online():
    if is_dev():
        status_page("devstatus","DEV","online|#00aa00|#BBDDBB","Bot (development) Online")
    else:
        status_page("botstatus","BOT","online|#00aa00|#BBDDBB","Bot (production) Online")
    
def mark_offline():
    if is_dev():
        status_page("devstatus","DEV","offline|#DD3333|#DDBBBB","Bot (development) Offline")
    else:
        status_page("botstatus","BOT","offline|#DD3333|#DDBBBB","Bot (production) Offline")

def status_page(page,code,status,summary):
    pywikibot.Page(wikipedia,"%s/%s" % (get_usernamespace(),page)).put("{{User:%s/statusbox|%s|%s|%s|%s}}" % (__BOTUSER__,code,__VERSION__,status,time.strftime("%Y-%m-%d %H:%M")),bot_summary(summary))
    
class Notification:
    """
        Used to hold methods that notify various pages
    """
    def __init__(self):
        if is_dev():
            self.notify = True
        else:
            self.notify = True
        
    def article_talk_deletion(self,page,image,user,reason):
        summary = "Notification of deletion of [[:commons:%s|%s]]" % (image.nicetitle(),image.nicetitle())
        text = "{{subst:%s/article_image_deletion|%s|%s|%s}}" % (get_usernamespace(),image.nicetitle(),user,reason)
        self.write(page,text,summary,"%s Deleted" % image.nicetitle())
        
    def article_talk_notification(self,page,image,deletion_type,reason):
        try:
            summary = "Notification of possible deletion of [[:commons:%s|%s]]" % (image.nicetitle(),image.nicetitle())
            text = "{{subst:%s/article_image_notification_%s|%s|%s|%s}}" % (get_usernamespace(),deletion_type,image.nicetitle(),deletion_type,reason)
            multi_summary = "[[:%s]] has been nominated for %s deletion for the following reason: ''%s''" % (image.nicetitle(),deletion_type,reason)
            #self.write(page,text,summary,"%s Nominated" % image.nicetitle())
            self.write(page,text,summary,"%s Nominated" % image.nicetitle(),image.nicetitle(),multi_summary)
        except:
            pass
          
    def article_talk_notification_en(self,page,image,deletion_type,reason):
        try:
            summary = "Notification of possible deletion of [[%s]]" % image.nicetitle()
            text = "{{subst:%s/article_image_notification_%s_en|%s|%s|%s}}" % (get_usernamespace(),deletion_type,image.nicetitle(),deletion_type,reason)
            multi_summary = "[[:%s]] has been nominated for %s deletion for the following reason: ''%s''" % (image.nicetitle(),deletion_type,reason)
            self.write(page,text,summary,"%s Nominated" % image.nicetitle(),image.nicetitle(),multi_summary)
        except:
            pass
       
    def central_deletion(self,image,user,reason):
        try:
            summary = "Notification of deletion of [[:commons:%s|%s]]" % (image.nicetitle(),image.nicetitle())
            text = "{{subst:%s/central_image_deletion|%s|%s|%s}}" % (get_usernamespace(),image.nicetitle(),user,reason)
            #self.write("Wikipedia:Administrators' noticeboard",text,summary,"%s Deleted" % image.nicetitle())
            #self.write("Wikipedia:Village pump (miscellaneous)",text,summary,"%s Deleted" % image.nicetitle())
        except:
            pass
       
    def central_notification(self,image,deletion_type,reason):
        try:
            summary = "Notification of possible deletion of [[:commons:%s|%s]]" % (image.nicetitle(),image.nicetitle())
            text = "{{subst:%s/central_image_notification_%s|%s|%s|%s}}" % (get_usernamespace(),deletion_type,image.nicetitle(),deletion_type,reason)
            #self.write("Wikipedia:Administrators' noticeboard",text,summary,"%s Nominated" % image.nicetitle())
            #self.write("Wikipedia:Village pump (miscellaneous)",text,summary,"%s" % image.nicetitle())
        except:
            pass
       
    def central_notification_en(self,image,deletion_type,reason):
        try:
            summary = "Notification of possible deletion of [[%s]]" % image.nicetitle()
            text = "{{subst:%s/central_image_notification_%s_en|%s|%s|%s}}" % (get_usernamespace(),deletion_type,image.nicetitle(),deletion_type,reason)
            #self.write("Wikipedia:Administrators' noticeboard",text,summary,"%s Nominated" % image.nicetitle())
            #self.write("Wikipedia:Village pump (miscellaneous)",text,summary,"%s" % image.nicetitle())
        except:
            pass
        
    def write(self,page,text,summary,heading,multi=None,multi_text=None):
        # get the full page to load/write
        page = "%s%s" % (get_page_prefix(),page)
        # if notification is disabled...
        if not self.notify:
            logging.debug("Would have written to page: %s - %s" % (page,heading))
        else:
            page = pywikibot.Page(wikipedia,"%s" % page)
            current = ""
            try:
                current = page.get()
            except:
                pass
            finally:
                try:
                    # if we have already notified, do not bother
                    if current.find(heading) == -1:
                        if multi:
                            # test for other prior notifications
                            if self.parse_time(current):
                                # yep
                                theimages = imageslist.findall(current)
                                if len(theimages) > 0:
                                    oldimages = theimages[0].split("\n")
                                    newimages = "The following images, used in this article, have been nominated for deletion:\n"
                                    for image in oldimages:
                                        # check image isn't already mentioned
                                        if multi in image:
                                            logging.info("Not placing notification because one already exists")
                                            return
                                        if image != "The following images, used in this article, have been nominated for deletion:" and image != "":
                                            newimages = "%s\n* %s" % (newimages,image.replace("An image used in this article, ","").replace("* ","")) 
                                    newimages = "%s\n* %s" % (newimages,multi_text)
                                new = str(current).replace(theimages[0],newimages)
                                page.put(new,bot_summary(summary))
                                return
                            if current.find(multi_text) > -1:
                                # already got a multi note
                                return
                        # otherwise place a notification at the bottom
                        logging.info("Writing: %s - %s" % (page,heading))
                        page.put("%s\n%s" % (current,text),bot_summary(summary))
                    else:
                        logging.info("Not placing notification because one already exists")
                except:
                    logging.warning("Unable to write page!")
    def parse_time(self,text):
        try:
            thetime = tstamp.findall(text)
            thetime = time.mktime(time.strptime(thetime[0],"%H:%M, %d %B %Y"))
            if int(thetime) > (int(time.time()) - 18000):
                return True
            return None
        except:
            return None
class NotificationLog:
    """
        Class to help with editing the notification log
    """
    def __init__(self,page_name,template):
        self.name = page_name
        self.images = []
        self.added = 0
        self.removed = 0
        self.template = template
        self.load()
        
    def add(self):
        raise NotImplementedError,"add method only available in sub-class"  
    def write(self):
        raise NotImplementedError,"write method only available in sub-class"  
            
    def _write(self,text,summary):
        try:
            log_page = pywikibot.Page(wikipedia,self.name)
            log_page.put(text,bot_summary(summary))
        except pywikibot.exceptions.PageNotSaved:
            logging.warning("Empty log page")
      
   
class DeletedImagesLog(NotificationLog):

    def load(self):
        # load the log data from our tracking dict
        for image_name in tracked_images:
            image = tracked_images[image_name]
            if image.deleted != None and len(image.delete_details) == 2:
                self.images.append((image,image.delete_details["user"],image.delete_details["reason"]))

    def write(self):
        try:
            pagetext = ""
            toremove = []
            for image,user,reason in self.images:
                alluses,articles = image.fileusage()
                # Only write it back if image has not expired (over 7 days) and it is still in used
                if len(alluses) > 0 and not image.expired():
                    logging.debug("Writing %s, timestamped %s" % (image.nicetitle(),image.updated))
                    pagetext += "\n<!--%s-->\n{{%s/%s|%s|%s|%s|%s|%s}}" % (image.updated,get_usernamespace(),self.template,image.nicetitle(),user,reason,len(alluses),len(articles))
                else:
                    self.removed += 1
                    toremove.append((image,user,reason))
                    logging.info("Removing %s, timestamped %s" % (image.nicetitle(),image.updated))
            for entry in toremove:
                try:
                    self.images.remove(entry)
                except:
                    pass
            self._write(pagetext,"Updated log (%s added, %s removed)" % (self.added,self.removed))
            self.added = 0
            self.removed = 0
        except:
            pass
        
    def add(self,image,user,reason):
        if (image,user,reason) not in self.images:
            self.images.insert(0,(image,user,reason))
            self.added += 1
        
class MarkedForDeletionLog(NotificationLog):

    def load(self):
        # load the log data from our tracking dict
        for image_name in tracked_images:
            image = tracked_images[image_name]
            if image.speedy != None and len(image.speedy_details) == 2:
                self.images.append((image,image.speedy_details["reason"],image.speedy_details["type"]))
                        
    def write(self): 
        pass
        
    def add(self,image,reason,deletion_type):
        if (image,reason,deletion_type) not in self.images:
            self.images.insert(0,(image,reason,deletion_type))
            self.added += 1
            
class Image:
    def __init__(self,img_name):
        self.name = img_name
        self.updated = int(time.time())
        self.speedy = None
        self.speedy_details = {}
        self.delete_details = {}
        self.deleted = None
        self._alluses = None
        self._articles = None
        self._last_checked = 0
        self._is_local = None
        # check for local image
        if pywikibot.Page(wikipedia,self.name).exists() == True:
            # the image is uploaded locally to we can ignore it
            self._is_local = True
            
    def local(self):
        return self._is_local
        
    def nicetitle(self):
        #return self.name.replace("%3A",":").replace("_"," ").replace("%2C",",")
        try:
            return urllib.unquote(self.name).replace("_"," ")
        except:
            # the above has a tendency to fail...
            return self.name.replace("_"," ")
        
    def fileusage(self):
        if (not self._alluses and not self._articles) or (int(time.time()) - self._last_checked) > 1800:
            self._alluses = self.usage()
            # pause briefly
            time.sleep(3)  
            self._articles = self.usage(0) 
            self._last_checked = int(time.time())
        return self._alluses, self._articles
        
    def is_marked_for_speedy_deletion(self,reason,deletion_type):
        if self.speedy == None and not self._is_local:
            # first time we have spotted this marked for speedy deletion
            alluses,articles = self.fileusage()
            if len(alluses) > 0:
                # file is used on Wikipedia
                self.speedy_details = {"reason" : reason, "type": deletion_type}
                marked_for_deletion_log.add(self,reason,deletion_type)
                if len(articles) > 50 or len(alluses) > 75:
                    # central notification
                    notification.central_notification(self,deletion_type,reason)
                else:
                    for page in articles:
                        notification.article_talk_notification("Talk:%s" % articles[page]["title"],self,deletion_type,reason)
            self.speedy = int(time.time())
        self.updated = int(time.time())
        
    def is_marked_for_speedy_deletion_en(self,reason,deletion_type):
        if self.speedy == None:
            
            # first time we have spotted this marked for speedy deletion
            alluses,articles = self.fileusage()
            if len(alluses) > 0:
                # file is used on Wikipedia
                self.speedy_details = {"reason" : reason, "type": deletion_type}
                marked_for_deletion_log.add(self,reason,deletion_type)
                if len(articles) > 50 or len(alluses) > 75:
                    # central notification
                    notification.central_notification_en(self,deletion_type,reason)
                else:
                    for page in articles:
                        notification.article_talk_notification_en("Talk:%s" % articles[page]["title"],self,deletion_type,reason)
            self.speedy = int(time.time())
        self.updated = int(time.time())
        
     
    def still_commons(self):
        return pywikibot.Page(commons,self.name).exists()
        
    def is_deleted(self,log):
        if self.deleted == None and not self._is_local:
            # also check for existence on commons
            if self.still_commons():
                logging.info("Not notifying about %s, image still available on commons" % (self.nicetitle()))
                return
            alluses,articles = self.fileusage()
            if len(alluses) > 0:
                # file is used on Wikipedia
                deleted_images_log.add(self,log.user(),fix_commons_links(log.comment()))
                self.delete_details = {"user": log.user(), "reason": fix_commons_links(log.comment())}
                if len(articles) > 50 or len(alluses) > 75:
                    # central notification
                    notification.central_deletion(self,log.user(),fix_commons_links(log.comment()))
                #else:
                #    for page in articles:
                #        notification.article_talk_deletion("Talk:%s" % articles[page]["title"],self,log.user(),fix_commons_links(log.comment()))
            self.deleted = int(time.time())
        self.updated = int(time.time())
        
    def logentry(self):
        # create a log entry for tracking this image for writing to /track
        return "%s|%s|%s|%s|%s|%s|%s\n" % (self.name,self.updated,self.speedy,self.deleted,self._is_local,json.dumps(self.speedy_details).replace("{{","{{t|"),json.dumps(self.delete_details).replace("{{","{{t|"))
        
    def parselog(self,logentry):
        # load details from log
        log = logentry.split("|")
        self.updated = int(log[1])
        if log[2] == "None":
            self.speedy = None
        else:
            self.speedy = int(log[2])
            self.speedy_details = json.loads(log[5])
        if log[3] == "None":
            self.deleted = None
        else:
            self.deleted = int(log[3])
            self.delete_details = json.loads(log[6])
        if log[4] == "None":
            self._is_local = None
        else:
            self._is_local = True

    def expired(self):
        return ((int(time.time()) - self.updated) >  604800)
        
    # gets a list of pages where a file appears
    def usage(self,namespace=None):
        params = {"action":"query","giulimit":500,"generator":"imageusage","format":"json"}
        if namespace is not None:
            params["giunamespace"] = namespace
        uri = "http://en.wikipedia.org/w/api.php?%s&giutitle=%s" % (urllib.urlencode(params),self.name)
        try:
            loaded = json.loads(urllib2.urlopen(uri).read())
            if "query" in loaded:
                return loaded["query"]["pages"]
        except:
            pass
        return []

        
class DeletionCategory:
    def __init__(self,cat_name,deletion_type="speedy"):
        self.name = cat_name
        self._cat = None
        self.deletion_type = deletion_type
        
    # get the list of files
    def get(self,refresh=False):
        if not self._cat or refresh is True:
            self._cat = catlib.Category(commons,'Category:%s' % self.name)  
        return self._cat
        
    # check for new pages
    def check(self):
        cat = self.get(True)
        for image in cat.articles():
            logging.info("Checking %s" % image.title())
            if image.title() not in tracked_images:
                tracked_images[image.title()] = Image(image.title(asUrl=True))
            tracked_images[image.title()].is_marked_for_speedy_deletion(self.name,self.deletion_type)
            
class EnDeletionCategory(DeletionCategory):
    # As above, but for en.wiki
    
    def get(self,refresh=False):
        if not self._cat or refresh is True:
            self._cat = catlib.Category(wikipedia,'Category:%s' % self.name)  
        return self._cat
        
    def check(self):
        cat = self.get(True)
        for image in cat.articles():
            logging.info("Checking %s" % image.title())
            if image.title() not in tracked_images:
                tracked_images[image.title()] = Image(image.title(asUrl=True))
            tracked_images[image.title()].is_marked_for_speedy_deletion_en(self.name,self.deletion_type)
               
class DeletionTracker:
    def check(self,starttime,endtime):
        for log in commons.logevents("delete",end=starttime,start=endtime):
            if log.ns() == 6:
                logging.info("Checking %s" % log.title().title())
                image = log.title()
                if image.title() not in tracked_images:
                    tracked_images[image.title()] = Image(image.title(asUrl=True))
                tracked_images[image.title()].is_deleted(log)

# the main checks to be run
def main():
    global starttime
    # check for deletions
    endtime = int(time.time())
    deletions.check(starttime,endtime)
    # reset starttime
    starttime = endtime
    # write log page
    deleted_images_log.write()
    # check cats
    copyvio.check()
    otrs.check()
    other.check()
    #flickr.check()
    # nominated
    for nomination_cat in load_nominated_cats():
        nomination_cat.check()
    # unsourced
    for unsourced_cat in load_unsourced_cats():
        unsourced_cat.check()
    # enwiki
    for enwiki_cat in load_en_cats():
        enwiki_cat.check()
    # write log page
    #marked_for_deletion_log.write()
    # write a logging page to track current status
    write_tracking_log()


# Config
bconfig = botconfig.BotConfig("commonsbot")
# load the default file as "config"
config = bconfig.default()

# set up loggin
if is_dev():
    # show DEBUG messages & do so in console
    logging.basicConfig(level=logging.DEBUG)
    __VERSION__ = "dev"
else:
    # otherwise log to file
    logging.basicConfig(level=logging.DEBUG)

logging.info("Commons Notification Bot (%s), %s mode" % (__VERSION__,config.get("root","mode")))

# set up some re
tstamp = re.compile("\(\[\[User talk:CommonsNotificationBot\|talk\]\]\) ([0-9]{2}:[0-9]{2}, [0-9]{2} [A-Za-z]+ [0-9]{4}) \(UTC\)")
imageslist = re.compile("<!--IMAGES-->(.*)<!--/IMAGES-->",re.S)

# pywikibot sites
commons = pywikibot.getSite()
wikipedia = pywikibot.getSite("en","wikipedia")

try:
    # online :)
    mark_online()

    # some initial variables
    tracked_images = {}
    starttime = int(time.time())
    tracking_log_written = 0
    tracking_log_file = os.path.join(bconfig.cfgpath(),"commonsbot-tracking-log.txt")


    # load the tracking log
    #load_tracking_log()
        
    # notification logs, pages & classes
    if is_dev():
        log_prefix = get_page_prefix()
    else:
        log_prefix = "%s/" % get_usernamespace()
    marked_for_deletion_log = MarkedForDeletionLog("%smarked" % log_prefix,"marked_for_deletion")
    deleted_images_log = DeletedImagesLog("%slog" % log_prefix,"deleted_images")
    notification = Notification()

    #categories
    copyvio = DeletionCategory("Copyright violations")
    otrs = DeletionCategory("No OTRS permission")
    other = DeletionCategory("Other speedy deletions")
    flickr = DeletionCategory("Unsourced Flickr images reviewed by FlickreviewR")
    
    # Deletion tracker
    deletions = DeletionTracker()
 
    while True:
            logging.info("Checking for new Commons Deletions & Speedy Nominations")
            # run the checks
            main()
            # sleep for about 3 minutes
            logging.info("Sleeping for 15 Minutes")
            time.sleep(900)   
except KeyboardInterrupt:
    # we tried for a shutdown
    logging.info("User ShutDown, please wait...")
    # force saving the tracking log
    tracking_log_written = 0
    write_tracking_log()
    # write the status page
    mark_offline()
    #finish logging
    logging.shutdown()
    # and exit
    import sys
    sys.exit()
except:
    # catch all other exceptions (crashes)
    # print the error
    import traceback,sys
    traceback.print_exc()
    # force saving the tracking log
    tracking_log_written = 0
    write_tracking_log()
    # at least try to mark as offline
    mark_offline()
    # and also try to notify owner
    notifo.send_message(config.get("notifo","username"),config.get("notifo","api_key"),"%s (%s) crashed" % (__BOTUSER__,__VERSION__))
    sys.exit()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.