Making Money with Python

Paranoid Android

Elite Member
Joined
Jun 20, 2010
Messages
2,864
Reaction score
4,209
I made a few beginner's attempts at making a few python scripts that could make a few bucks at least per run. My codes don't look pretty, some of my variables and prompts are profane, and you pros out there might go roflwtf, but I hope to be able to fix all of that and code like a pro soon enough.

You need a local python environment if you don't have it already. There is IDLE, and theres PyCharm CE that you can install after installing IDLE. I like TextEdit on Ubuntu and the shell for execution. Suit yourself.

I have also put up this thread where fellow members tell me what they need and I code it up for them. I am making this thread to post those working scripts that everyone can use. Thought I'd start off first by posting what I have done so far, which would start from my 2nd post.

Before we get to the moneymakers, I'd like to show off a few scripts that I felt so proud of.

Here is a password generator to start with
Python:
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
ln=5
nn=4
sn=3
password=[]
for i in range(0,ln):
    password+=letters[random.randint(0,len(letters)-1)]
for i in range(0, nn):
    password+=numbers[random.randint(0,len(numbers)-1)]
for i in range(0, sn):
    password+=symbols[random.randint(0,len(symbols)-1)]
random.shuffle(password)
pw=''
for char in password:
    pw+=char
print(f'Password: {pw}')

The Lucas Lehmer method of finding Mersenne Prime, without which the SSLs don't work. Got the method from this video

Python:
import time



i = 4
l = 1
start_time = time.time()
n=int(input('n = '))
pn = (2 ** n) - 1

if pn % 2 == 0:
    print(f'{pn} is a fucking even number')
else:
    print(f"the number you're solving for is {pn}\nCalculating...")
    while i < pn:
        i = (i ** 2) - 2
        l += 1
    print(l, 'loop 1 ')
    i = i % pn
    while l < n - 1:
        i = (i ** 2) - 2
        i = i % pn
        l += 1
    print(l, 'loop2 ')
    if (i % (pn)) == 0:
        print(f'2^{n} - 1 is a prime')
        print("--- %s seconds ---" % (time.time() - start_time))
    else:
        print(f'2^{n} - 1 isnt a prime')
        print("--- %s seconds ---" % (time.time() - start_time))
 
Fill a wordpress blog with 5k youtube videos in an hour and sell it for 50 bucks, or more?

Go to http://console.cloud.google.com and get your API access set up.

1657101252213.png

Get in there, and create a new project, and create new OAuth credentials

1657101396752.png

Select Web Application when you do

1657101608082.png

And in the Authorized Redirect URLs, hit add url and enter what you see in the pic. It is http://127.0.0.1:8080. If you fuck this up the script won't work.

Once you hit create you go back to the same page on the 2nd image, where you click on the project name under OAuth2 section, and you download the secret json file and rename it to secret.json and put it in the same folder as the py file you paste the code below into. You can edit the name of the secrets file in the variable right below the imports in case you want to use multiple secrets in a day.

Run the code

Enter a search term, my favorite is pussycat videos. Returns 50 videos per search, then searches for 50 more related videos from the first video of the previous search, runs until 5k videos are pulled or the search gets exhausted.

Once a list of 50 videos are pulled, they are pushed into wordpress through a multi thread function, pretty fast. But make sure you let your host know that you're going to be sending some traffic to your api so they don't think its a ddos.

Apart from the secrets, you will need auth info for your wordpress site.

Get into the users area and find out how to make an application password. Insert the user and password within the quotes in the variable right below the expansion ideas text and run the script.

Add 50k videos in 10 days, or use 10 secret.json from different google accounts and do it in 1 day, list the site on empireflippers for 50 bucks and it will sell in no time. Or maybe some other place. You'll figure it out.

Python:
import os
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
import requests
import base64
from random import randint
import concurrent.futures
import time

secret_file_name = 'secret.json'
'''
Expansion Ideas:
1. Find related videos for all fetched videos
2. Run youtube and wp processes in different cores
3. Fetch related videos for each video in json with 50 threads
4. Post to wp with 50 parallel threads
5. 10 units per search call with 10k limit per day fetches 5k videos per day, if the keyword is popular and returns 50
    results per call
6. Ingtegrate openAI for description based on title.
7.
'''
wp_user=''
wp_pw='' #Application Password
wp_api_url = 'https://yttesting.yourdomain.com/wp-json/wp/v2/posts'

#Don't fuck with anything below this line
wp_cred=f'{wp_user}:{wp_pw}'
wp_tkn = base64.b64encode(wp_cred.encode())
wp_header = {'Authorization': 'Basic ' + wp_tkn.decode('utf-8')}

def wp_post(data, i):
    wp_response = requests.post(url=wp_api_url, headers=wp_header, json=data)
    print(i, wp_response)

start_time=time.perf_counter()
nextPageToken = None
credentials = None
relatedTo = ''
total_videos_loop = 0

while total_videos_loop < 3400:
    print('videos posted so far', total_videos_loop)
    # token.pickle stores the user's credentials from previously successful logins
    if os.path.exists('token.pickle'):
        print('Loading Credentials From File...')
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)

    # If there are no valid credentials available, then either refresh the token or log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            print('Refreshing Access Token...')
            credentials.refresh(Request())
        else:
            print('Fetching New Tokens...')
            flow = InstalledAppFlow.from_client_secrets_file(
                secret_file_name,
                scopes=[
                    'https://www.googleapis.com/auth/youtube.force-ssl'
                ]
            )

            flow.run_local_server(port=8080, prompt='consent',
                                  authorization_prompt_message='')
            credentials = flow.credentials

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as f:
                print('Saving Credentials for Future Use...')
                pickle.dump(credentials, f)
    #End of Credentials

    youtube = build('youtube', 'v3', credentials=credentials)
    if total_videos_loop == 0:
        searchTerm = input('searchTerm: ')
        request = youtube.search().list(
            part="snippet",
            maxResults=50,
            relevanceLanguage="en",
            regionCode='us',
            type='video',
            safeSearch='strict',
            videoDefinition='high',
            videoEmbeddable='true',
            videoLicense='creativeCommon',
            q=searchTerm
        )
    else:
        request = youtube.search().list(
            part="snippet",
            maxResults=50,
            relevanceLanguage="en",
            regionCode='us',
            type='video',
            safeSearch='strict',
            videoDefinition='high',
            videoEmbeddable='true',
            videoLicense='creativeCommon',
            relatedToVideoId=relatedTo
        )

    videoId = []
    videoTitle = []
    videoDescription = []

    response = request.execute()

    totalResults = response['pageInfo']["totalResults"]
    nextPageToken = response["nextPageToken"]
    resultsPerPage = int(len(response['items']))
    print(nextPageToken, totalResults, resultsPerPage, type(resultsPerPage))

    with open('vid.list', 'a') as f:
        for i in range(resultsPerPage):
            print(i, response['items'][i]['id']['videoId'], '\n')
            f.write(str(response['items'][i]['id']['videoId'] + '\n'))
            videoId.append(response['items'][i]['id']['videoId'])
            videoTitle.append(response['items'][i]['snippet']['title'])
            videoDescription.append(response['items'][i]['snippet']["description"])
            print(videoId[i],videoTitle[i])

    relatedTo = videoId[0]
    with open('yt.json', 'w') as f1:
        f1.write(str(response))

    print(len(videoId), len(videoTitle), len(videoDescription))
    sleeptime = randint(20, 45)
    print('imma sleep for ', sleeptime, ' secs')
    time.sleep(sleeptime)
    #WP Posting
    with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
        for i in range(resultsPerPage):

            wpcontent = f'[embed]https://www.youtube.com/watch?v={videoId[i]}[/embed] \n <h3>Description</h3>\n{videoDescription[i]}'
            data = {
                'title': videoTitle[i],
                'status': 'draft',
                'slug': videoTitle[i].replace(' ', ''),
                'content': wpcontent
            }
            executor.submit(wp_post,data=data,i=i)

    total_videos_loop += resultsPerPage
print('total videos posted in this run: ', total_videos_loop)
print('finished in',time.perf_counter()-start_time)

Disclaimer: This is a fun project. I shall not be responsible if you are not able to sell the site you make for 50 bucks. I shall not be responsible if Sundar fuckin Pichai comes after you for api abuse either. Nor if your host shuts you down for trying to make 50k posts on your blog.

Have Fun!

All questions go on the thread please. Let us make the answers useful to everyone.
 

Attachments

  • 1657101489817.png
    1657101489817.png
    235.6 KB · Views: 143
Integrate OpenAi? That's gonna be expensive.

Why use an API and not scrapers?
 
you can try BHW market place or websited like fiverr
 
Post answers to your questions from OpenAI to wordpress

Signup to OpenAI.com and get a free $18 credit and an API key. Stick the API key into the script, insert wordpress domain, username and application password. Please find out how to create an Application Password so that you don't have to use your real password.

Install pyCharm or IDLE, install the required libraries shown in the top 2 lines. If you don't know how to do this, learn.

Enter 1 question per line, or use a file q.txt to import a bunch of questions.

Choose to save output in files to be used later, or have them posted to wp directly, or post the content from files to wp. Sell the content files, do what you want with it.
Be sure to format questions properly and ask very descriptive questions and include a word count too if possible as required.

So, here is the code. Not fully debugged, error handling not done properly. My first test worked and I'm posting this here. Will improve on this depending on how welcome this script is on the forum.

I hope the human writers of BHW don't gang up and order a hit on me. I'm doing this for dopamine, nothing else.

Python:
import os,openai, requests, random, base64
from concurrent.futures import ProcessPoolExecutor

'''OpenAI Key goes within the quotes'''
openai_key = 'Key Here'

# WP
wordpress_domain = '' ##DO NOT INCLUDE HTTPS OR WWW OR ANY TRAILING SLASHES. ONLY ENTER domainname.tld
wordpress_username = ''
wordpress_application_password = ''

wordpress_post_status = 'draft'

# OpenAI Tweaks
aiTemperature = 0.7
maxTokens = 100

'''Paths. Change these only if you know wtf you're doing'''
generated_content = 'new_content_files/'
uploaded_content = 'content_uploaded_to_wp/'

# Menu Items
singleq = ('''OpenAI is a bitch. Please format your questions clearly.
        Sample Question: Tell me about guitar strings in 200 words
        Sample Answer below has only 199 words... OpenAI is a bitch

        Guitar strings are one of the most important aspects of the instrument, and the type of string you use can have
        a big impact on your sound. There are a variety of different types of strings available, each with their own
        unique properties.

        The most common type of string is the steel string, which is most often used on acoustic guitars. Steel strings
        are known for their bright, clear tone and are a good choice for most styles of music.

        If you're looking for a warmer, more mellow sound, you might want to try a set of nylon strings. Nylon strings
        are typically used on classical and flamenco guitars, and they offer a softer, more delicate sound.

        If you're looking for the ultimate in shredding capabilities, you'll want to check out a set of stainless steel
        strings. These strings are incredibly durable and can stand up to serious abuse, making them a good choice for
        metal and hard rock players.

        No matter what type of music you play, there's a set of guitar strings that's perfect for you. With so many
        different types available, there's no reason not to experiment until you find the perfect set for your sound.

        So, type in your question accordingly: ''')

mainmenu = '''
    Howdy!

        Hit
            1: Generate Articles and write them to file
            2: Generate Articles and post them to Wordpress
            3: Read Articles from file and post them to Wordpress
            4: Quit

        Wachawannado? : '''

a2menu = '''
        1: Imput single question here
        2: Read list of questions from file (One question per line)
        3: Go back to previous menu

        Wachawannadonow? : '''


def post2wp(q, i, flag, content):
    if flag:
        openai.api_key = openai_key
        content = openai.Completion.create(model="text-davinci-002", prompt=q, temperature=aiTemperature,
                                           max_tokens=maxTokens)["choices"][0]["text"]

    cred = f'{wordpress_username}:{wordpress_application_password}'
    tkn = base64.b64encode(cred.encode())
    wpheader = {'Authorization': 'Basic ' + tkn.decode('utf-8')}
    api_url = f'https://{wordpress_domain}/wp-json/wp/v2/posts'
    data = {
    'title' : q.capitalize(),
    'status': wordpress_post_status,
    'content': content,
    }
    print(content)
    wp_response = requests.post(url=api_url,headers=wpheader, json=data)
    print(f'Item no. {i+1} posted, with title{q} and post content \n\n {content} \n\n {wp_response})


def article2file(q,i):
    openai.api_key = openai_key
    response = openai.Completion.create(model="text-davinci-002", prompt=q, temperature=aiTemperature,
                                        max_tokens=maxTokens)["choices"][0]["text"]
    fname = q.replace(' ', '_') + '.txt'
    if os.path.exists(generated_content+fname):
        print('File with title already exists, renaming it with a random number prefix')
        os.replace(generated_content+fname,generated_content+str(random.randint(1000,9999))+fname)
    with open(generated_content+fname, 'w') as f:
        f.write(response)
        print(f'Item: {i} in list done.\nQuery string: {q}\nArticle:\n{response}\n\nSaved to {fname}')





if __name__ == '__main__':
    if not os.path.exists(generated_content):
        os.mkdir(generated_content)
    if not os.path.exists(uploaded_content):
        os.mkdir(uploaded_content)
    try:
        while True:
            try:
                wachawannado = int(input(mainmenu))
            except ValueError:
                print('\nPlease enter a number')
                continue
            if wachawannado == 1: #Article to file
                try:
                    wachawannadonow = int(input(a2menu))
                except ValueError:
                    print('\nPlease enter a number')
                    continue
                if wachawannadonow == 1: #a2f single
                    article2file(q=input(singleq), i=1)

                elif wachawannadonow == 2: #a2f file
                    if os.path.exists('q.txt'):
                        if not os.stat("file").st_size == 0:
                            with open('q.txt', 'r') as f:
                                with ProcessPoolExecutor(max_workers=16) as executor:
                                    for i, line in enumerate(f):
                                        executor.submit(article2file, i=i, q=line)
                        else:
                            print('\nq.txt is empty')
                            continue
                    else:
                        print("Can't find q.txt")
                        continue
                else:
                    continue

            elif wachawannado == 2: #Article to Wordpress
                try:
                    wachawannadonow = int(input(a2menu))
                except ValueError:
                    print('\nPlease enter a number')
                    continue
                if wachawannadonow == 1: #a2wp single
                    post2wp(q=input(singleq), i=1, flag = True, content = '')
                elif wachawannadonow == 2: #a2wp file
                    if os.path.exists('q.txt'):
                        if not os.stat("file").st_size == 0:
                            with open('q.txt', 'r') as f:
                                with ProcessPoolExecutor(max_workers=16) as executor:
                                    for i, line in enumerate(f):
                                        executor.submit(post2wp, q=line, i=i, flag = True, content = '')
                        else:
                            print('\nq.txt is empty')
                            continue
                    else:
                        print("Can't find q.txt")
                        continue
                else:
                    continue
            elif wachawannado == 3: #Files to WP
                contentfiles = os.listdir(generated_content)
                if contentfiles:
                    with ProcessPoolExecutor(max_workers=16) as executor:
                        for i, file in enumerate(contentfiles):
                            if file.endswith('.txt'):
                                print('Posting from file:', file)
                                with open(generated_content+file,'r') as f:
                                    executor.submit(post2wp, flag = False, content = f.read(), q = file.replace('_', '').replace('.txt',''), i=i)
                                os.replace(generated_content+file, uploaded_content+file)
                else:
                    print('Generated Content folder is empty')
            elif wachawannado == 4:
                print('Bye!')
                break
            else:
                print('Invalid Choice, try that again')
    except KeyboardInterrupt:
        print('Bye!')

Please post your questions, requests, comments, suggestions, bug reports (150 lines of code can't have that many bugs) right here. PM me and it will be I ordering a hitman for you.
 
Post content from reddit with comments on to your wordpress blog

What the script does
Pulls the top posts from reddit along with 75 to 125 top level comments of each post and posts them to wordpress, posts and comments are from the original authors names with the original timestamp. The multithreading feature with the current settings can do 200 posts with an average of 75 comments per post in about 16 seconds.


Limitations:
1. Only 100 requests per sec per account, I recommend keeping the multiprocesing workers to the mininimum, not more than 2x the number of cores you have. The script does sleep after every 100 requests for 61 seconds.
2. You're good if you host your wordpress locally or on a vps or a dedicated server, but if you're on a shared hosting, your host might have a problem with multiple requests. You might have to setup an ssh tunnel, or build the site locally and populate the db and move it to the server or find a way to sync it in real time.
3. If you let it run and step away and if there is a loss of connection due to one of these limitations the script stops working.
4. You will need an administrator account, and not an account with any lesser privileges.
5. It does not include a rewriter so the content is not unique.

To Dos
1. If you don't have a python environment or an IDE, set it up
2. Copy the code and save it to a file with extension .py
3. Type in your reddit user name, password, client-id and client-secret. Find out how to make them here https://www.geeksforgeeks.org/how-t...nt_secret-for-python-reddit-api-registration/
4. Type in your wordpress username and Application Password. It won't work with your regular password. The guide to do that is here https://www.paidmembershipspro.com/create-application-password-wordpress/
5. If you need multithreading, set the flag to True, but initially I'd recommend keeping it at False so your host doesn't get surprised.
6. You can enter one subreddit at a time, or make a list of them one per line on sr.txt in the same folder as the code file.
7. Run the script.


Here is the code.

Python:
import praw, os, requests, time, random, base64, json, secrets, string
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime

redditUsername = ""
redditPassword = ""
redditClientId = ""
redditClientSecret = ""
redditPullLimit = 200
redditUserAgent= "postConsolidator_1.0"
wpDomain = '' ##DO NOT INCLUDE HTTPS OR WWW OR ANY TRAILING SLASHES. ONLY ENTER domainname.tld unless wordpress is located in a subfolder, in which case do not use a trailing slash
wpUsername = 'admin'
wpApplicationPassword = ''
wpHasHTTPS = True
wpPostStatus = 'publish'
wpCommentStatus = 'approve'
multiProcessFlag = False
multiProcessMaxWorkers = 16
reddit = praw.Reddit(username=redditUsername,
                     password=redditPassword,
                     client_id=redditClientId,
                     client_secret=redditClientSecret,
                     user_agent=redditUserAgent
                     )
wpCredentials = f'{wpUsername}:{wpApplicationPassword}'
wpCredentialsToken = base64.b64encode(wpCredentials.encode())
wpHeader = {'Authorization': 'Basic ' + wpCredentialsToken.decode('utf-8')}
if wpHasHTTPS:
    wpPostAPIURL = f'https://{wpDomain}/wp-json/wp/v2/posts/'
    wpCommentsAPIURL = f'https://{wpDomain}/wp-json/wp/v2/comments/'
    wpUsersAPIURL = f'https://{wpDomain}/wp-json/wp/v2/users/'
else:
    wpPostAPIURL = f'http://{wpDomain}/wp-json/wp/v2/posts/'
    wpCommentsAPIURL = f'http://{wpDomain}/wp-json/wp/v2/comments/'
    wpUsersAPIURL = f'http://{wpDomain}/wp-json/wp/v2/users/'
main_menu = '''
    Howdy!
        Hit
            1: Input name of Subreddit manually
            2: Import from a list of subreddits
            3. Exit
        Wachawannado? : '''
def post2wp(submission, i):
    if str(submission.selftext) == '':
        print('nothing to post')
        return

    wpUserDate = {
        'username':str(submission.author).lower().replace('_',"").replace('-',''),
        'email':str(submission.author).lower().replace('_',"").replace('-','') + '@' + wpDomain,
        'password':''.join(secrets.choice(string.ascii_letters + string.digits + '!@#$%^&*()_+=-`~;:"|?><,./') for i in range(16)),
        'roles':['subscriber'],
    }
    wpUserResponse = requests.post(url=wpUsersAPIURL, headers=wpHeader, json=wpUserDate)
    try:
        wpPostAuthorID = int(json.loads(wpUserResponse.text)['id'])
    except KeyError:
        print(f'{submission.author}, not created')
        print(wpUserResponse.text)
        wpPostAuthorID = 2
    print('Author ID', wpPostAuthorID)
    wpPostData = {
    'title' : submission.title,
    'status': wpPostStatus,
    'content': submission.selftext,
    'date_gmt':datetime.utcfromtimestamp(submission.created).strftime('%Y-%m-%dT%H:%M:%S'),
    'author':wpPostAuthorID,

    }
    wpPostResponse = requests.post(url=wpPostAPIURL, headers=wpHeader, json=wpPostData)
    print('wppostresponse', wpPostResponse)
    try:
        wpPostID = json.loads(wpPostResponse.text)['id']
    except KeyError:
        j=0
        print('Bad Response, skipping post')
        return
    submission.comments.replace_more(limit=None)
    for j, topLevelComment in enumerate(submission.comments):
        if topLevelComment is not None:
            wpCommentData = {
                'post': wpPostID,
                'author_name': topLevelComment.author,
                'author_email': str(topLevelComment.author) + '@' + wpDomain,
                'content': topLevelComment.body,
                'status':wpCommentStatus,
                'author_ip':str(random.randint(0,255))+'.'+str(random.randint(0,255))+'.'+str(random.randint(0,255))+'.'+str(random.randint(0,255)),
                'date_gmt':datetime.utcfromtimestamp(topLevelComment.created).strftime('%Y-%m-%dT%H:%M:%S'),

            }
            wp_comment_response = requests.post(url=wpCommentsAPIURL, headers=wpHeader, data=wpCommentData)
            print(i+1, j+1, wp_comment_response)
            if j > random.randint(75,125):
                break
    print(f'Item no. {i + 1} posted, with {j+1} comments and title{submission.title} and post content \n\n {submission.selftext} \n\n {wpPostResponse}')
if __name__ == '__main__':
    startTime = time.perf_counter()
    try:
        wachawannado = int(input(main_menu))
    except ValueError:
        print('\nPlease enter a number')
    if wachawannado == 1:
        subreddit = reddit.subreddit(input("Ok, lets crawl reddit.\nWhats the name of the subreddit? : "))
        with ProcessPoolExecutor(max_workers=multiProcessMaxWorkers) as executor:
            for i, submission in enumerate(subreddit.top(limit=redditPullLimit)):
                if multiProcessFlag:
                    executor.submit(post2wp, submission=submission, i=i)
                else:
                    post2wp(submission=submission, i=i)
    elif wachawannado == 2:
        if os.path.exists('sr.txt'):
            if not os.stat("sr.txt").st_size == 0:
                with open('sr.txt','r') as sr:
                    with ProcessPoolExecutor(max_workers=multiProcessMaxWorkers) as executor:
                        for i, line in enumerate(sr):
                            subreddit = reddit.subreddit(line)
                            for j, submission in enumerate(subreddit.top(limit=redditPullLimit)):
                                if multiProcessFlag:
                                    executor.submit(post2wp, submission=submission, i=j)
                                    if j % 99 == 0:
                                        print('yawn')
                                        time.sleep(61)
                                        print('Sorry, dozed off')
                                else:
                                    post2wp(submission=submission, i=j)
                            print(f'{i}:{line} done, pulled {j} submissions from {line}')
            else:
                print('sr.txt is empty')
        else:
            print('Cant find sr.txt with the list of SubReddits')
    elif wachawannado == 3:
        print('Bye!')
    else:
        print('\nHit a valid number\n')
    print('Total time for this loop is ', time.perf_counter()-startTime)
 
Your Own TikTok video maker bot

Do you look fugly even with filters? Do you sound like a croaking toad? Are you camera shy to make videos of yourself? Or are you just so damn lazy to use a video editor to make your own shorts from stock footage? Are you having to pay people on Fiverr to do it for you? Paranoid Android on Beast Mode is here for your rescue.

Get your API key from OpenAI.com, sign up and get a free $18 credit with the key. This is plenty to get you started
Install pycharm or your favorite python IDE and paste the script below.
Install all the libraries, pycharm makes it easy if you don't know what you're doing.
Run the script.


Order of execution:
1. Download background videos first. You can pick from copyright free playlists, single videos, or from a built in list of 4 videos.
2. Create Audio. Pass in a well formatted question about the topic, or make a list in a file q.txt and let OpenAI generate the text for you, which is then converted to voice files with Google Text to Speech
3. Make videos from the created audio files.
4. Upload to youtube or tiktok and watch the money roll in

If the Audio length is less than 60 secs, video is made to that length, and if the audio is longer than 60 secs, it gets trimmed to 60 secs. Play around with openai for a bit to figure out the optimal question format for what you're asking if you don't want too much of valuable information cut off in the end.

Audio creation is multithreaded so it is all done in almost no time if you have an ssd, and the background video downloads (required once) will depend on your internet speeds. But the videomaking at 1080x1920p resolution takes about 15 minutes per video on my 8 core Ryzen laptop with 16 gigs of ram running linux. So if you're going to be making multiple videos, you're going to have to leave your computer running when you're sleeping.

Wanna make your videos with your own audio? I've seen people do it with funny call recordings and stuff on TikTok. Just put your audio inside the 'tts' folder (after running the script once so the folders are created), and hit option 3 to get the audio cropped to 60 seconds and videos of exactly 1800 frames.

Python:
import concurrent.futures
import openai, os, random, time
from gtts import gTTS
import moviepy.editor as mp
from mutagen.mp3 import MP3
from pytube import Playlist, YouTube
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.audio.io.AudioFileClip import AudioFileClip

openai.api_key = "Your Key Here"
videoHeight = 1920


audiopath = 'tts/'
videopath = 'finalvideo/'

mainMenu = '''
    1. Make Audio from list in q.txt
    2. Input a question manually to make audio
    3. Make videos from available audio
    4. Download new backgrounds
    5. Exit
        Wachawannado? : '''

bgvdMainMenu = '''
1. Pull from a Playlist link
2.Pull from a video link Video
3. Download built in List of Videos Or any other key to return
  Wachawannado? : '''


def audioMaker(i, q):
    q = q.strip('\n')
    response = openai.Completion.create(
        model="text-davinci-002",
        prompt=q,
        temperature=0.7,
        max_tokens=500,
        top_p=1.0,
        frequency_penalty=0.0,
        presence_penalty=0.0
    )
    print(q, 'done')
    tts = gTTS(text=response["choices"][0]["text"], tld='ca', slow=False)
    if os.path.exists(f"tts/{q.replace(' ', '_')}.mp3"):
        newfilename = '_' + q.replace(' ', '_') + '.mp3'
        tts.save(f"tmp/{newfilename.replace(' ', '_')}.mp3")
        os.replace(f"tmp/{newfilename.replace(' ', '_')}.mp3", f"tts/{newfilename.replace(' ', '_')}.mp3")
        print('iteration', i, q, 'saved')
    else:
        tts.save(f"tmp/{q.replace(' ', '_')}.mp3")
        os.replace(f"tmp/{q.replace(' ', '_')}.mp3", f"tts/{q.replace(' ', '_')}.mp3")
        print('iteration', i, q, 'saved')


def videoMaker():
    aflist = os.listdir(path='tts/')
    for i, fname in enumerate(aflist):
        retry = 0
        if fname.endswith('.mp3'):
            while True:
                randomVideo = random.choice(os.listdir('bgvideo/'))
                if randomVideo.endswith('.mp4'):
                    backgroundVideo = VideoFileClip('bgvideo/' + randomVideo).without_audio().resize(height=videoHeight).crop(x1=1166.6, y1=0, x2=2246.6, y2=1920)
                    audioFileDuration = MP3(audiopath + fname).info.length
                    if  audioFileDuration < 60:
                        audioDuration = audioFileDuration
                        audioClip = mp.CompositeAudioClip([AudioFileClip(audiopath + fname)])
                        print('video length is shorter than 60 secs', audioDuration)
                    else:
                        audioDuration = 60
                        audioClip = mp.CompositeAudioClip([AudioFileClip(audiopath + fname)]).subclip(0, 60)
                    videoDuration = backgroundVideo.duration
                    if videoDuration >= audioDuration:
                        randRange = random.randrange(30, int(videoDuration - audioDuration))
                        videoSubClip = backgroundVideo.subclip(randRange, randRange + audioDuration)
                        print('found a video longer than audio')

                        videoSubClip.audio = audioClip
                        videoSubClip.write_videofile('tmp/' + fname.replace('.mp3', '.mp4'), fps=30, audio_codec='aac',
                                                     audio_bitrate='192k', verbose=True, threads=os.cpu_count())
                        os.replace(audiopath + fname, 'usedaudio/' + fname)
                        os.replace('tmp/'+ fname.replace('.mp3', '.mp4'), videopath + fname.replace('.mp3', '.mp4'))
                        break
                    else:
                        retry += 1
                        print('video is shorter than your fucking dick, retrying : ', retry + 1)
                        if retry > 10:
                            print('Audio probably too long, skipping after 10 tries. Skipping audio', fname)
                            os.replace(audiopath + fname, 'audiotoolong/' + fname)
                            break


def backgroundVideoDownloader():
    opt = int(input(bgvdMainMenu))
    if opt == 1:
        p = Playlist(input('What is the playlist link? : '))
        n = int(input('How many videos do you want to download?\n Hit 0 for all : '))
        for i, video in enumerate(p.videos):
            vidtitle = str(random.randint(100000, 1000000)) + '.mp4'
            print('Downloading', vidtitle)
            video.streams.filter(res="1080p").first().download(output_path='tmp/', filename=vidtitle, timeout=30,
                                                               max_retries=3, skip_existing=False)
            if os.path.exists('bgvideo/' + vidtitle):
                altvidtitle = str(random.randint(100000, 1000000)) + '.mp4'
                os.replace('tmp/' + vidtitle, 'bgvideo/' + altvidtitle)
            else:
                os.replace('tmp/' + vidtitle, 'bgvideo/' + vidtitle)
            print(i + 1, video.title, 'downloaded as', vidtitle)
            if i + 1 == n:
                break
    elif opt == 2:
        vidtitle = str(random.randint(100000, 1000000)) + '.mp4'
        p = YouTube(input('What is the video link? : '))
        p.streams.filter(res="1080p").first().download(output_path='tmp/', filename=vidtitle, skip_existing=False)
        if os.path.exists('bgvideo/' + vidtitle):
            altvidtitle = str(random.randint(100000, 1000000)) + '.mp4'
            os.replace('tmp/' + vidtitle, 'bgvideo/' + altvidtitle)
            print(p.title, 'downloaded as', altvidtitle)
        else:
            os.replace('tmp/' + vidtitle, 'bgvideo/' + vidtitle)
            print(p.title, 'downloaded as', vidtitle)
        print(p.title, 'downloaded')
    elif opt == 3:
        builtInListOfVideos = ["https://www.youtube.com/watch?v=vw5L4xCPy9Q", "https://www.youtube.com/watch?v=2X9QGY__0II", "https://www.youtube.com/watch?v=n_Dv4JMiwK8", "https://www.youtube.com/watch?v=qGa9kWREOnE"]
        for v in builtInListOfVideos:
            vidtitle = str(random.randint(100000, 1000000)) + '.mp4'
            YouTube(v).streams.filter(res="1080p").first().download(output_path='tmp/', filename=vidtitle, skip_existing=False)
            if os.path.exists('bgvideo/' + vidtitle):
                altvidtitle = str(random.randint(100000, 1000000)) + '.mp4'
                os.replace('tmp/' + vidtitle, 'bgvideo/' + altvidtitle)
                print(YouTube(v).title, 'downloaded as', altvidtitle)
            else:
                os.replace('tmp/' + vidtitle, 'bgvideo/' + vidtitle)
                print(YouTube(v).title, 'downloaded as', vidtitle)
            print(YouTube(v).title, 'downloaded')
    else:
        print('returning to main menu')
        return


if __name__ == '__main__':
    if not os.path.exists(audiopath):
        os.mkdir('tts')
    if not os.path.exists('audiotoolong/'):
        os.mkdir('audiotoolong')
    if not os.path.exists('bgvideo/'):
        os.mkdir('bgvideo')
    if not os.path.exists(videopath):
        os.mkdir('finalvideo')
    if not os.path.exists('tmp/'):
        os.mkdir('tmp')
    if not os.path.exists('usedaudio/'):
        os.mkdir('usedaudio')
    try:
        while True:
            wachawannado = int(input(mainMenu))
            if wachawannado == 1:
                if os.path.exists('q.txt'):
                    with open('q.txt', 'r') as q:
                        with concurrent.futures.ProcessPoolExecutor(max_workers=64) as executor:
                            for i, lines in enumerate(q):
                                executor.submit(audioMaker, i=i, q=lines)
                else:
                    print('q.txt not found. Create q.txt or hit 2 in the main menu')
            elif wachawannado == 2:
                audioMaker(q=input('Type a well worded clearly formatted question. Simple questions return very short answers: '), i=1)
            elif wachawannado == 3:
                videoMaker()
            elif wachawannado == 4:
                backgroundVideoDownloader()
            elif wachawannado == 5:
                print('Bye!')
                break
            else:
                print('\nLets try again\n')

    except KeyboardInterrupt:
        tmpdir = os.listdir('tmp/')
        if not tmpdir:
            print('\ntmp folder is empty, Bye!')
        else:
            for i, file in enumerate(tmpdir):
                os.remove('tmp/' + file)
            print(f'\n{i + 1} files cleared from the tmp folder. Bye!')

Sample output : https://www.dropbox.com/s/t7qpepk9i...ter_purification_plants_purify_water.mp4?dl=0
Question was 'Tell me in detail how commercial water purification plants purity water'
The video lasts only 30 secs. I'll let you play with it to find out how to make them around exactly 60 mins
 
The last 3 codes above were posted on their own threads earlier, just consolidating them here.
 
Hey, thanks for sharing all these scripts. These can be used 1:1 or altered to meet specific needs.

Here is a password generator to start with
import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] ln=5 nn=4 sn=3 password=[] for i in range(0,ln): password+=letters[random.randint(0,len(letters)-1)] for i in range(0, nn): password+=numbers[random.randint(0,len(numbers)-1)] for i in range(0, sn): password+=symbols[random.randint(0,len(symbols)-1)] random.shuffle(password) pw='' for char in password: pw+=char print(f'Password: {pw}')
A Simplified version of the password generator:
import secrets
password = secrets.token_urlsafe(12)
print(password)
 
Hey, thanks for sharing all these scripts. These can be used 1:1 or altered to meet specific needs.


A Simplified version of the password generator:
yeah I kind of use this in my recent scripts, what you've quoted is from my earlier days of python. Just plotting my journey here I guess. And if you look in the lib files, you'll actually find something similar to this. So it was worth sharing.
 
@Paranoid Android you are really good at it mate. I'm glad you're on this forum. It's being 1 or 2 months I started learning python to automate things but when I see all the crazy stuffs you are doing I am at the same time frustrated and excited kind of frustraxcited state :confused:. Any way thanks for your valuable scripts but know that you just got yourself into my competitors list.
 
@Paranoid Android you are really good at it mate. I'm glad you're on this forum. It's being 1 or 2 months I started learning python to automate things but when I see all the crazy stuffs you are doing I am at the same time frustrated and excited kind of frustraxcited state :confused:. Any way thanks for your valuable scripts but know that you just got yourself into my competitors list.
don't know, been depressed for a few months and this has been my suicide prevention strategy so far. The moment I run out of project ideas the suicidal thoughts kick in so I HAVE to look for new things to do to stay alive. Its a mater of survival.
 
don't know, been depressed for a few months and this has been my suicide prevention strategy so far. The moment I run out of project ideas the suicidal thoughts kick in so I HAVE to look for new things to do to stay alive. Its a mater of survival.
Damn like seriously ?
 
Back
Top