Explorar el Código

Initial commit

DeadTOm hace 2 meses
commit
eb7045d30f
Se han modificado 5 ficheros con 185 adiciones y 0 borrados
  1. 73 0
      .gitignore
  2. 8 0
      LICENSE
  3. 14 0
      README.md
  4. 2 0
      defaultconfig.py
  5. 88 0
      mau.py

+ 73 - 0
.gitignore

@@ -0,0 +1,73 @@
+config.py
+
+# ---> KDevelop4
+*.kdev4
+.kdev4/
+
+# ---> Python
+# Byte-compiled / optimized / DLL files
+instance/
+.kdev4/
+/*.kdev4
+.git/
+
+
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+.venv/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*,cover
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+

+ 8 - 0
LICENSE

@@ -0,0 +1,8 @@
+MIT License
+Copyright (c) <year> <copyright holders>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 14 - 0
README.md

@@ -0,0 +1,14 @@
+# MastoAutoUploader
+
+A script for uploading photos to Mastodon
+
+### Usage
+
+Set up a folder with up to four images that you would like uploaded. jpg or png only.
+
+```bash
+    python mau.py "<message>" "<alt text>" "<public, unlisted, private>" "</path/to/photo/folder/"
+```
+
+### Requirements
+An access token from the "Development" section in your Mastodon settings, with read and write permissions.

+ 2 - 0
defaultconfig.py

@@ -0,0 +1,2 @@
+instance_url = 'https://dice.camp'
+access_token = 'OMg93zcfT1nh3I3OzgbT41x5ZGQRgn30a1zzaxJkXEw'

+ 88 - 0
mau.py

@@ -0,0 +1,88 @@
+#!/usr/bin/python
+#
+import requests
+import sys
+import magic
+import time
+import string
+import random
+import mimetypes
+import logging
+import config
+from glob import glob
+
+# logging.basicConfig(filename='mau.log',level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')  # Set up log file and level
+logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
+
+message = sys.argv[1]
+description = sys.argv[2]
+visibility = sys.argv[3]
+pics_path = sys.argv[4]
+
+
+def get_pics():
+    imgfiles = []
+    for file in glob(f'{pics_path}/*.jpg'):
+        imgfiles.append(file)
+    for file in glob(f'{pics_path}/*.png'):
+        imgfiles.append(file)
+    logging.debug(f'{imgfiles}')
+    return imgfiles
+
+
+def do_upload(msg, media_ids):
+    logging.info(f'Posting to Mastodon...')
+    auth_data = f'\"Bearer {config.access_token}'
+    response = requests.post(f'{config.instance_url}/api/v1/statuses',
+                             params={'status': msg, 'media_ids[]': media_ids},
+                             headers={'Authorization': auth_data,
+                                      'visibility': 'public'})
+    json_response = response.json()
+
+
+def img_upload(description, media_info):  # Upload the image, return the media id
+    logging.info(f'Uploading image {media_info}')
+    auth_data = f'\"Bearer {config.access_token}'
+    response = requests.post(f'{config.instance_url}/api/v2/media',
+                             files={'file': media_info},
+                             params={'description': description},
+                             headers={'Authorization': auth_data})
+    json_response = response.json()
+    id = json_response['id']
+    logging.debug(f'{id}')
+    return id
+
+
+def guess_type(media_file):  # Get the mime type of the file
+    mime_type = None
+    try:
+        mime_type = magic.from_file(media_file, mime=True)
+    except AttributeError:
+        mime_type = mimetypes.guess_type(media_file)[0]
+
+    logging.debug(f'It looks like this is a {mime_type}.')
+    return mime_type
+
+
+media_ids = []
+for image in get_pics():
+    mime_type = guess_type(image)  # Get the mime type
+    random_suffix = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))  # Create a random suffix for our file name so we don't upload the same file name more than once
+    file_name = "mau_upload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension(mime_type)
+    info = (file_name, open(image, 'rb'), mime_type)  # Get the image, and create multipart form data
+
+    logging.info(f'{image}...\n')
+    media_id = img_upload(description,info)  # Upload the image, get the id
+    media_ids.append(media_id)  # Append to the media_ids list
+    logging.info(f'Current list: {media_ids}')
+    logging.info(f'Pausing, so the server has time to process the image\n')
+    time.sleep(10)
+
+
+if len(sys.argv) < 5:
+    print('Usage: python mau.py \"<message>\" \"<alt text>\" \"<public, unlisted, private>\" \"</path/to/photo/folder/\"')
+else:
+    do_upload(message, media_ids)  # Post the image
+    logging.info(f'Done.')
+
+sys.exit()