/ pyscripts.md
pyscripts.md
  1  ## Py scripts
  2  
  3  # A modified catbox uploader, more clean and less messy.
  4  import os
  5  import requests
  6  from datetime import datetime
  7  
  8  credits="""
  9  This program is made and maintained by Andrew
 10  This program is open source and free to use
 11  MIT @ 2025 
 12  Support me by Starring the project & following me on Github:
 13  - https://github.com/Andrewgxgx/catbox.moe
 14  - https://github.com/Andrewgxgx
 15  """
 16  api = "https://catbox.moe/user/api.php"
 17  api_litterbox="https://litterbox.catbox.moe/resources/internals/api.php"
 18  os_unix="/"
 19  os_windows="\\"
 20  control=0
 21  start=0
 22  formatting = 2  # Default formatting
 23  user_os = os_unix  # Default OS
 24  
 25  def get_user_preferences():
 26      global user_os, control
 27      while True:
 28          print("""Please choose your OS:
 29            1. Windows
 30            2. Unix (Linux, MacOS)
 31            3. Temple OS 
 32            4. Other
 33            Type the number of your choice.
 34          """)
 35          Preferences = input("Enter a number 1 to 4: ")
 36          if Preferences == "1":
 37              user_os = os_windows
 38              break
 39          elif Preferences == "2":
 40              user_os = os_unix
 41              break
 42          elif Preferences == "3":
 43              print("Hello Terry Davis, We currently don't support Temple OS")
 44              print("Exiting...")
 45              control = 1
 46              exit()
 47          elif Preferences == "4":
 48              user_os = os_unix
 49              print("Using Unix-style paths as default")
 50              break
 51          else:
 52              print("Please type 1, 2, 3, or 4")
 53  
 54  def format():
 55      global formatting, start
 56      print("""
 57            How would you like to format your links?
 58            1. <file path>: <link>
 59            2. <link>
 60            3. <numbered list>. <link>
 61            4. <Timestamp (hh:mm:ss)> : <File path> : <Link>
 62            5. <custom string (user input)> : <link> 
 63            """)
 64      try:
 65          formatting = int(input("Enter a number 1 to 5: "))
 66          start = 0
 67      except ValueError:
 68          print("Invalid input, using default format (link only)")
 69          formatting = 2
 70  
 71  def check_upload_folder():
 72      """Check if upload folder exists and warn if empty"""
 73      folder_path = f".{user_os}upload"
 74      if not os.path.exists(folder_path):
 75          print(f"Warning: Folder '{folder_path}' does not exist!")
 76          create = input("Create it now? (Y/N): ")
 77          if create.upper() in ["Y", "YES", "YE"]:
 78              os.makedirs(folder_path)
 79              print(f"Created {folder_path}. Please add files to upload and run again.")
 80              exit()
 81          else:
 82              print("Exiting...")
 83              exit()
 84      return folder_path
 85  
 86  def save_links_to_file(content):
 87      """Save links, ALWAYS overwriting the existing file"""
 88      try:
 89          with open("uploaded_links.txt", "w", encoding='utf-8') as f:
 90              f.write(content)
 91          print("✅ Links saved to uploaded_links.txt (file overwritten)")
 92      except Exception as e:
 93          print(f"❌ Error saving to file: {str(e)}")
 94  
 95  def get_files_from_folder():
 96      """Get list of files from upload folder"""
 97      folder_path = check_upload_folder()
 98      files_to_upload = []
 99      
100      print("\nScanning for files...")
101      for root, dirs, files in os.walk(folder_path):
102          for file in files:
103              file_path = os.path.join(root, file)
104              print(f"Found: {file_path}")
105              files_to_upload.append(file_path)
106      
107      if not files_to_upload:
108          print("No files found in upload folder!")
109          return []
110      
111      print(f"\nFound {len(files_to_upload)} file(s)")
112      confirm = input("Upload these files? (Y/N): ")
113      
114      if confirm.upper() in ["Y", "YES", "YE", "YEAH"]:
115          return files_to_upload
116      return []
117  
118  def upload_to_service(api_url, data, files):
119      """Wrapper for requests.post"""
120      try:
121          return requests.post(api_url, data=data, files=files)
122      except Exception as e:
123          print(f"Network error: {str(e)}")
124          return None
125  
126  def process_uploads(files_to_upload, upload_function, additional_data=None):
127      """Generic upload processor"""
128      global start, formatting
129      
130      all_links = ""
131      total_files = len(files_to_upload)
132      
133      for idx, file_path in enumerate(files_to_upload, 1):
134          print(f"Uploading [{idx}/{total_files}]: {file_path}")
135          
136          try:
137              with open(file_path, "rb") as item:
138                  files = {"fileToUpload": item}
139                  data = {"reqtype": "fileupload"}
140                  if additional_data:
141                      data.update(additional_data)
142                  
143                  response = upload_function(data, files)
144              
145              if response and response.status_code == 200:
146                  link = response.text.strip()
147                  
148                  if formatting == 1:
149                      formatting_write = f'"{file_path}" : {link}\n'
150                  elif formatting == 2:
151                      formatting_write = f"{link}\n"
152                  elif formatting == 3:
153                      start += 1
154                      formatting_write = f"{start}. {link}\n"
155                  elif formatting == 4:
156                      current_time = datetime.now().strftime("%H:%M:%S")
157                      formatting_write = f"[{current_time}]: {file_path} : {link}\n"
158                  elif formatting == 5:
159                      write = input("Put text before the link: ")
160                      formatting_write = f"{write} : {link}\n"
161                  else:
162                      formatting_write = f"{link}\n"
163                  
164                  all_links += formatting_write
165                  print(f"✓ Uploaded: {link}")
166              else:
167                  print(f"✗ Failed to upload: {file_path}")
168                  
169          except Exception as e:
170              print(f"✗ Error uploading {file_path}: {str(e)}")
171      
172      if all_links:
173          save_links_to_file(all_links)
174          print(f"\n✅ Successfully uploaded {len(files_to_upload)} files")
175      else:
176          print("\n❌ No files were uploaded successfully")
177  
178  def upload_links():
179      """Handle URL uploads - ALWAYS OVERWRITES the file"""
180      all_links = ""
181      print("\nEnter links to upload (type 'done' when finished):")
182      while True:
183          enter_links = input("Link: ")
184          if enter_links.lower() == "done":
185              break
186          
187          data = {"reqtype": "urlupload", "url": enter_links}
188          response = upload_to_service(api, data, None)
189          
190          if response and response.status_code == 200:
191              print(f"✓ Uploaded: {response.text}")
192              all_links += f"{response.text}\n"
193          else:
194              print("✗ Failed to upload link")
195      
196      if all_links:
197          save_links_to_file(all_links)
198      else:
199          print("No links were uploaded")
200  
201  def upload_links_with_account(account):
202      """Handle URL uploads with account - ALWAYS OVERWRITES the file"""
203      all_links = ""
204      print("\nEnter links to upload (type 'done' when finished):")
205      while True:
206          enter_links = input("Link: ")
207          if enter_links.lower() == "done":
208              break
209          
210          data = {
211              "reqtype": "urlupload",
212              "userhash": account,
213              "url": enter_links
214          }
215          response = upload_to_service(api, data, None)
216          
217          if response and response.status_code == 200:
218              print(f"✓ Uploaded: {response.text}")
219              all_links += f"{response.text}\n"
220          else:
221              print("✗ Failed to upload link")
222      
223      if all_links:
224          save_links_to_file(all_links)
225      else:
226          print("No links were uploaded")
227  
228  def catbox_no_acc():
229      linkornot = input("Upload via link? (Y/N): ")
230      
231      if linkornot.upper() in ["Y", "YE", "YES"]:
232          upload_links()
233      else:
234          files_to_upload = get_files_from_folder()
235          if files_to_upload:
236              format()
237              process_uploads(
238                  files_to_upload,
239                  lambda d, f: upload_to_service(api, d, f)
240              )
241  
242  def catbox_with_acc():
243      account = input("Enter your account hash: ")
244      if not account:
245          print("Account hash required!")
246          return
247      
248      linkornot = input("Upload via link? (Y/N): ")
249      
250      if linkornot.upper() in ["Y", "YE", "YES"]:
251          upload_links_with_account(account)
252      else:
253          files_to_upload = get_files_from_folder()
254          if files_to_upload:
255              format()
256              process_uploads(
257                  files_to_upload,
258                  lambda d, f: upload_to_service(api, d, f),
259                  {"userhash": account}
260              )
261  
262  def litterbox():
263      files_to_upload = get_files_from_folder()
264      if not files_to_upload:
265          return
266      
267      time_options = {"1h", "12h", "24h", "72h"}
268      while True:
269          time = input("Upload duration? (1h, 12h, 24h, 72h): ").lower()
270          if time in time_options:
271              break
272          print("Invalid duration. Please enter 1h, 12h, 24h, or 72h")
273      
274      format()
275      process_uploads(
276          files_to_upload,
277          lambda d, f: upload_to_service(api_litterbox, d, f),
278          {"time": time}
279      )
280  
281  def menu():
282      global control
283      print(f"""
284  {credits}
285  =========
286  Welcome to CATBOX & Litterbox Uploader!
287  Choose your options! 
288  1. Upload to Catbox.moe (No account, perma)
289  2. Upload to Catbox.moe (with account)
290  3. Upload to Litterbox (temp upload)
291  4. Exit / Stop program
292  ====
293  Note: uploaded_links.txt will be OVERWRITTEN each time you upload!
294  """)
295      
296      try:
297          opt = int(input("Type 1,2,3 or 4: "))
298          if opt == 1:
299              print("Catbox - no account")
300              catbox_no_acc()
301          elif opt == 2:
302              print("Catbox - with account")
303              catbox_with_acc()
304          elif opt == 3:
305              print("Upload to LitterBox")
306              litterbox()
307          elif opt == 4:
308              print("Exiting...")
309              control = 1
310          else:
311              print("Invalid option. Please enter 1-4")
312      except ValueError:
313          print("Please enter a valid number")
314  
315  # Main program
316  if __name__ == "__main__":
317      print(credits)
318      print("Welcome to the Catbox Uploader")
319      print("Please choose your OS first, before getting started")
320      get_user_preferences()
321      
322      folder_path = f".{user_os}upload"
323      if not os.path.exists(folder_path):
324          os.makedirs(folder_path)
325          print(f"Created upload folder: {folder_path}")
326          print("Please add files to upload and run again.")
327          exit()
328      
329      while control == 0:
330          menu()
331          if control != 1:
332              input("\nPress Enter to continue...")
333      
334      print("\n" + credits)
335      print("Thank you for using the Catbox Uploader")
336      print("Exiting...")