Skip to content

Instantly share code, notes, and snippets.

@gschizas
Last active May 27, 2021 18:25
Show Gist options
  • Save gschizas/aaa8f374b5b22c5eb1a55503e21b3cff to your computer and use it in GitHub Desktop.
Save gschizas/aaa8f374b5b22c5eb1a55503e21b3cff to your computer and use it in GitHub Desktop.
Mass upload emoji to reddit redesign alpha
from tqdm import tqdm
from praw_wrapper import praw_wrapper
r = praw_wrapper(scopes=['read', 'structuredstyles'])
subreddit = input("Enter your subreddit name here: ")
sr = r.subreddit(subreddit)
all_emojis = r.get(f"/api/v1/{subreddit}/emojis/all")
for emoji in tqdm(all_emojis[f't5_{sr.id}'], ncols=100):
r._authorized_core._requestor.request(
method='DELETE',
url=f"{r.config.oauth_url}/api/v1/{subreddit}/emoji/{emoji}",
headers={'Authorization': 'Bearer ' + r._authorized_core._authorizer.access_token})
import datetime
import os.path
import uuid
from urllib.parse import urlparse, parse_qs
import praw
CLIENT_ID = 'xxxxxxxxxxxxxx'
CLIENT_SECRET = 'yyyyyyyyyyyyyyyyyyyyyyyyyyy'
# replace these values with the relevant ones from https://www.reddit.com/prefs/apps
def praw_wrapper(scopes=None):
user_agent = 'python:gr.terrasoft.reddit.scratch:v' + datetime.date.today().isoformat() + ' (by /u/gschizas)'
user_agent_key = user_agent.split(':')[1]
refresh_token = None
token_filename = user_agent_key + '.refresh_token'
if os.path.exists(token_filename):
with open(token_filename, 'r') as f:
refresh_token = f.read()
if refresh_token:
r = praw.Reddit(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
refresh_token=refresh_token,
user_agent=user_agent)
else:
r = praw.Reddit(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri='https://example.com/authorize_callback',
user_agent=user_agent)
state = uuid.uuid4().hex
if scopes is None:
scopes = ['*']
print('Visit the following URL:', r.auth.url(scopes, state))
url = input('Result URL: ')
query = parse_qs(urlparse(url).query)
assert state == query['state'][0]
code = query['code'][0]
refresh_token = r.auth.authorize(code)
with open(token_filename, 'w') as f:
f.write(refresh_token)
return r
import pathlib
import re
import lxml.etree as ET
import requests
from tqdm import tqdm
from praw_wrapper import praw_wrapper
r = praw_wrapper(scopes=['read', 'structuredstyles'])
subreddit = input("Enter your subreddit name here")
useful_fields = ['acl', 'content-type', 'key', 'policy', 'success_action_status',
'X-Amz-Algorithm', 'X-Amz-Credential', 'X-Amz-Date',
'x-amz-meta-ext', 'x-amz-security-token', 'X-Amz-Signature', 'x-amz-storage-class']
def cleanup_flag_name(original_name):
lower_case_name = original_name.lower()
remove_extension = lower_case_name.replace(' ', '_').split('.')[0]
remove_ambersand = remove_extension.replace(' & ', '_')
remove_parens = re.sub('[\(\)]', '', remove_ambersand)
return re.sub('\W', '', remove_parens)[:19]
all_images = list(pathlib.Path('images').glob('*.png'))
all_images_progress = tqdm(all_images, ncols=80)
for image_file in all_images_progress:
image_name = cleanup_flag_name(image_file.name)
step1 = r.post(
f'/api/v1/{subreddit}/emoji_asset_upload_s3.json',
data={
'filepath': image_file.name,
'mimetype': 'image/png'
})
post_fields = {f['name']: f['value'] for f in step1['s3UploadLease']['fields'] if f['name'] in useful_fields}
step2 = requests.post(
f"https:{step1['s3UploadLease']['action']}/",
data=post_fields,
files={'file': image_file.read_bytes()},
headers={
'Origin': 'https://alpha.reddit.com',
'Referer': f"https://alpha.reddit.com/r/{subreddit}"
})
tree = ET.fromstring(step2.content)
s3_key = tree.xpath('/PostResponse/Key')[0].text
step3 = r.post(
f"/api/v1/{subreddit}/emoji.json",
data={
'name': f"flag_{image_name}",
's3_key': s3_key}
)
@rahulashok360
Copy link

how do i implement this.
iam new

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment