Whatsapp Bot Problem when identifying any onLocateScreen object with Python - python

import pyautogui as pt
from time import sleep
import pyperclip
import random
sleep(3)
position1 = pt.locateOnScreen("whatsapp/smile.png", confidence=.6)
x = position1[0]
y = position1[1]
# Gets Message
def get_message():
global x, y
position = pt.locateOnScreen("whatsapp/smile.png", confidence=.6)
x = position[0]
y = position[1]
pt.moveTo(x, y, duration=.05)
get_message()
When I try to run this code and open Whatsapp desktop, it fails and shows an error message like
OSError: Failed to read whatsapp/smile.png because file is missing, has improper permissions, or is an unsupported or invalid format
The title and the image format are correct. I've checked it many times. Any other suggestions on what might be the issue here?

Related

How to add an exception in pyautogui

I created a code using pyautogui to send messages automatically in whatsapp, but there is a problem, I'm using a purchased database so some of the phones don't exist or aren't in whatsapp, how could I add this exception in pyautogui? when the phone exists, the program runs normally and clicks on starting the conversation as programmed, but when it does not exist, instead of sending the programmed message to the contact, it sends it to the group where the contacts are
import pyautogui
import pyperclip
import time
import random
import pygame
pyautogui.pause = 2
text = ("""message
message
message """)
pyautogui.press('win')
pyautogui.write('brave')
pyautogui.press('enter')
time.sleep(2)
pyautogui.hotkey('ctrl','t')
pyperclip.copy('https://web.whatsapp.com/')
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter')
time.sleep(10)
x = 1513
y = 152
yy = 183
for i in range(40):
#enter on the group
pyautogui.click(x=339, y=383)
#clicking into the contact
pyautogui.click(x=x, y=y)
time.sleep(1)
pyautogui.click(x=x, y=y)
time.sleep(random.uniform(1.2, 3.5))
pyautogui.click(x=x, y=y)
#the box with option of start a chat appears
pyautogui.click(x=1400, y=yy)
time.sleep(random.uniform(0.7, 1.8))
#click on the chat
pyautogui.click(x=788, y=966)
time.sleep(random.uniform(2.0, 3.8))
pyperclip.copy(text)
pyautogui.hotkey('ctrl','v')
time.sleep(random.uniform(2.0, 4.0))
pyautogui.press('enter')
time.sleep(random.uniform(4.5, 10.3))
y += 17
yy += 18
if i == 39:
pygame.init()
pygame.mixer.music.load("beet.mp3")
pygame.mixer.music.play()
Im expecting to find a answer to ignore when the phone does not exist and just proceed with the looping with the contacts below (with the y += 17, yy +=18)
You can't do this with pyautogui library since it's just a mouse/keyboard simulation library.
I would try to accomplish this using some libraries that include
text recognition functions such as OpenCv or TesseractOCR, google them.

Live Updates on Python

Terminal Running
I'm making a Python code to get me the real timevalues on some currencies to test the API, how do I keep it runnning and printing just the updated value, but without print the lines all over again, basically printing the currency names one time and keep updating the values without closing the terminal.
Here's my code:
import requests
import json
import colored
from colored import fg
print("Valor atualizado:\n\n")
cotacoes = requests.get("https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL,ETH-BRL")
cotacoes = cotacoes.json()
dolar = cotacoes['USDBRL']["bid"]
euro = cotacoes['EURBRL']["bid"]
bitcoin = cotacoes['BTCBRL']["bid"]
eth = cotacoes['ETHBRL']["bid"]
red = fg('red')
blue = fg('blue')
yellow = fg('yellow')
green = fg('green')
white = fg('white')
print(green + "Dólar:", dolar,"reais")
print(red + "Euro:", euro, "reais")
print(yellow + "Bitcoin:", bitcoin, "reais")
print(blue + "Etherium:", eth,"reais")
print(white)
Generally to override already written text you need to do some cursor positioning, but the simplest way is to clear the terminal in every iteration.
import os
import time
while True:
os.system('cls' if os.name == 'nt' else 'clear') # clears terminal
<get needed values>
<print everything>
time.sleep(1)

Python Memory leak in pyautogui, unsure the cause

I have a memory leak in my pyautogui script I made. I have no idea where it's coming from or what might be causing it.
The script is made to perfectly press space for a skill check in a game. So it just checks for when a pixel (out of an array) turns white and then changes color indicating the skill check bar has passed over it.
I don't feel like I'm doing anything unusual here that would cause a memory leak, it wouldn't be on the pyautogui side would it?
import pyautogui as auto
import keyboard
import random
import time
import random
circleLocations = [(1023, 522), (1025, 527), (1025, 537), (1024, 548), (1022, 560), (1018, 568)]
def delay(value1 = 0.05, value2 = 0.2):
return random.uniform(value1,value2)
def perfectSpacePress(x, y):
while auto.pixelMatchesColor(x, y, (255,255,255)):
print("waiting")
time.sleep(delay(0.1,0.15 ))
auto.press(' ')
print("PressedCircleSpace")
def checkCircle():
for location in circleLocations:
if auto.pixelMatchesColor(location[0], location[1], (255,255,255)):
perfectSpacePress(location[0], location[1])
try:
while True:
checkCircle()
time.sleep(0.1)
except KeyboardInterrupt:
print('\nDone.')

python win32 api document.getElementById Error

import win32com
import win32com.client
import win32gui
import win32con
import pythoncom
def getIEServer(hwnd, ieServer):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
ieServer.append(hwnd)
if __name__ == '__main__':
#pythoncom.CoInitializeEx(0) # not use this for multithreading
mainHwnd = win32gui.FindWindow('windowclass', 'windowtitle')
if mainHwnd:
ieServers = []
win32gui.EnumChildWindows(mainHwnd, getIEServer, ieServers)
if len(ieServers) > 0:
ieServer = ieServers[0]
msg = win32gui.RegisterWindowMessage('WM_HTML_GETOBJECT')
ret, result = win32gui.SendMessageTimeout(ieServer, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
doc = win32com.client.dynamic.Dispatch(ob)
print doc.url
# doc.all['id'].click()
You can get doc (document object) with the above code
If you try doc.getElementById ("some-id")
I get an error like the one below.
TypeError: getElementById () takes 1 positional argument but 2 were given
It will appear in IE11
Please Help Me T0T~
p.s The type of problem is different from the suggested answer.
I think I need to fix the error in pywin32.

Genetic Algorithm chromedriver snake

So I'm almost done completing a genetic algorithm for the snake game in python for this javascript snake game: http://patorjk.com/games/snake/
I've been getting an error for my code:
import selenium, os, urllib
from selenium import webdriver
import win32com.client as comctl
from random import randint
from operator import add
import time
import random
import lxml
from lxml import html
import requests
page=requests.get("http://patorjk.com/games/snake/")
tree=lxml.html.fromstring(page.content)
chromedriver="C:/Python34/Scripts/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
wsh = comctl.Dispatch("WScript.Shell")
wsh.AppActivate("patorjk.com/games/snake/")
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
driver.get('http://patorjk.com/games/snake/')
hidden_element = driver.find_element_by_id('sbTryAgain0')
def createIndividual(length, mintim, maxtim):
return [[random.uniform(mintim,maxtim) for x in range(length)],[randint(0,3) for x in range(length)],[]]
def changeInt(int1):
if(int1==0):
return '{UP}'
if(int1==1):
return '{RIGHT}'
if(int1==2):
return '{DOWN}'
if(int1==3):
return '{LEFT}'
def run(ind):
for x in range(len(ind[0])):
if hidden_element.is_displayed():
break
wsh.SendKeys(" ")
time.sleep(ind[0][x])
wsh.SendKeys(changeInt(ind[1][x]))
print(changeInt(ind[1][x]))
def indfit(time, pts):
tree=lxml.html.fromstring(page.content)
points=tree.xpath('//div[#class="snake-panel-component"]/text()')
for i in points:
if(points[i-1]==" " and points[i-2]==":"):
pts=int(points[i:len(points)-1])
#return (pts/time)
return pts
def createPopulation(size, length, mintim, maxtim):
population=[]
for x in range(size):
population.append(createIndividual(length, mintim, maxtim))
return population
def cyclePop(pop):
index1=0
for x in pop:
start_time=time.time()
pop1=pop[index1]
run(pop1)
pop[index1][2]=indfit(time.time()-start_time,1)
print("Fitness of individual ",(index1+1),": ",pop[index1][2])
wsh.SendKeys(" ")
index1+=1
print("Population Fitness: ",popFitScore(pop))
def popFitScore(pop):
sum1=0
for x in pop:
sum1+=x[2]
return sum1/len(pop)
def bubble_sort(items):
""" Implementation of bubble sort """
for i in range(len(items)):
for j in range(len(items)-1-i):
if items[j][2] > items[j+1][2]:
items[j], items[j+1] = items[j+1], items[j] # Swap!
def mixtraitscross(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=ind2[index1]
index1+=1
def mixtraitsavg(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=(ind1[index1]+ind2[index1])/2
index1+=1
def evolve(pop,mutrate,killpercent,sammin,sammax):
bubble_sort(pop)
startmutlen=(len(pop)-(killpercent*len(pop)))
mutrateind=mutrate*len(pop[0][0])
for ig in pop:
index1=pop.index(ig)
if index1>startmutlen:
for g in range(int(mutrateind)):
ig[0][randint(0,len(pop[0][0])-1)]=randint(0,3)
ig[1][randint(0,len(pop[0][0])-1)]=random.uniform(sammin,sammax)
else:
for iff in range(int(startmutlen-1)):
mixtraitscross(pop[index1][0],pop[index1+1][0])
mixtraitsavg(pop[index1][1],pop[index1+1][1])
#createPopulation(10, 20, 0, 5)
index8=0
while(index8<=50):
x=createPopulation(5,10,0,2)
cyclePop(x)
evolve(x,.30,.5,0,2)
index8+=1
so this is my code and i'm trying to make it so that if the element that says "You Died :(", it will stop running the individual and it will apply the time to the individual's fitness. I'm getting really confused with all of this chromedriver stuff with selenium and if I were able to get it to work, It would be perfect. the comment that says
#return (pts/time)
is what I want to be there, but until I am able to get the selenium working, the time is the same. I made it so that the time would be the same, but I want it so that it cuts off after it dies. Right now, I'm just having errors working with chromedriver, and I'm not exactly sure it's what I even want to be using. This is my error:
Traceback (most recent call last):
File "H:\Senior Year\CSAP2\Snakegenalg\SnakeJSGenAlg.py", line 27, in <module>
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
self.service.start()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site- packages\selenium\webdriver\common\service.py", line 86, in start
self.assert_process_still_running()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0
Sorry if I'm really bad at coding and I'm getting bad at this simple stuff, I'm just in high school and learned python this month. I'm not using the shorthand for stuff right now because it confuses me, but I know my code is easy to follow

Categories