Skip to content

Instantly share code, notes, and snippets.

@Axeltherabbit
Last active September 16, 2020 17:05
Show Gist options
  • Save Axeltherabbit/a1aa05b78afaae9fa12fcd6b0d749d99 to your computer and use it in GitHub Desktop.
Save Axeltherabbit/a1aa05b78afaae9fa12fcd6b0d749d99 to your computer and use it in GitHub Desktop.
import praw
import prawcore
import argparse
import time
from functools import wraps
from socket import error as SocketError
#######################################################################################
###the latest version is on github https://github.com/Axeltherabbit/RedditIDsGrabber###
#######################################################################################
# Lo script funziona e spamma su r/italy finche' non si crea un post reddit.com/italia
# Non so quanto spesso reddit permette di spammare quindi per il momento fa un post al secondo
# Lo cambiero' appena scopro quanto posso spammare
# Per non intasare il sub di merda il post viene subito cancellato se non ha l'id desiderato
# Per aumentare le probabilita' di creare il post c'e' bisogno di lavoro di gruppo!
# Update reddit soft-banna abbastanza velocemente, c'e' bisogno di molto piu' tempo tra un post e un altro
# Update2 praw sembra avere builtin reddit.auth.limits per vedere il numero di richieste che rimangono ma devo capire come funziona
# Update3 uso la funzione handle_api_exceptions per evitare il ratelimit e' molto brutta ma per adesso va bene
# Update4 adesso lo script sta in watch fino a quando non siamo vicini ad un target
# original source https://github.com/renfredxh/compilebot/blob/master/compilebot/compilebot.py
def handle_api_exceptions(max_attempts=1):
"""Return a function decorator that wraps a given function in a
try-except block that will handle various exceptions that may
occur during an API request to reddit. A maximum number of retry
attempts may be specified.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
retries = 0
while retries < max_attempts:
sleep_time = None
error_msg = ""
try:
return func(*args, **kwargs)
# Handle and log miscellaneous API exceptions
except praw.exceptions.ClientException as e:
error_msg = 'Client Exception "{error}" occurred: '.format(error=e)
except praw.exceptions.APIException as e:
# this is ugly as fuck but should work
e = str(e)
if e.startswith("RATELIMIT:"):
sleep_time = int("".join(c for c in e if c.isdigit())) * 60 + 1
error_msg = 'API Exception "{error}" occurred: '.format(error=e)
except SocketError as e:
error_msg = 'SocketError "{error}" occurred: '.format(error=e)
print(error_msg)
except praw.exceptions.PRAWException as e:
error_msg = 'PRAW Exception "{error}" occurred: '.format(error=e)
sleep_time = sleep_time or retries * 150
print(
"{0} in {f}. Sleeping for {t} seconds. "
"Attempt {rt} of {at}.".format(
error_msg,
f=func.__name__,
t=sleep_time,
rt=retries + 1,
at=max_attempts,
)
)
time.sleep(sleep_time)
retries += 1
return wrapper
return decorator
def wait(reddit):
while True:
try:
m = max(
[
int(submission.id, 36)
for submission in reddit.subreddit("all").new(limit=2)
]
)
except:
continue
distance = int("italia", 36) - m
print("distanza: ", distance)
if distance <= 200:
return
time.sleep(3)
@handle_api_exceptions(max_attempts=3)
def submit(subreddit, flair):
return subreddit.submit(
title="Ciao",
selftext=(
"It's me a bot, Hey non bannarmi pls, questo post si cancellera'"
" automaticamente"
),
flair_id=flair,
)
@handle_api_exceptions(max_attempts=3)
def delete(submited):
submited.delete()
def main(clientid: str, clientsecret: str, password: str, username: str) -> None:
# leggiti https://praw.readthedocs.io/en/latest/getting_started/authentication.html
reddit = praw.Reddit(
client_id=clientid,
client_secret=clientsecret,
password=password,
user_agent=f"testscript by /u/{username}",
username=username,
)
# flag che fa roba per reddit
reddit.validate_on_submit = True
try:
reddit.user.me()
except prawcore.exceptions.OAuthException:
print("Autenticazione fallita, Credenziali errate")
return
# aspetta fino a che non siamo vicini al target
wait(reddit)
subreddit = reddit.subreddit("italy")
no_flair_id = "cda47928-16a9-11e9-8128-0e8720a239d8"
while True:
submited = submit(subreddit, no_flair_id)
if submited.id.strip() != "italia":
post_id = submited.id
delete(submited)
print("rimosso: ", post_id)
else:
break
print("se sei qua qualcosa si e' rotto o ci sei riuscito :D")
if __name__ == "__main__":
print("the latest version is on github https://github.com/Axeltherabbit/RedditIDsGrabber, this script is out of date")
parser = argparse.ArgumentParser(
description="Script per ottenere il post ID 'italia' su reddit"
)
parser.add_argument(
"--clientid",
type=str,
help=(
"The client ID is the 14-character string listed just under “personal use"
" script” for the desired https://www.reddit.com/prefs/apps/"
),
)
parser.add_argument(
"--clientsecret",
type=str,
help=(
"The client secret is the 27-character string listed adjacent to secret for"
" the application."
),
)
parser.add_argument(
"--password",
type=str,
help="metti la tua password e non la condividere online pirla",
)
parser.add_argument("--username", type=str, help="il tuo username reddit")
args = parser.parse_args()
main(**vars(args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment