Bikarhêner:Balyozxane/skrîpt/py/log wikidata.py

import pywikibot
from pywikibot.comms import eventstreams

def has_bot_rights(username):
    site_wikidata = pywikibot.Site("wikidata", "wikidata")
    user_page = pywikibot.User(site_wikidata, username)
    return 'bot' in user_page.groups()

def log_change(user_page, item_id, user, timestamp, edit_summary):
    # Append the information to the user page on ku.wikipedia.org
    log_entry = f"\n|-\n|{{{{wde|{item_id}}}}}\n|{user}\n|{timestamp}\n|<nowiki>{edit_summary}</nowiki>\n"
    
    # Find the index of the last occurrence of '|}'
    last_pipe_brace_index = user_page.text.rfind('|}')
    
    # Insert the new log entry before '|}'
    user_page.text = user_page.text[:last_pipe_brace_index] + log_entry + user_page.text[last_pipe_brace_index:]
    
    print(f"Log saved for {item_id}")
    
    # Save the modified text
    user_page.save(summary=f"Update log with Wikidata change - {edit_summary}")

def monitor_and_log_changes():
    site_wikidata = pywikibot.Site("wikidata", "wikidata")
    site_kuwiki = pywikibot.Site("ku", "wikipedia")

    # Specify the target user page on ku.wikipedia.org
    user_page_title = "User:Balyozxane/log wikidata.py/log"
    user_page = pywikibot.Page(site_kuwiki, user_page_title)

    # Set to keep track of already logged items and their timestamps
    logged_items = set()

    try:
        print("Starting Wikidata monitor...")

        # Create an EventStreams object for recent changes
        stream = eventstreams.EventStreams(streams=['recentchange'])

        # Infinite loop to continuously monitor recent changes
        for event in stream:
            try:
                if event['type'] == 'edit' and event['wiki'] == 'wikidatawiki':
                    # Check if the change is related to descriptions in Kurdish
                    if ('wbsetdescription-add:1|ku-latn' in event['comment'] or
                            'wbsetdescription-set:1|ku-latn' in event['comment'] or
                            'wbeditentity-update-languages-short:0||ku' in event['comment'] or
                            'wbsetdescription-add:1|ku' in event['comment'] or
                            'wbsetdescription-set:1|ku' in event['comment']):

                        # Check if "quickstatements/#/batch" is in the comment
                        if 'quickstatements/#/batch' in event['comment']:
                            print(f"Ignoring edit with 'quickstatements/#/batch' comment for {item_id}")
                            continue
                    
                        item_id = event['title']
                        timestamp = event['timestamp']
                        user = event['user']
                        if user != 'Balyozxane':
                            # Check if the item and timestamp are already logged
                            if (item_id, timestamp) not in logged_items:
                                edit_summary = event['comment']

                                if has_bot_rights(user):
                                    print(f"{user} has bot rights on Wikidata.")
                                else:
                                    print(f"{user} does not have bot rights on Wikidata.")
                                    # Call the log_change function
                                    print(f"Edit by {user} found for {item_id}")
                                    log_change(user_page, item_id, user, timestamp, edit_summary)

                                    # Add the item and timestamp to the set
                                    logged_items.add((item_id, timestamp))

            except Exception as e:
                print(f"Error processing event: {e}")
                continue

    except KeyboardInterrupt:
        print("Monitoring stopped by user.")
    except Exception as e:
        print(f"Error occurred: {e}")

if __name__ == "__main__":
    monitor_and_log_changes()