Skip to content

Instantly share code, notes, and snippets.

@EsotericDryad
Last active February 24, 2024 00:32
Show Gist options
  • Save EsotericDryad/85179b9c3f1d0a505658a7539ae77576 to your computer and use it in GitHub Desktop.
Save EsotericDryad/85179b9c3f1d0a505658a7539ae77576 to your computer and use it in GitHub Desktop.
lemmy_upload.py
#!/usr/bin/env python3
import tomllib
import requests
import urllib.parse
# change these 4 variables:
USER_NAME = "baumgeist"
PASSWORD = "Super_secret_password" # there has to be a better way, but I'm tired
USER_INSTANCE = "lemmy.ml"
POSTS_FILE = "./test.toml"
# toml file in the form:
"""
[post_name]
community = "baumgeist@lemmy.ml"
name = "Post title goes here"
url = "http://example.site"
file = "/home/baumgeist/file_to_upload"
"""
# the 'file' field will only work if you added the logic
# to handle uploads
api_url = f"https://{USER_INSTANCE}/api/v3"
headers = {
"accept": "application/json",
"content-type": "application/json"
}
def validate():
url = f"{api_url}/user/login"
payload = {
"username_or_email": USER_NAME,
"password": PASSWORD
}
response = requests.post(url, json=payload, headers=headers)
return response.json()["jwt"]
def catbox_upload(file):
# TODO: catbox.moe upload code
# from: catbox.moe FAQ, https://catbox.moe/sharexcode.txt
#
#{
# "Name": "catbox.moe",
# "RequestType": "POST",
# "RequestURL": "https://catbox.moe/user/api.php",
# "FileFormName": "fileToUpload",
# "Arguments": {
# "userhash": "Your userhash here (leave blank for anonymous)",
# "reqtype": "fileupload"
# },
# "ResponseType": "Text"
#}
pass
#def youtube_upload(file):
# TODO: logic to handle youtube uploads
#
# https://developers.google.com/youtube/v3/guides/uploading_a_video
#pass
def get_community_id(community):
response = requests.get(community, headers=headers)
jsonified = response.json()
return jsonified['community_view']['community']['id']
with open(POSTS_FILE, "rb") as f:
data = tomllib.load(f)
if __name__ == "__main__":
auth_token = validate()
for post in data.values():
video_file = post['file']
cb_url = None
#
# TODO: logic to handle where to upload and get uploaded url
#
cb_url = catbox_upload(video_file)
video_url = cb_url if cb_url is not None else post['url']
community = f"{api_url}/community?name={urllib.parse.quote(post['community'])}"
community_id = get_community_id(community)
post_url = f"{api_url}/post"
payload = {
"community_id": community_id,
"name": post['name'],
"url": video_url
}
post_headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {auth_token}"
}
requests.post(post_url, json=payload, headers=post_headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment