def upload_to_albums(facebook_api: facebook.GraphAPI) -> None: """ Uploads a picture from the user to the album the user must select Arguments: facebook_api (object) : facebook api graph """ path = input_user_chat("Please enter the path of your picture: ") if path: albums_id = [] show_albums(facebook_api, albums_id) select = int(input_user_chat("Select the album: ")) - 1 select = validate_number(select, albums_id) caption = input_user_chat("Caption: ") try: facebook_api.put_photo(image = open(path, 'rb'), album_path = albums_id[select - 1] + "/photos", message = caption) print_write_chatbot("The photo has been uploaded successfully!", color = "green", attrs_color = ["bold"]) except Exception as error: write_log(STATUS_FILE, f"There was a problem opening the file, error: {error}", "Exception") print_write_chatbot(f"There was a problem opening the file, error: {error}", color = "red", attrs_color = ["bold"])
def connection_aux_api(username: str, password: str) -> object: """ This connection is made specifically for sending messages Arguments: username (str) : The username of the current instagram account password (str) : The password of the current instagram account Returns: object """ aux_api = '' try: logging.disable(logging.CRITICAL) aux_api = Bot() aux_api.login(username=username, password=password, use_cookie=False) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"There was an error:{error}", color="red", attrs_color=['bold']) write_log(STATUS_FILE, "You have successfully connected with the app", 'instagram.Bot') return aux_api
def connection_api(user_credentials: dict = {}) -> object: """ If the user does not enter their credentials, those of crux are used. Returns the facebook Api and checks if there was any error while connecting to Facebook Arguments: user_credentials (str): users token Returns: object - (facebook_api) """ facebook_api = '' if not user_credentials: credentials = get_credentials() page_token = credentials['facebook']['token'] else: page_token = user_credentials["token"] try: facebook_api = facebook.GraphAPI(access_token = page_token, version = "2.12") except Exception as err: write_log(STATUS_FILE, str(err), 'Exception') print("Error") else: write_log(STATUS_FILE, 'Successfully connected with Facebook the api', 'GraphAPI') print_write_chatbot('You have successfully connected with the Facebook api!\n', color = 'green', attrs_color = ["bold"]) return facebook_api
def edit_profile(api: Client) -> None: """ Available personal data is edited. What are full name, private account, biography, url, email, phone number and gender Arguments: api (Client) - object Client instagram """ # I call _call_api because the original function "current_user" was passing wrong parameters # and the request was not made correctly user_profile = api._call_api('accounts/current_user/', query={'edit': 'true'})['user'] text_to_print = "Your actual profile is: \n" genders = ['male', 'female', 'unspecified'] print_write_chatbot(text_to_print) attributes = { 'Full name': 'full_name', 'Private account': 'is_private', 'Biography': 'biography', 'External url': 'external_url', 'Email': 'email', 'Phone number': 'phone_number', 'Gender': 'gender', } new_profile_data = {} all_data = show_profile_data(user_profile, attributes, genders) text_to_print += all_data get_new_profile_data(user_profile, attributes, new_profile_data, genders) try: status_account = api.set_account_private( ) if new_profile_data['is_private'] else api.set_account_public() result = api.edit_profile( first_name=new_profile_data['full_name'], biography=new_profile_data['biography'], external_url=new_profile_data['external_url'], email=new_profile_data['email'], gender=int(new_profile_data['gender']), phone_number=new_profile_data['phone_number']) if result and status_account['status'] == 'ok': text = "Profile has been modified successfully!" print_write_chatbot(message=text, color='green', attrs_color=['bold']) else: text = "There was a problem updating the profile, please try again\n" print_write_chatbot(message=text, color='red', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"There was an error:{error}", color='red', attrs_color=['bold'])
def connection_instagram(user_credentials: dict = {}) -> object: """ The connection with the instagram api is generated (instagram_private_api module) Arguments: user_credentials (dict) = Dictionary in which the credentials of the user's instagram account are stored (default {}) Returns: object - The Client object """ api = '' if not user_credentials: credentials = get_credentials() username = credentials['instagram']['username'] password = credentials['instagram']['password'] else: username = user_credentials['username'] password = user_credentials['password'] settings_file = os.path.abspath('credentials/instagram_api.json') if os.path.isfile(settings_file): delete_expired_cookie(settings_file) if not os.path.isfile(settings_file): # If the credentials do not exist, do a new login try: api = Client( username, password, on_login=lambda x: on_login_callback(x, settings_file)) except Exception as err: write_log(STATUS_FILE, str(err), "Exception") else: # If the credentials do not exist, do a new login cached_settings = get_cached_settings(settings_file) device_id = cached_settings.get('device_id') try: api = Client(username, password, device_id=device_id, settings=cached_settings) except Exception as e: write_log(STATUS_FILE, str(e), "Exception") print_write_chatbot( "You have successfully connected with the instagram! \n", color='green', attrs_color=['bold']) return api
def upload_post(facebook_api: facebook.GraphAPI) -> None: """ Uploads the post written by the user and prints the success of the action if there are no errors Arguments: facebook_api (object) : facebook api graph """ user_message = input_user_chat("What would you like to write?: ") try: facebook_api.put_object(parent_object = 'me', connection_name = 'feed', message = user_message) print_write_chatbot("Posting has been updated successfully!\n", color = 'green', attrs_color = ["bold"]) except Exception as err: write_log(STATUS_FILE, str(err), 'Exception') print_write_chatbot(f"Error to upload a post {err}", color = "red", attrs_color = ['bold'])
def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simple replace the two lines below with: return auth.wiki() """ from datetime import datetime return dict(time=str(datetime.utcnow())) import logs logs.write_log("Manh vo dich") return logs.read_log("<br>") #response.flash = T("Welcome to web2py!" + str(logs.read_log("<br>"))) return dict(message=T('Hello World'))
def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simple replace the two lines below with: return auth.wiki() """ from datetime import datetime return dict(time=str(datetime.utcnow())) import logs logs.write_log("Manh vo dich") return logs.read_log("<br>") #response.flash = T("Welcome to web2py!" + str(logs.read_log("<br>"))) return dict(message=T('Hello World'))
def upload_photo(facebook_api: facebook.GraphAPI) -> None: """ Asks the user the path of the photo and the caption the user wants to upload, and uploads the photo and the caption Arguments: facebook_api (object) : facebook api graphThe facebook api """ path = search_file() caption = input_user_chat("Caption: ") try: facebook_api.put_photo(image = open(path, 'rb'), message = caption) print_write_chatbot("The photo has been uploaded successfully!", color = 'green', attrs_color = ["bold"]) except Exception as error: write_log(STATUS_FILE, f"There was a problem uploading the file, error: {error}", 'Exception') print_write_chatbot(f"There was a problem uploading the file, error: {error}", color = "red", attrs_color = ["bold"])
def follow(api: Client) -> None: """ A specific user was searched and that user will be followed by the current user Arguments: api (Client) : Object instagram Client """ search_users(api) username = input_user_chat(f"Who do you want to follow? ") user = api.username_info(username)['user'] user_id = user['pk'] try: api.friendships_create(user_id=user_id) text = f"{username} has a private account, we have sent him a request with success!" if user[ 'is_private'] else f"{username} has been followed with success!" print_write_chatbot(message=text, color='green', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"There was an error:{error}", color="red", attrs_color=['bold'])
def train_bot(bot) -> None: """ The txt containing the training is read and trains the bot Arguments: bot (ChatBot) : ChatBot object """ trainer = ListTrainer(bot) list_trainer = [] try: with open("trainer.txt") as file: lines = file.readlines() except Exception as error: write_log(STATUS_FILE, str(error), 'Crux') print_write_chatbot(str(error)) for line in lines: list_trainer.append(line.strip()) trainer.train(list_trainer)
def post_related(facebook_api: facebook.GraphAPI, action: str, selected: str) -> None: """ The posts of the page are shown and depending on the action, it will be edited / liked/ deleted / commented Arguments: facebook_api (object) : facebook api graph action (str) : The action the user wants to do selected (str) : The connection name the user selected """ posts_id = [] selection = 0 posts = get_posts(facebook_api, selected) info_list = posts['data'] print_write_chatbot("The posts are: ") for count, info in enumerate(info_list, start = 1): if_text_in_info(info, posts_id, count) if action != "read": option = int(input_user_chat("Select one: ")) - 1 option = validate_number(option, posts_id) selection = posts_id[option] try: if action == "like": like(facebook_api, selection) elif action == "comment": comment(facebook_api, selection) elif action == "delete": delete_post(facebook_api, selection) elif action == "edit": text = input_user_chat("Enter the new caption: ").capitalize() edit_post(facebook_api, selection, message = text) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"Error {error}", color = "red", attrs_color = ["bold"])
def unfollow(api: Client) -> None: """ Users who are followed by the current user are obtained and one of them chosen by the current user is unfollowed Arguments: api (Client) : Object instagram Client """ results = get_follows(api) username = input_user_chat(f"Who do you want to unfollow? ") for user in results['users']: try: if user['username'] == username and api.friendships_destroy( user['pk']): text = f"{username} has been successfully unfollowed!" print_write_chatbot(message=text, color='green', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"Error to unfollow: {error}", color="red", attrs_color=['bold'])
def main(): logs.write_log('***** Starting script *****', '') configuration = os.path.dirname( os.path.abspath(__file__)) + '/configuration.xml' suspendweekmode = 0 students = config.read_config(configuration) for i in range(len(students)): planfile = itslearning.construct_planfile(students[i]['student_id'], suspendweekmode) if os.path.isfile(planfile) == True: message = 'Plan exists in ' + str(planfile) + ', skipping...' logs.write_log(message, 'Skip') else: status = itslearning.request_plan(students[i]['student_id'], students[i]['student_name'], students[i]['site_path'], 'morfug', 'FM050881fi', suspendweekmode) if status == 'OK': logs.write_log('Plan retrieved to ' + str(planfile), 'Ok') else: logs.write_log(status, 'Error') result = google.insert(planfile, students[i]['calendar_id'], students[i]['student_id']) if result == '0': logs.write_log('Plan inserted to calendar', 'Success') else: logs.write_log(result, 'Error') logs.write_log('***** Script finished *****', '')
def likes_actions(api: Client, target_type: str, like_type: str = 'like') -> None: """ Depending on the type of target and type of like, a post or a comment will be liked or unlike Arguments: api (Client) : Object instagram Client target_type (str) : String that can be post or comment like_type (str) : String that can be like or unlike Returns: None """ try: if target_type != "comment": username = get_username( api, f"\nWhich user do you want to {like_type} the {target_type}? ") can_get_feed = is_following_user(api, username) if can_get_feed: feed, is_feed_empty = get_user_feed(api, username=username, show_feed=False) if not is_feed_empty: own_feed = username == api.username show_user_feed(api, feed['items'], own_feed=own_feed) post_id = get_post_id( feed=feed, text=f"Which post would you {like_type} to post a like?" ) if like_type == 'like': like_post(api, post_id=post_id[0], own_feed=own_feed) else: unlike_post(api, post_id[0]) else: print_write_chatbot(message="The user has no posts\n", color='red', attrs_color=['bold', 'underline']) else: print_write_chatbot( message=f"You cannot access the feed of the user {username} " f"because it is a private account that you do not follow, " f"or because it has blocked you\n", color='red', attrs_color=['bold', 'underline']) else: print_write_chatbot(message="Your feed: ", color='blue', attrs_color=['bold']) feed, is_feed_empty = get_user_feed(api, own_feed=True) if not is_feed_empty: text = f"Which comment would you like to post a {like_type}?" comment_data = prepare_comment(api=api, feed=feed['items'], text=text) if like_type == 'like': like_comment(api, comment_id=comment_data["comment_id"], own_feed=True) else: unlike_comment(api, comment_id=comment_data["comment_id"]) else: print_write_chatbot(message="Your feed is empty", color='red', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, f"There was an error:{error}", 'Exception') print_write_chatbot(f"There was an error:{error}", color='red', attrs_color=['bold'])
def post_comment(api: Client) -> None: """ Post a comment on a post from a user chosen by the current user Arguments: api (Client) : object instagram Client Returns: None """ username = get_username( api, "Who do you want to find to post a comment on his post?") can_get_feed, own_feed = is_following_user(api=api, username=username, client_username=api.username) if can_get_feed: feed, is_feed_empty = get_user_feed(api, username, own_feed=own_feed) if not is_feed_empty: comment_block = True text = "Which post would you like to comment on?" post_id, number_post = get_post_id(feed, text) want_put_comment = True while comment_block and want_put_comment: if 'comments_disabled' not in feed['items'][number_post]: comment_block = False else: print_write_chatbot( message= "The post has the comments blocked, please choose another post\n", color='red', attrs_color=['bold']) another_try = input_user_chat( "Do you want to try another comment? (yes/no) ") if user_answer_is_yes(another_try): post_id, number_post = get_post_id( feed, text), get_post_number(text=text, max_cant_posts=len( feed['items'])) else: want_put_comment = False if want_put_comment: message = input_user_chat("Message: ") result = api.post_comment(media_id=post_id, comment_text=message) try: if result['status'] == 'ok': print_write_chatbot( message="The comment has been posted correctly!\n", color='green', attrs_color=['bold']) except Exception as error: write_log(STATUS_FILE, str(error), 'Exception') print_write_chatbot(f"There was an error: {error}", color='red', attrs_color=['bold']) else: print_write_chatbot( message="It's okay if you couldn't leave a comment," " there are many posts in the sea, go get them tiger!\n", color='blue', attrs_color=['bold', 'underline']) else: print_write_chatbot(message="You cant get the feed", color='red', attrs_color=['bold'])