I have the algorithm below that performs likes and comments on instagram photos via URL, my goal is to run this script on an AWS machine within 5 minutes which will generate 288 comments per day. However, whenever he realizes that he already executes LIKE in the photo, he returns "LIKED 0 images | ALREADY LIKED: 1", and aborts the process. I wanted to create a deal for when LIKE already exists, just execute the comment, is it possible? If yes you can help me with provisioning examples or the solution in question, thank you!
from instapy import InstaPy
from instapy import smart_run
def connect(insta_username,insta_password):
try:
session = InstaPy(username=insta_username,
password=insta_password,
headless_browser=False)
return session
except Exception as e:
print("[FAILED] Caused by: {}".format(e))
def action(url,insta_username,insta_password):
session = connect(insta_username,insta_password)
try:
with smart_run(session):
# Always follow and like before, the algorithm understands how it has already been executed when used in place of the like function
# Define interaction settings
session.set_do_comment(enabled=True, percentage=100)
session.set_comments(["#user-id"])
session.set_user_interact(amount=1, randomize=False, percentage=100, media='Photo')
# Start the feature
session.interact_by_URL(urls=url, randomize=False, interact=True)
session.end()
except Exception as e:
print("[FAILED] Caused by: {}".format(e))
if __name__ == "__main__":
pics = ["https://www.instagram.com/p/id-here"]
for url in pics:
action(url,'username','password')
Related
My task is to call a function with photoshop through a telegram bot. To do this, I take user information from the telegram chat for the program (for example, some text to change it inside the psd), but when I call this function, my code gives the error "Please check if you have Photoshop installed correctly.", BUT if call the same function not through the bot, then everything works fine. What could be the problem?
What I already tried - reinstall photoshop, install newer version of photoshop, add path in windows environment variables. Running through pywin32 is not profitable for me.
here I take and send the argument to the function
#bot.message_handler(content_types=['text'])
def func(message):
if(message.text == '/ph'):
user_info = {'test' : 'exampletext'}
test_edit_text(user_info)
here is a function, it just changes the text
def test_edit_text(info_from):
try:
psApp = ps.Application()
psApp.Open(r"mypath\first.psd")
doc = psApp.Application.ActiveDocument
print(info_from['test'])
text_from_user = info_from['test']
layer1init = doc.ArtLayers["layer1"]
text_new_layer1 = layer1init.TextItem
text_new_layer1 .contents = f"{text_from_user .upper()}"
options = ps.JPEGSaveOptions(quality=5)
jpg = r'mypath\photo.jpg'
doc.saveAs(jpg, options, True)
except Exception as e:
print(e)
if we call the "test_edit_text()" function separately, not through the bot, everything will work
Currently, the below code returns all the posts from the profile:
profilename = 'oneplus'
loader = instaloader.Instaloader()
profile = Profile.from_username(loader.context,profilename)
posts = profile.get_posts()
If the profile has, say 3000 posts, it takes a lot of time to load for instaloader.
However, I just want most recent n posts, and n<10, how do I do that?
finally came across something handy!
Firstly:
pip install func_timeout
Imagine your function was:
def sum(x,y):
return x+y
Then use it like so:
from func_timeout import func_timeout, FunctionTimedOut
try:
seconds = 5 # times out after 5 secs
result=func_timeout(seconds,sum,args=(5,3))
except FunctionTimedOut:
print('timeout')
except Exception as e:
print(e)
For me, it works like a charm.
Note: if you are thinking of downloading the posts, make sure you also timeout control the download function, as the function scans all the comments, which can get pretty lengthy.
If in trouble, visit the website where I found it: https://pypi.org/project/func-timeout/
Cheers
I wrote a script that lists EC2 instances in Amazon Web Services. It writes the results to confluence. But it's behaving oddly.
I'm on windows 10. The first time I open a powershell terminal and run it it reports the correct number of servers in the AWS account.
The next time I run it (without changing anything at all) it doubles the resutls. And each time you run it again with the same arguments it reports the same incorrect (doubled) amount.
This is the function that lists the instances and this is where I think the trouble is, but I'm having trouble finding it:
def list_instances(aws_account, aws_account_number, interactive, regions, fieldnames, show_details):
today, aws_env_list, output_file, output_file_name, fieldnames = initialize(interactive, aws_account) options = arguments() instance_list = '' session = '' ec2 = '' account_found = '' PrivateDNS = None block_device_list = None instance_count = 0 account_type_message = '' profile_missing_message = '' region = ''
# Set the ec2 dictionary
ec2info = {}
# Write the file headers
if interactive == 1:
with open(output_file, mode='w+') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=',', lineterminator='\n')
writer.writeheader()
if 'gov' in aws_account and not 'admin' in aws_account:
try:
session = boto3.Session(profile_name=aws_account,region_name=region)
account_found = 'yes'
except botocore.exceptions.ProfileNotFound as e:
message = f"An exception has occurred: {e}"
account_found = 'no'
banner(message)
else:
try:
session = boto3.Session(profile_name=aws_account,region_name=region)
account_found = 'yes'
except botocore.exceptions.ProfileNotFound as e:
message = f"An exception has occurred: {e}"
account_found = 'no'
banner(message)
print(Fore.CYAN)
report_gov_or_comm(aws_account, account_found)
print(Fore.RESET)
for region in regions:
if 'gov' in aws_account and not 'admin' in aws_account:
try:
session = boto3.Session(profile_name=aws_account,region_name=region)
except botocore.exceptions.ProfileNotFound as e:
profile_missing_message = f"An exception has occurred: {e}" account_found = 'no' pass else: try: session = boto3.Session(profile_name=aws_account,region_name=region) account_found = 'yes' except botocore.exceptions.ProfileNotFound as e: profile_missing_message = f"An exception has occurred: {e}" pass try: ec2 = session.client("ec2") except Exception as e: pass
# Loop through the instances
try:
instance_list = ec2.describe_instances()
except Exception as e:
pass
try:
for reservation in instance_list["Reservations"]:
for instance in reservation.get("Instances", []):
instance_count = instance_count + 1
launch_time = instance["LaunchTime"]
launch_time_friendly = launch_time.strftime("%B %d %Y")
tree = objectpath.Tree(block_devices = set(tree.execute('$..BlockDeviceMappings['Ebs']['VolumeId']'))
if block_devices:
block_devices = list(block_devices)
block_devices = str(block_devices).replace('[','').replace(']','').replace("'",'')
else:
block_devices = None
private_ips = set(tree.execute('$..PrivateIpAddress'))
if private_ips:
private_ips_list = list(private_ips) private_ips_list = str(private_ips_list).replace('[','').replace(']','').replace(''','')
else:
private_ips_list = None
type(private_ips_list)
public_ips = set(tree.execute('$..PublicIp'))
if len(public_ips) == 0:
public_ips = None
if public_ips:
public_ips_list = list(public_ips)
public_ips_list = str(public_ips_list).replace('[','').replace(']','').replace("'",'')
else:
public_ips_list = None
if 'KeyName' in instance:
key_name = instance['KeyName']
else:
key_name = None
name = None
if 'Tags' in instance:
try:
tags = instance['Tags']
name = None
for tag in tags:
if tag["Key"] == "Name":
name = tag["Value"]
if tag["Key"] == "Engagement" or tag["Key"] == "Engagement Code":
engagement = tag["Value"]
except ValueError:
print("Instance: %s has no tags" % instance_id
pass
if 'VpcId' in instance:
vpc_id = instance['VpcId'] else: vpc_id = None if 'PrivateDnsName' in instance: private_dns = instance['PrivateDnsName'] else: private_dns = None if 'Platform' in instance: platform = instance['Platform'] else: platform = None print(f"Platform: {platform}") ec2info[instance['InstanceId']] = { 'AWS Account': aws_account, 'Account Number': aws_account_number, 'Name': name, 'Instance ID': instance['InstanceId'], 'Volumes': block_devices, 'Private IP': private_ips_list, 'Public IP': public_ips_list, 'Private DNS': private_dns, 'Availability Zone': instance['Placement']['AvailabilityZone'], 'VPC ID': vpc_id, 'Type': instance['InstanceType'], 'Platform': platform, 'Key Pair Name': key_name, 'State': instance['State']['Name'], 'Launch Date': launch_time_friendly } with open(output_file,'a') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=',', lineterminator='\n') writer.writerow({'AWS Account': aws_account, "Account Number": aws_account_number, 'Name': name, 'Instance ID': instance["InstanceId"], 'Volumes': block_devices, 'Private IP': private_ips_list, 'Public IP': public_ips_list, 'Private DNS': private_dns, 'Availability Zone': instance['Placement']['AvailabilityZone'], 'VPC ID': vpc_id, 'Type': instance["InstanceType"], 'Platform': platform, 'Key Pair Name': key_name, 'State': instance["State"]["Name"], 'Launch Date': launch_time_friendly})
if show_details == 'y' or show_details == 'yes': for instance_id, instance in ec2info.items(): if account_found == 'yes': print(Fore.RESET + "-------------------------------------") for key in [ 'AWS Account', 'Account Number', 'Name', 'Instance ID', 'Volumes', 'Private IP', 'Public IP', 'Private DNS', 'Availability Zone', 'VPC ID', 'Type', 'Platform', 'Key Pair Name', 'State', 'Launch Date' ]: print(Fore.GREEN + f"{key}: {instance.get(key)}") print(Fore.RESET + "-------------------------------------") else: pass ec2info = {} with open(output_file,'a') as csv_file: csv_file.close() except Exception as e: pass if profile_missing_message == '*': banner(profile_missing_message) print(Fore.GREEN) report_instance_stats(instance_count, aws_account, account_found) print(Fore.RESET + '\n') return output_file
This is a paste of the whole code for context: aws_ec2_list_instances.py
The first time you run it from the command line it reports the correct total of servers in EC2 (can be verified in the AWS console):
----------------------------------------------------------
There are: 51 EC2 instances in AWS Account: company-lab.
----------------------------------------------------------
The next time it's run with ABSOLUTELY NOTHING changed it reports this total:
----------------------------------------------------------
There are: 102 EC2 instances in AWS Account: company-lab.
----------------------------------------------------------
You literally just up arrow the command and it doubles the results. When it writes to confluence you can see duplicate servers listed. It does that each time you up arrow to run it again, with the same incorrect total (102 servers).
If you close the powershell command line and open again it's back to reporting the correct result (51 servers) which corresponds to what you see in the AWS console.
What the heck is happening, here? Why is it doing that and how do I correct the problem?
This is pretty mysterious! I don't think I'm going to be able to debug it without access to your environment. My suggestion is that you use pdb to try to figure out how instance_count is being incremented past 51. I'd recommend adding import pdb; pdb.set_trace() at line 210, that is, right after for reservation in instance_list["Reservations"]:. You can then inspect the value of instance_count each time through the loop, see whether instance_list["Reservations"] actually has duplicate data somehow, etc.
I'm trying out Python Client for Google Maps Services to pull a list of places using Places API.
Here is the GitHub page: https://github.com/googlemaps/google-maps-services-python
Here is the documentation page: https://googlemaps.github.io/google-maps-services-python/docs/2.4.4/#module-googlemaps.exceptions
In the .places def, I need to enter page_token in string format in order to get next 10 listings. When I run the codes below, it kept showing me INVALID_REQUEST
Here is my code:
places_result = gmaps.places(query="hotels in Singapore", page_token='')
for result in places_result['results']:
print(result['name'])
try :
places_result = gmaps.places(query="hotels in Singapore", page_token=places_result['next_page_token'])
except ApiError as e:
print(e)
else:
for result in places_result['results']:
print(result['name'])
Alright, after hours of trial and error. I noticed I need to add a time.sleep(2) to make it work. I'm not sure why but it works.
It failed with time.sleep(1), time.sleep(2) and above will solve the problem.
Hopefully someone can shed some light to the reason behind.
Here is my code that works to retrieve Places and go to the next page until the end. Remember to replace
1. your key at 'YOUR KEY HERE' and
2. the string you want to search at 'SEARCH SOMETHING'.
import googlemaps
import time
gmaps = googlemaps.Client(key='YOUR KEY HERE')
def printHotels(searchString, next=''):
try:
places_result = gmaps.places(query=searchString, page_token=next)
except ApiError as e:
print(e)
else:
for result in places_result['results']:
print(result['name'])
time.sleep(2)
try:
places_result['next_page_token']
except KeyError as e:
print('Complete')
else:
printHotels(searchString, next=places_result['next_page_token'])
if __name__ == '__main__':
printHotels('SEARCH SOMETHING')
So, I'm a complete noob when it comes to this kind of thing, and I need some help. I work in software QA for an ecommerce company, and we started using Saucelabs for our automated testing. I'm in the process of learning python but really know next to nothing at this point. I can build a decent test in Selenium IDE, export in Python/Selenium Webdriver, and run the test. Not an issue. However, how do I set the pass/fail flag on the interface? One of our devs wrote a parallel script so I can run a large number of tests at one time, but in order to do so I need to be able to see at a glance which tests have passed and which ones have failed. Can you help me? Thanks!
Also, any tutorials you are aware of on Selenium Webdriver would be helpful too! Really want to learn this stuff!
I did it this way, first you need to import some things
# These next imports for reporting Test status to Sauce Labs
import sys
import httplib
import base64
try:
import json
except ImportError:
import simplejson as json
Then you need this config
#Config to connect to SauceLabs REST API
config = {"username": "yourusernamehere",
"access-key": "youraccesskeyhere"}
Then you put your tests. At the end, before your TearDown you need to include
# Curl call to SauceLabs API to report Job Result
def set_test_status(self, jobid, passed):
base64string = base64.encodestring('%s:%s' % (config['username'], config['access-key']))[:-1]
body_content = json.dumps({"passed": passed})
connection = httplib.HTTPConnection("saucelabs.com")
connection.request('PUT', '/rest/v1/%s/jobs/%s' % (config['username'], jobid),
body_content,
headers={"Authorization": "Basic %s" % base64string})
result = connection.getresponse()
return result.status == 200
Then in your tearDown you need to include some kind of if logic. I did it this way (and it works)
def tearDown(self):
# sys.exc_info should be (None, None, None) if everything is OK, it fills with some values if something went wrong
# This if reports to Sauce Labs the outcome of the Test where True = Pass and False = Failed
if sys.exc_info() == (None, None, None):
self.set_test_status(self.driver.session_id, True)
else:
self.set_test_status(self.driver.session_id, False)
self.driver.quit()
self.assertEqual([], self.verificationErrors)
That did the trick for me
You can use Sauce labs REST API to mark your test pass/failed. You can find some example code given here