כיצד לבנות בוט ולמכן את העבודה היומיומית שלך

ברוב העבודות יש משימות שחוזרות על עצמן שתוכלו לבצע אוטומציה, מה שמפנה חלק מזמנכם היקר. זה הופך את האוטומציה למיומנות מרכזית לרכישה.

קבוצה מצומצמת של מהנדסי אוטומציה מיומנים ומומחי תחום עשויה להצליח לבצע אוטומציה רבות מהמשימות המייגעות ביותר של צוותים שלמים.

במאמר זה נחקור את היסודות של אוטומציה של זרימת עבודה באמצעות Python - שפת תכנות חזקה וקלה ללימוד. נשתמש בפייתון כדי לכתוב סקריפט אוטומציה קטן וקל ומועיל שינקה תיקיה נתונה ויכניס כל קובץ לתיקיה שלו בהתאם.

המטרה שלנו לא תהיה לכתוב קוד מושלם או ליצור ארכיטקטורות אידיאליות בהתחלה.

אנחנו גם לא נבנה שום דבר "לא חוקי". במקום זאת נבחן כיצד ליצור סקריפט שמנקה אוטומטית תיקיה נתונה ואת כל הקבצים שלה.

תוכן עניינים

  1. תחומי אוטומציה ואיפה להתחיל
    • אוטומציה פשוטה
    • אוטומציה API API
    • API הנדסה הפוכה
  2. שיקולים אתיים של אוטומציה
  3. יצירת סקריפט ניקוי מדריך
  4. מדריך מלא ליצירת בוטים ואוטומציה של העבודה היומיומית שלך

תחומי אוטומציה ואיפה להתחיל

נתחיל עם הגדרת סוג האוטומציות שיש.

אומנות האוטומציה חלה על רוב המגזרים. בתור התחלה, זה עוזר במשימות כמו חילוץ כתובות דוא"ל מחבורת מסמכים, כך שתוכלו לפוצץ דוא"ל. או גישות מורכבות יותר כמו אופטימיזציה של תהליכי עבודה ותהליכים בתוך תאגידים גדולים.

כמובן, מעבר מתסריטים אישיים קטנים לתשתיות אוטומציה גדולות שמחליפות אנשים בפועל כרוך בתהליך של למידה ושיפור. אז בואו נראה היכן תוכלו להתחיל את המסע.

אוטומציות פשוטות

אוטומציות פשוטות מאפשרות נקודת כניסה מהירה ופשוטה. זה יכול לכסות תהליכים עצמאיים קטנים כמו ניקוי פרויקטים ובנייה מחדש של קבצים בתוך ספריות, או חלקים בתהליך עבודה כמו שינוי אוטומטי של קבצים שנשמרו באופן אוטומטי.

אוטומציות ממשק API ציבורי

אוטומציות API ציבוריות הן הצורה הנפוצה ביותר של אוטומציה שכן אנו יכולים לגשת לרוב הפונקציונליות באמצעות בקשות HTTP לממשקי API כיום. לדוגמא, אם אתה רוצה להפוך את השקיית הגינה החכמה שלך ביתית לאוטומטית בבית.

לשם כך, אתה רוצה לבדוק את מזג האוויר של היום הנוכחי כדי לראות אם אתה צריך להשקות או אם יש גשם שנכנס.

API הנדסה הפוכה

אוטומציה מבוססת הנדסה לאחור של API נפוצה יותר בבוטים בפועל ובקטע "מתחזה בוט" בתרשים בסעיף "שיקולים אתיים" להלן.

באמצעות הנדסה לאחור של API, אנו מבינים את זרימת המשתמשים של יישומים. דוגמה אחת יכולה להיות הכניסה למשחק דפדפן מקוון.

על ידי הבנת תהליך הכניסה והאימות, אנו יכולים לשכפל התנהגות זו באמצעות התסריט שלנו. אז נוכל ליצור ממשק משלנו לעבודה עם היישום למרות שהם לא מספקים אותו בעצמם.

לא משנה לאיזו גישה אתה מכוון, שקול תמיד אם זה חוקי או לא.

אתה לא רוצה להכניס את עצמך לצרות, נכון? ?

שיקולים אתיים

פעם פנה אלי איזה בחור ב- GitHub ואמר לי את זה:

"לייקים ומעורבות הם מטבע דיגיטלי ואתה מעריך אותם."

זה דבק בי וגרם לי להטיל ספק בכלי שבניתי בדיוק למטרה זו.

העובדה כי אינטראקציות אלו והמעורבות ניתנות לאוטומציה ו"זיוף "יותר ויותר מובילה למערכת מדיה חברתית מעוותת ושבורה.

אנשים שמייצרים תוכן יקר וטוב אינם נראים למשתמשים אחרים ולחברות פרסומת אם הם לא משתמשים בבוטים ובמערכות מעורבות אחרות.

חבר שלי יצר את הקשר הבא עם "תשעת מעגלי הגיהינום" של דנטה, כאשר בכל צעד קרוב יותר להיות משפיע חברתי אתה מקבל פחות ופחות מודע עד כמה כל המערכת הזו שבורה.

אני רוצה לשתף אתכם כאן כאן מכיוון שאני חושב שזה ייצוג מדויק ביותר למה שהייתי עד אליו בזמן שעבדתי באופן פעיל עם משפיעים עם InstaPy.

רמה 1: לימבו - אם אתה בכלל לא בוט

רמה 2: פלירטוטים - כאשר אתה אוהב ומעקב ידני כמה שיותר אנשים כדי לגרום להם לעקוב אחריך / כמו לייק את ההודעות שלך

רמה 3: קונספירציה - כשאתה מצטרף לקבוצת טלגרם כדי לעשות לייק ולהגיב על 10 תמונות כך ש -10 האנשים הבאים יאהבו ויעירו תגובה על התמונה שלך

רמה 4: בגידה - כשאתה משתמש בעוזר וירטואלי בעלות נמוכה כדי לחבב ולעקוב מטעמך

רמה 5: תאווה - כשאתה משתמש בבוט כדי לתת לייקים ולא מקבל בתמורה שום לייקים (אבל אתה לא משלם עבור זה - למשל, סיומת Chrome)

רמה 6: הפקרות - כאשר אתה משתמש בבוט כדי לתת 50+ לייקים לקבל 50+ לייקים, אך אינך משלם עבורו - למשל, סיומת Chrome

רמה 7: סוס או חמדנות קיצונית - כשאתה משתמש בבוט כדי לעשות לייק / לעקוב / להגיב בין 200–700 תמונות, תוך התעלמות מהסיכוי להיאסר

רמה 8: זנות - כשאתה משלם שירות ידוע של צד שלישי כדי לעסוק בלייקים / עוקבים אוטומטיים עבורך, אך הם משתמשים בחשבונך כדי לייק / לעקוב אחורה

רמה 9: הונאה / כפירה - כשאתה קונה עוקבים ולייקים ומנסה למכור את עצמך למותגים כמשפיע

רמת הביקבוק ברשתות החברתיות כל כך רווחת, שאם לא תבצעי בוט, אתה תקוע ברמה 1 בלימבו , ללא צמיחת חסידים ומעורבות נמוכה יחסית לבני גילך.

בתיאוריה הכלכלית, זה ידוע כדילמת אסיר ומשחק סכום אפס . אם אני לא בוט ואתה בוט, אתה מנצח. אם אתה לא בוט ואני בוט, אני מנצח. אם אף אחד לא מתמקד, כולם מנצחים. אבל מכיוון שאין תמריץ לכולם לא לעשות בוט, כולם מתמחרים, כך שאף אחד לא מנצח.

היו מודעים לכך ולעולם אל תשכחו את ההשלכות שיש לכל כלי זה על המדיה החברתית.

אנו רוצים להימנע מהתמודדות עם השלכות אתיות ועדיין לעבוד על פרויקט אוטומציה כאן. זו הסיבה שניצור סקריפט ניקוי ספריות פשוט שיעזור לכם לארגן את התיקיות המבולגנות שלכם.

יצירת סקריפט ניקוי מדריך

כעת אנו רוצים להסתכל על תסריט פשוט למדי. זה מנקה באופן אוטומטי ספרייה נתונה על ידי העברת קבצים אלה לתיקיות בהתבסס על סיומת הקובץ.

אז כל מה שאנחנו רוצים לעשות זה:

הגדרת מנתח הטיעונים

Since we are working with operating system functionality like moving files, we need to import the os library. In addition to that, we want to give the user some control over what folder is cleaned up. We will use the argparse library for this.

import os import argparse

After importing the two libraries, let's first set up the argument parser. Make sure to give a description and a help text to each added argument to give valuable help to the user when they type --help.

Our argument will be named --path. The double dashes in front of the name tell the library that this is an optional argument. By default we want to use the current directory, so set the default value to be ".".

parser = argparse.ArgumentParser( description="Clean up directory and put files into according folders." ) parser.add_argument( "--path", type=str, default=".", help="Directory path of the to be cleaned directory", ) # parse the arguments given by the user and extract the path args = parser.parse_args() path = args.path print(f"Cleaning up directory {path}")

This already finishes the argument parsing section – it's quite simple and readable, right?

Let's execute our script and check for errors.

python directory_clean.py --path ./test => Cleaning up directory ./test

Once executed, we can see the directory name being printed to the console, perfect.

Let's now use the os library to get the files of the given path.

Getting a list of files from the folder

By using the os.listdir(path) method and providing it a valid path, we get a list of all the files and folders inside of that directory.

After listing all elements in the folder, we want to differentiate between files and folders since we don't want to clean up the folders, only the files.

In this case, we use a Python list comprehension to iterate through all the elements and put them into the new lists if they meet the given requirement of being a file or folder.

# get all files from given directory dir_content = os.listdir(path) # create a relative path from the path to the file and the document name path_dir_content = [os.path.join(path, doc) for doc in dir_content] # filter our directory content into a documents and folders list docs = [doc for doc in path_dir_content if os.path.isfile(doc)] folders = [folder for folder in path_dir_content if os.path.isdir(folder)] # counter to keep track of amount of moved files # and list of already created folders to avoid multiple creations moved = 0 created_folders = [] print(f"Cleaning up {len(docs)} of {len(dir_content)} elements.")

As always, let's make sure that our users get feedback. So add a print statement that gives the user an indication about how many files will be moved.

python directory_clean.py --path ./test => Cleaning up directory ./test => Cleaning up 60 of 60 elements.

After re-executing the python script, we can now see that the /test folder I created contains 60 files that will be moved.

Creating a folder for every file extension

The next and more important step now is to create the folder for each of the file extensions. We want to do this by going through all of our filtered files and if they have an extension for which there is no folder already, create one.

The os library helps us with more nice functionality like the splitting of the filetype and path of a given document, extracting the path itself and name of the document.  

# go through all files and move them into according folders for doc in docs: # separte name from file extension full_doc_path, filetype = os.path.splitext(doc) doc_path = os.path.dirname(full_doc_path) doc_name = os.path.basename(full_doc_path) print(filetype) print(full_doc_path) print(doc_path) print(doc_name) break

The break statement at the end of the code above makes sure that our terminal does not get spammed if our directory contains dozens of files.

Once we've set this up, let's execute our script to see an output similar to this:

python directory_clean.py --path ./test => ... => .pdf => ./test/test17 => ./test => test17

We can now see that the implementation above splits off the filetype and then extracts the parts from the full path.

Since we have the filetype now, we can check if a folder with the name of this type already exists.

Before we do that, we want to make sure to skip a few files. If we use the current directory "." as the path, we need to avoid moving the python script itself. A simple if condition takes care of that.

In addition to that, we don't want to move Hidden Files, so let's also include all files that start with a dot. The .DS_Store file on macOS is an example of a hidden file.

 # skip this file when it is in the directory if doc_name == "directory_clean" or doc_name.startswith('.'): continue # get the subfolder name and create folder if not exist subfolder_path = os.path.join(path, filetype[1:].lower()) if subfolder_path not in folders: # create the folder

Once we've taken care of the python script and hidden files, we can now move on to creating the folders on the system.

In addition to our check, if the folder already was there when we read the content of the directory, in the beginning, we need a way to track the folders we've already created. That was the reason we declared the created_folders = [] list. It will serve as the memory to track the names of folders.

To create a new folder, the os library provides a method called os.mkdir(folder_path) that takes a path and creates a folder with the given name there.

This method may throw an exception, telling us that the folder already exists. So let's also make sure to catch that error.

if subfolder_path not in folders and subfolder_path not in created_folders: try: os.mkdir(subfolder_path) created_folders.append(subfolder_path) print(f"Folder {subfolder_path} created.") except FileExistsError as err: print(f"Folder already exists at {subfolder_path}... {err}")

After setting up the folder creation, let's re-execute our script.

python directory_clean.py --path ./test => ... => Folder ./test/pdf created.

On the first run of execution, we can see a list of logs telling us that the folders with the given types of file extensions have been created.

Moving each file into the right subfolder

The last step now is to actually move the files into their new parent folders.

An important thing to understand when working with os operations is that sometimes operations can not be undone. This is, for example, the case with deletion. So it makes sense to first only log out the behavior our script would achieve if we execute it.

This is why the os.rename(...) method has been commented here.

# get the new folder path and move the file new_doc_path = os.path.join(subfolder_path, doc_name) + filetype # os.rename(doc, new_doc_path) moved += 1 print(f"Moved file {doc} to {new_doc_path}")

After executing our script and seeing the correct logging, we can now remove the comment hash before our os.rename() method and give it a final go.

# get the new folder path and move the file new_doc_path = os.path.join(subfolder_path, doc_name) + filetype os.rename(doc, new_doc_path) moved += 1 print(f"Moved file {doc} to {new_doc_path}") print(f"Renamed {moved} of {len(docs)} files.")
python directory_clean.py --path ./test => ... => Moved file ./test/test17.pdf to ./test/pdf/test17.pdf => ... => Renamed 60 of 60 files.

This final execution will now move all the files into their appropriate folders and our directory will be nicely cleaned up without the need for manual actions.

In the next step, we could now use the script we created above and, for example, schedule it to execute every Monday to clean up our Downloads folder for more structure.

That is exactly what we are creating as a follow-up inside of our Bot Creation and Workflow Automation Udemy course.

A Complete Guide to Bot Creation and Automating Your Everyday Work

Felix and I built an online video course to teach you how to create your own bots based on what we've learned building InstaPy and his Travian-Bot. In fact, he was even forced to take down since it was too effective.

Join right in and start learning.

If you have any questions or feedback, feel free to reach out to us on Twitter or directly in the discussion section of the course ?