Remove click in the middle of the message screen in pywhatkit - python

Can anybody help me.
When using sendwhats_image, before starting to type the text, he clicks in the middle of the screen. When entering the code, on line 135, there is no field that informs about this click, but looking at line 30, there is a pg.click(core.WIDTH / 2, core.HEIGHT / 2) but, even removing this line, the click still remains. I don't know where I can block this click, or change position.
My Code:
# Enviar Print Report PV MT -
imgreportPvMT ='C:/Users/Corporativo/Documents/Bot Alphard/reportPVMT.png'
kt.sendwhats_image("+5561xxxxxxxx",imgreportPvMT,"José Artur - Report Pós Vendas",15,True)
time.sleep(10)
when I click on control and on top of sendwhats_image , so I can see the code, I don't find anything that refers to the click on the screen. There is a pg.click(core.WIDTH / 2, core.HEIGHT / 2) on line 30, but it refers to sendwhatmsg_instantly
def sendwhats_image(
receiver: str,
img_path: str,
caption: str = "",
wait_time: int = 15,
tab_close: bool = False,
close_time: int = 4,
) -> None:
"""Send Image to a WhatsApp Contact or Group at a Certain Time"""
if (not receiver.isalnum()) and (not core.check_number(number=receiver)):
raise exceptions.CountryCodeException("Country Code Missing in Phone Number!")
current_time = time.localtime()
core.send_image(
path=img_path, caption=caption, receiver=receiver, wait_time=wait_time
)
log.log_image(_time=current_time, path=img_path, receiver=receiver, caption=caption)
if tab_close:
core.close_tab(wait_time=close_time)
I tried taking the code at line 30, pg.click(core.WIDTH / 2, core.HEIGHT / 2) on line 30, but it refers to sendwhatmsg_instantly

Related

ValueError: empty range for randrange() (0, 0, 0) - function in a Tkinter button

Here's the error code :
Traceaback (most recent call last):
File "D:\Programmes\PyCharm Edu 2022.2.2\projects\mdp.py", line 115, in <module>
gen = Button(tabUser, text="Générer", fg="white", bg="#006400", font=("",15), command=generationMdp(longMdp, listeMain))
File "D:\Programmes\PyCharm Edu 2022.2.2\projects\mdp.py", line 39, in generationMdp
k = randint(0, o)
File "C:\Program Files\Python38\lib\random.py", line 248, in randint
return self.randrange(a, b+1)
File "C:\Program Files\Python38\lib\random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
Function :
def generationMdp(longMdp, listeM):
gene = ""
for i in range(0, longMdp+1):
o = len(listeM)-1
k = randint(0, o)
gene = gene + str(listeM[k])
del listeM[k]
return gene
Button :
gen = Button(tabUser, text="Générer", fg="white", bg="#006400", font=("", 15), command=generationMdp(longMdp, listeMain))
My goal is to run the "generationMdp" function every time the button "gen" is clicked.
I tried to see if the issue came from the function itself but it ended up working fine on its own so I think the issue comes from the code in the button but I cannot find where.
My goal is to run the "generationMdp" function every time the button
"gen" is clicked.
The button's command has to point to a function (that gets run whenever you press this button):
def show_somr_mdp():
print('listeMain has', len(listeMain), "elements, of which I'll get", longMdp+1)
print( generationMdp(longMdp, listeMain) )
gen = Button(....., command=show_somr_mdp)
Currently, your code doesn't make sense: you assign the result of generationMdp to the button's command. And my guess is that you populate listeMain & longMdp after that line got executed, which probably means this function got an empty listeMain. But that's just a guess.
As for generationMdp: as #jasonharper pointed out, it removes elements from listeM (and therefore listeMain too), and this is going to affect the next calls to this function (and likely lead to the error you see, sooner or later). To fix this, either send this function a copy of the list (listeMain.copy()), or have this copy made in the function, or (better) rewrite your code to use random.sample().
At the least add assert longMdp+1 <= len(listeM) to that function.

Pyautogui - click on image: cannot unpack non-iterable NoneType object

I'm writing a script to fill a monthly tax form using pyautogui.
There are 2 images to be clicked on.
Issue
I'm getting the following error on the second one:
PS C:\Users\Rodrigo\OneDrive\Documentos\Python> & C:/Users/Rodrigo/AppData/Local/Programs/Python/Python310/python.exe c:/Users/Rodrigo/OneDrive/Documentos/Python/SIFERE/saf.py
Traceback (most recent call last):
File "c:\Users\Rodrigo\OneDrive\Documentos\Python\SIFERE\saf.py", line 16, in <module>
pyautogui.click('SIFERE/agrega_saf.png')
File "C:\Users\Rodrigo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui\__init__.py", line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "C:\Users\Rodrigo\AppData\Local\Programs\Python\Python310\lib\site-packages\pyautogui\__init__.py", line 980, in click
x, y = _normalizeXYArgs(x, y)
TypeError: cannot unpack non-iterable NoneType object
PS C:\Users\Rodrigo\OneDrive\Documentos\Python>
Code
import pyautogui, time
time.sleep(3)
anio='2015'
mes='abril'
secuencia='1'
monto='1234.56'
pyautogui.click('SIFERE/periodo.png')
pyautogui.press('tab')
pyautogui.write(anio)
pyautogui.press('tab')
pyautogui.write(mes)
pyautogui.press('tab')
pyautogui.write(secuencia)
pyautogui.press('tab')
pyautogui.write(monto)
pyautogui.click('SIFERE/agrega_saf.png')
I've copied that exact same line to another py file and it works, but not on this one.
I think you want to locate the given images on your screen.
Therefor PyAutoGUI has the function locateOnScreen(image) which returns a location. If the image was found, the location is defined otherwise it's None.
See also: How to detect an image and click it with pyautogui?
Try to locate the given images first. If they were found, then continue with your input.
Code
import pyautogui, time
anio='2015'
mes='abril'
secuencia='1'
monto='1234.56'
def find_image_or_exit(image):
i = 1
while location == None and i < 3: # try max 3 times (for 9 seconds)
time.sleep(3) # wait 3 seconds
location = pyautogui.locateOnScreen(image)
i += 1
if location == None:
print(f"Sorry! Image {image} not found on screen. Aborting!")
exit()
return location
def enter_period():
location = find_image_or_exit('SIFERE/periodo.png')
pyautogui.click(location)
pyautogui.press('tab')
pyautogui.write(anio)
pyautogui.press('tab')
pyautogui.write(mes)
pyautogui.press('tab')
pyautogui.write(secuencia)
pyautogui.press('tab')
pyautogui.write(monto)
def add_saf():
location = find_image_or_exit('SIFERE/agrega_saf.png')
pyautogui.click(location)
# main steps
enter_period()
add_saf()

Can scraping be applied to this page which is actively recalculating?

I would like to grab satellite positions from the page(s) below, but I'm not sure if scraping is appropriate because the page appears to be updating itself every second using some internal code (it keeps updating after I disconnect from the internet). Background information can be found in my question at Space Stackexchange: A nicer way to download the positions of the Orbcomm-2 satellites.
I need a "snapshot" of four items simultaneously:
UTC time
latitude
longitude
altitude
Right now I use screen shots and manual typing. Since these values are being updated by the page - is conventional web-scraping going to work here? I found a "screen-scraping" tag, should I try to learn about that instead?
I'm looking for the simplest solution to get those four values, I wonder if I can just use urllib or urllib2 and avoid installing something new?
example page: http://www.satview.org/?sat_id=41186U I need to do 41179U through 41189U (the eleven Orbcomm-2 satellites that SpaceX just put in orbit)
One option would be to fire up a real browser and continuously poll the position in an endless loop:
import time
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.satview.org/?sat_id=41186U")
while True:
location = driver.find_element_by_css_selector("#sat_latlon .texto_track2").text
latitude, longitude = location.split("\n")[:2]
print(latitude, longitude)
time.sleep(1)
Sample output:
(u'-16.57', u'66.63')
(u'-16.61', u'66.67')
...
Here we are using selenium and Firefox - there are multiple drivers for different browsers including headless, like PhantomJS.
no need to scrape. Just look at the source html of that page and copy/paste the javascript code. None of the positions are fetched remotely...they're all calculated on the fly in the page. So just grab the code and run it yourself!
Space-Track.org's REST API seems built to handle this type of request. Once you have an account there, you can even download a sample script (updated here) to download TLES:
# STTest.py
#
# Simple Python app to extract resident space object history data from www.space-track.org into a spreadsheet
# (prior to executing, register for a free personal account at https://www.space-track.org/auth/createAccount)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# For full licencing terms, please refer to the GNU General Public License (gpl-3_0.txt) distributed with this release,
# or see http://www.gnu.org/licenses/gpl-3.0.html.
import requests
import json
import xlsxwriter
import time
import datetime
import getpass
import sys
class MyError(Exception):
def __init___(self, args):
Exception.__init__(self, "my exception was raised with arguments {0}".format(args))
self.args = args
# See https://www.space-track.org/documentation for details on REST queries
# "Find Starlinks" query finds all satellites w/ NORAD_CAT_ID > 40000 & OBJECT_NAME matching STARLINK*, 1 line per sat;
# the "OMM Starlink" query gets all Orbital Mean-Elements Messages (OMM) for a specific NORAD_CAT_ID in JSON format.
uriBase = "https://www.space-track.org"
requestLogin = "/ajaxauth/login"
requestCmdAction = "/basicspacedata/query"
requestFindStarlinks = "/class/tle_latest/NORAD_CAT_ID/>40000/ORDINAL/1/OBJECT_NAME/STARLINK~~/format/json/orderby/NORAD_CAT_ID%20asc"
requestOMMStarlink1 = "/class/omm/NORAD_CAT_ID/"
requestOMMStarlink2 = "/orderby/EPOCH%20asc/format/json"
# Parameters to derive apoapsis and periapsis from mean motion (see https://en.wikipedia.org/wiki/Mean_motion)
GM = 398600441800000.0
GM13 = GM ** (1.0 / 3.0)
MRAD = 6378.137
PI = 3.14159265358979
TPI86 = 2.0 * PI / 86400.0
# Log in to personal account obtained by registering for free at https://www.space-track.org/auth/createAccount
print('\nEnter your personal Space-Track.org username (usually your email address for registration): ')
configUsr = input()
print('Username capture complete.\n')
configPwd = getpass.getpass(prompt='Securely enter your Space-Track.org password (minimum of 15 characters): ')
# Excel Output file name - e.g. starlink-track.xlsx (note: make it an .xlsx file)
configOut = 'STText.xslx'
siteCred = {'identity': configUsr, 'password': configPwd}
# User xlsxwriter package to write the .xlsx file
print('Creating Microsoft Excel (.xlsx) file to contain outputs...')
workbook = xlsxwriter.Workbook(configOut)
worksheet = workbook.add_worksheet()
z0_format = workbook.add_format({'num_format': '#,##0'})
z1_format = workbook.add_format({'num_format': '#,##0.0'})
z2_format = workbook.add_format({'num_format': '#,##0.00'})
z3_format = workbook.add_format({'num_format': '#,##0.000'})
# write the headers on the spreadsheet
print('Starting to write outputs to Excel file create...')
now = datetime.datetime.now()
nowStr = now.strftime("%m/%d/%Y %H:%M:%S")
worksheet.write('A1', 'Starlink data from' + uriBase + " on " + nowStr)
worksheet.write('A3', 'NORAD_CAT_ID')
worksheet.write('B3', 'SATNAME')
worksheet.write('C3', 'EPOCH')
worksheet.write('D3', 'Orb')
worksheet.write('E3', 'Inc')
worksheet.write('F3', 'Ecc')
worksheet.write('G3', 'MnM')
worksheet.write('H3', 'ApA')
worksheet.write('I3', 'PeA')
worksheet.write('J3', 'AvA')
worksheet.write('K3', 'LAN')
worksheet.write('L3', 'AgP')
worksheet.write('M3', 'MnA')
worksheet.write('N3', 'SMa')
worksheet.write('O3', 'T')
worksheet.write('P3', 'Vel')
wsline = 3
def countdown(t, step=1, msg='Sleeping...'): # in seconds
pad_str = ' ' * len('%d' % step)
for i in range(t, 0, -step):
sys.stdout.write('{} for the next {} seconds {}\r'.format(msg, i, pad_str))
sys.stdout.flush()
time.sleep(step)
print('Done {} for {} seconds! {}'.format(msg, t, pad_str))
# use requests package to drive the RESTful session with space-track.org
print('Interfacing with SpaceTrack.org to obtain data...')
with requests.Session() as session:
# Need to log in first. NOTE: we get a 200 to say the web site got the data, not that we are logged in.
resp = session.post(uriBase + requestLogin, data=siteCred)
if resp.status_code != 200:
raise MyError(resp, "POST fail on login.")
# This query picks up all Starlink satellites from the catalog. NOTE: a 401 failure shows you have bad credentials.
resp = session.get(uriBase + requestCmdAction + requestFindStarlinks)
if resp.status_code != 200:
print(resp)
raise MyError(resp, "GET fail on request for resident space objects.")
# Use json package to break json-formatted response into a Python structure (a list of dictionaries)
retData = json.loads(resp.text)
satCount = len(retData)
satIds = []
for e in retData:
# each e describes the latest elements for one resident space object. We just need the NORAD_CAT_ID...
catId = e['NORAD_CAT_ID']
satIds.append(catId)
# Using our new list of resident space object NORAD_CAT_IDs, we can now get the OMM message
maxs = 1 # counter for number of sessions we have established without a pause in querying space-track.org
for s in satIds:
resp = session.get(uriBase + requestCmdAction + requestOMMStarlink1 + s + requestOMMStarlink2)
if resp.status_code != 200:
# If you are getting error 500's here, its probably the rate throttle on the site (20/min and 200/hr)
# wait a while and retry
print(resp)
raise MyError(resp, "GET fail on request for resident space object number " + s + '.')
# the data here can be quite large, as it's all the elements for every entry for one resident space object
retData = json.loads(resp.text)
for e in retData:
# each element is one reading of the orbital elements for one resident space object
print("Scanning satellite " + e['OBJECT_NAME'] + " at epoch " + e['EPOCH'] + '...')
mmoti = float(e['MEAN_MOTION'])
ecc = float(e['ECCENTRICITY'])
worksheet.write(wsline, 0, int(e['NORAD_CAT_ID']))
worksheet.write(wsline, 1, e['OBJECT_NAME'])
worksheet.write(wsline, 2, e['EPOCH'])
worksheet.write(wsline, 3, float(e['REV_AT_EPOCH']))
worksheet.write(wsline, 4, float(e['INCLINATION']), z1_format)
worksheet.write(wsline, 5, ecc, z3_format)
worksheet.write(wsline, 6, mmoti, z1_format)
# do some ninja-fu to flip Mean Motion into Apoapsis and Periapsis, and to get orbital period and velocity
sma = GM13 / ((TPI86 * mmoti) ** (2.0 / 3.0)) / 1000.0
apo = sma * (1.0 + ecc) - MRAD
per = sma * (1.0 - ecc) - MRAD
smak = sma * 1000.0
orbT = 2.0 * PI * ((smak ** 3.0) / GM) ** (0.5)
orbV = (GM / smak) ** (0.5)
worksheet.write(wsline, 7, apo, z1_format)
worksheet.write(wsline, 8, per, z1_format)
worksheet.write(wsline, 9, (apo + per) / 2.0, z1_format)
worksheet.write(wsline, 10, float(e['RA_OF_ASC_NODE']), z1_format)
worksheet.write(wsline, 11, float(e['ARG_OF_PERICENTER']), z1_format)
worksheet.write(wsline, 12, float(e['MEAN_ANOMALY']), z1_format)
worksheet.write(wsline, 13, sma, z1_format)
worksheet.write(wsline, 14, orbT, z0_format)
worksheet.write(wsline, 15, orbV, z0_format)
wsline = wsline + 1
maxs = maxs + 1
print(str(maxs))
if maxs > 18:
print('\nSnoozing for 60 secs for rate limit reasons (max 20/min and 200/hr).')
countdown(60)
maxs = 1
session.close()
workbook.close()
print('\nCompleted session.')

Python Return Invalid Syntax Error

I am writing a simple python program on a raspberry pi and I am quite new to python programming. I have defined a function called GetMessage which has no parameters and returns a variable which I called data, but I am getting an error which states
File "Raspberry_pi.py", line 39
return none
^
SyntaxError: invalid syntax
import os
import glob
import time
import RPi.GPIO as GPIO
from math import *
from bluetooth import *
from RPIO import PWM
os.system('sudo hciconfig hci0 pisca')
os.system('sudo hciconfig hci0 name "De Quadcoptur"')
servo = PWM.Servo()
StartSpin()
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
GetMessage()
DecodeInput()
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
def GetMessage():
advertise_service( server_sock, "XT1032", #phone bluetooth name
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
#protocols = [ OBEX_UUID ]
)
client_sock, client_info = server_sock.accept()
try:
data = client_sock.recv(1024)
if len(data) == 0: break
print "received [%s]" % data
client_sock.close()
server_sock.close()
except IOError:
pass
break
return data
def StartSpin():
# Set servo on GPIO17 to 1200µs (1.2ms)
servo.set_servo(17, 1000)
servo.set_servo(18, 1000)
servo.set_servo(19, 1000)
servo.set_servo(20, 1000)
time.sleep(1)
servo.stop_servo(17)
servo.stop_servo(18)
servo.stop_servo(19)
servo.stop_servo(20)
#Check if more pulses is faster
time.sleep(2000)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
PWM.add_channel_pulse(0, 17, start = 1000, width = 100)
servo.stop_servo(17)
servo.stop_servo(18)
servo.stop_servo(19)
servo.stop_servo(20)
return None
def DecodeInput():
data = GetMessage()
if(data == 'start')
StartSpin()
return 0
else if(data[0] == 'U')
data.strip('U')
UpPower = int(data)
SetUpPower(UpPower)
else if(data[0] == 'P')
data.strip('P')
PitchPower = int(data)
SetPitchPower
else
data.strip('P')
RollPower = int(data)
SetPower(UpPower, PitchPower, RollPower)
return None
def SetPower(UpPower, PitchPower, RollPower):
#Make Arbitrary Values
Motor1Power = UpPower #Front Left
Motor2Power = UpPower #Front Right
Motor3Power = UpPower #Back Left
Motor4Power = UpPower #Back Right
PitchPower = PitchPower /2
RollPower = RollPower /2
if(PitchPower < 25)
Motor1Power = Motor1Power + abs(25-PitchPower)
Motor2Power = Motor1Power + abs(25-PitchPower)
else
Motor3Power = Motor3Power + (PitchPower-25)
Motor4Power = Motor4Power + (PitchPower-25)
if(RollPower < 25)
Motor1Power = Motor1Power + abs(25-RollPower)
Motor3Power = Motor3Power + abs(25-RollPower)
else
Motor2Power = Motor2Power + (RollPower - 25)
Motor4Power = Motor4Power + (RollPower - 25)
What is causing this error and how can I fix it?
Edit: I have defined data as a global variable and the error now is
File "Raspberry_pi.py", line 39
return data
^
SyntaxError: invalid syntax
There are a number of syntax problems in your code. Because of the nature of SyntaxError exceptions (which are raised when the interpreter doesn't understand the code syntax), the error messages may not identify the right line as the source of the problem.
The first syntax error I see is that you're using break in the GetMessage function without it being in a loop. A break statement is only useful within a for or while block, and using one elsewhere (in an except block in this case) is a syntax error.
The next set of errors have to do with missing colons. Each of the conditional branches in DecodeInput and SetPower need to have a colon after the condition: if condition1:, elif condition2:, else:
It's also an error to use else if rather than elif (you could make it work if you added a colon, a newline and an extra level of indentation after else:, then used a separate if statement, but that would be wasteful of space).
There are some additional issues, but they're not syntax errors. For instance, you're calling your functions from top-level code before they've been defined, and DecodeInput has a line with the bare expression SetPower which doesn't do anything useful (you probably want to call SetPower with some argument).
Hopefully this will get you on the right track.
Once you get your colons fixed, you'll probably run into a problem with your GetMessage syntax. You cannot break unless you're inside of a loop. If you intend to return from an exception, you don't need the pass call. An example (simplified from your code) of how this method could (should?) look:
def GetMessage():
data = None
try:
data = [1,2]
if len(data) == 0:
return None
except IOError:
return None
return data
Clearly you'll want to replace the bulk of the method with your own code, and determine if you really want to return from the function at the points where you put breaks.

how can i update the value of a textbox in a live manner?

I have a gui interface in blender and the following should be the scenario for the user :
after pressing the button "Run" then the user could enter sentences in the input text box such that each sentence should be ended with a dot point '.' then if the user enter a sentence then the input box should be cleared and the entered sentence should be displayed in the output text box.
The problem is in the following part of code :
while 1:
input = Textbox1.val
if input.__contains__('.'):
Textbox1.val = ''
Textbox2.val = input
And here is all of my code:
import Blender
from Blender.BGL import *
from Blender.Draw import *
def draw_gui():
global Textbox1, Textbox2
Textbox1 = Create('input')
Textbox2 = Create('output')
glClearColor(0.753, 0.753, 0.753, 0.0)
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(0.000, 0.000, 0.627)
glRecti(20, 150, 730,500)
Button('Exit', 1, 450, 220, 87, 31)
Button('Quit', 2, 350, 220, 87, 31)
Button('Run', 3, 250, 220, 87, 31)
Textbox1 = String('', 4, 50, 400, 650, 50, Textbox1.val, 399, '')
Textbox2 = String('', 4, 50, 300, 650, 50, Textbox2.val, 399, '')
def event(evt, val):
if (evt==QKEY and not val): Exit()
def bevent(evt):
if evt == 1: #cmdExit
Exit()
elif evt == 2 : #cmdQuit
Blender.Quit()
elif evt == 3 : #cmdRun
########################### from here the problem starts
while 1:
input =Textbox1.val
if input.__contains__('.'):
Textbox1.val=''
Textbox2.val=input
#################### and here is the end of it
Blender.Redraw()
Register(draw_gui, event, bevent)
This is very old Blender (pre Blender 2.5), and back then it was practically impossible to do that. With current Blender (since 2.5 series, currently in 2.67 as of this writing) you could solve this with a model operator that triggers also on Python time events. Not so long ago I answered to another SO question here: https://stackoverflow.com/a/16744008/2419030 . It gives a simple structure for such a modal operator in current Blender that also listens on time events. It also has a link to a simple Conways Game of Life implementation running as modal operator.
In your case you'd be checking the value of an input box (you can create your own panels that seamlessly integrate in the rest of blender) and updating the other parts you want to react on it. In the example file the modal handler does one step of the simulation. You'll notice that the entire interface stays responsive.
Specifically you'd be doing the checks in the model() handler under the 'TIMER' if-block.
To create panels (and other forms of scripts) open up the Blender text editor and check the Templates menu entry. You'll find a huge amount of good stuff.

Categories