User:Fishy Wrangler/Bot Stuff

From Fish Wrangler
Jump to navigation Jump to search

Creating a bot[edit]

I'm trying to create a bot in python to help automate some of the wiki development. It will use the Wiki API

First Test[edit]

This is the first test code that logs in and writes a page to the wiki. To get it to work you will need to replace the text "YOURUSERNAME" with your username and replace "YOURPASSWORD" with your password. Please don't share your password with anyone.
The content of API test.py is below. Press edit to copy correctly.

import mwclient from mwclient.errors import APIError, LoginError

def handle_captcha(site, edit_params):

   """Handle CAPTCHA challenge during edits"""
   max_retries = 3
   for attempt in range(max_retries):
       try:
           # Get fresh edit token
           edit_params['token'] = site.get_token('edit')
           
           # Make the edit attempt
           result = site.api('edit', **edit_params)
           
           if result.get('edit', {}).get('result') == 'Success':
               return True
               
           # Check for CAPTCHA
           if 'captcha' in result.get('edit', {}):
               captcha = result['edit']['captcha']
               print(f"CAPTCHA required: {captcha['question']}")
               
               # Answer the CAPTCHA (using known answer)
               edit_params.update({
                   'captchaid': captcha['id'],
                   'captchaword': 'joe'  # The known answer
               })
               continue
               
           print(f"Edit failed: {result}")
           return False
           
       except APIError as e:
           print(f"API Error: {e}")
           return False
           
   print(f"Failed after {max_retries} CAPTCHA attempts")
   return False

def test_mwclient_connection():

   try:
       # Initialize connection
       site = mwclient.Site(
           host='wiki.fishwrangler.com',
           scheme='https',
           path='/',
           retry_timeout=30
       )
       
       # Login
       print("Attempting login...")
       site.login(
           username='YOURUSERNAME',
           password='YOURPASSWORD'
       )
       print("Login successful!")
       
       # Prepare edit
       sandbox_title = 'User:YOURUSERNAME/sandbox'
       sandbox = site.pages[sandbox_title]
       current_text = sandbox.text() if sandbox.exists else ""
       new_text = current_text + "\n\n== Test Edit ==\nThis is a test write using a Python Bot."
       
       # Edit parameters
       edit_params = {
           'title': sandbox_title,
           'text': new_text,
           'summary': 'API test',
           'minor': True,
           'bot': True  # Mark as bot edit if you have bot rights
       }
       
       # Handle edit with CAPTCHA
       if handle_captcha(site, edit_params):
           print("Successfully edited sandbox page!")
           return True
       else:
           print("Failed to edit sandbox page")
           return False
           
   except LoginError as e:
       print(f"Login failed: {e}")
   except Exception as e:
       print(f"Unexpected error: {e}")
   return False

if __name__ == "__main__":

   if test_mwclient_connection():
       print("mwclient is working correctly!")
   else:
       print("There were issues with mwclient setup")