Python Auto Click bot not working and I cant figure out why - python-3.x

I made a python 'aimbot' type program that looks for targets in the aim trainer and clicks on them. The problem is it clicks but not on the target and I'm pretty sure I did everything right. Here's the program:
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
time.sleep(2)
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
while keyboard.is_pressed('q')== False:
pic = pyautogui.screenshot(region=(0,0,1080,1920))
width, height = pic.size
for x in range(0,width,5):
for y in range(0,height,5):
r,g,b = pic.getpixel((x,y))
if g == 154:
click(x,y)
time.sleep(1)
break

Related

Can't scroll through a div more than once | Selenium | Python

When I run this, it only manages to scroll down once, and it throws a "Message: element not interactable" error. (it's supposed to scroll twice). When I tried to run it in a loop (made a try and except to ignore the error), and scrolled around with it manually, it would keep pushing me back up to a specific position. But that's strange, because I'm using arrow keys here, not a move to element:
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
I've tried: giving everything more time to load with sleep, hovering over the element and clicking it to make it interactable, using other methods to scroll such as this one and others like it: driver.execute_script("window.scrollTo(0, Y)")
I'm very lost at this point, don't know what to do
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from datetime import date
from datetime import datetime
from time import sleep
from random import *
import random, json, selenium, os.path, os
driver = webdriver.Chrome('/Users/apple/Downloads/chromedriver')
driver.maximize_window()
driver.get('https://instagram.com')
sleep(7)
username_form = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[1]/div/label/input')
username_form.clear()
username_form.send_keys('ENTER INSTA USER HERE')
password_form = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[2]/div/label/input')
password_form.clear()
password_form.send_keys('ENTER INSTA PASS HERE')
button_click = driver.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[3]/button')
try:
button_click.click()
except:
driver.execute_script("arguments[0].click();", button_click)
sleep(4)
driver.get('https://instagram.com/p/CQ_sfAeFl5s/')
sleep(4)
like_meter = driver.find_element_by_class_name('zV_Nj')
like_meter.click()
sleep(1)
try:
scroll_zone = driver.find_element_by_xpath('/html/body/div[5]/div/div/div[2]/div/div')
except:
scroll_zone = driver.find_element_by_xpath('/html/body/div[4]/div/div/div[2]/div/div')
scroll_zone.click()
sleep(0.5)
hover = ActionChains(driver).move_to_element(scroll_zone)
hover.perform()
sleep(0.5)
scroll_zone.send_keys(Keys.ARROW_DOWN)
scroll_zone.send_keys(Keys.ARROW_DOWN)
If you want to scroll that list of persons liked that page you can do this:
like_meter = driver.find_element_by_class_name('zV_Nj')
like_meter.click()
sleep(1)
elem = driver.find_element_by_css_selector("div[role='dialog'] div[style*='padding']")
for n in range(10):
driver.execute_script("arguments[0].scrollDown += 20", elem)
The range of 10 and 20 pixels scrolling can be changed according to your needs

PySide2 updating a graph

I have been knocking my head against the wall on the following issue for quite some times now and need some fresh pair of eyes to help me out.
In Qt Designer I created a tab with a QComboBox (to select a feature), a QPushButton (to instruct the plotting of the feature) and a QWidget (plot area, called mywidget). The whole code is largely inspired from various codes found on SO.
In main.py I connected the QPushButton to the following function (defined within my QtApp class):
def launchGraph(self):
df1 = ... #data from a data source
self.mywidget.figure = Figure()
self.mywidget.canvas = FigureCanvas(self.mywidget.figure)
self.mywidget.toolbar = NavigationToolbar(self.mywidget.canvas, self)
self.mywidget.graphLayout = QtWidgets.QVBoxLayout()
self.mywidget.graphLayout.addWidget(self.mywidget.canvas)
self.mywidget.graphLayout.addWidget(self.mywidget.toolbar)
self.mywidget.setLayout(self.mywidget.graphLayout)
ax1f1 = self.mywidget.figure.add_subplot(111)
ax1f1.clear()
ax1f1.xaxis.set_major_formatter(mdates.DateFormatter('%b%-y'))
ax1f1.plot(df1['x'], df1['y'], linewidth=1, color='blue')
ax1f1.set(title='My Little Graph')
self.mywidget.canvas.draw()
The issue is that when I launched my window, select a feature and click the button, the correct graph is being shown. If I changed the feature and click the plot button, nothing happens. I did print the feature of the combobox and it prints the correct up-to-date value from the combobox however the graph is not replaced/updated. I also added a test-variable isgraph and used self.mywidget.figure.clear() but no success neither. canvas.repaint() doesn't update the graph neither. It feels like I need to use a test-variable to check whether a graph is there or not and if yes then I need to clen up the content of mywidget. But that seems overcomplicated for this issue (?)
For info I import the following:
from gui import main
from PySide2 import QtWidgets, QtCore, QtGui
from matplotlib.figure import Figure
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
from matplotlib.backends.backend_qt5agg import (FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
Edit:
Here is the minimal/adapted full code:
from gui import main
from PySide2 import QtWidgets, QtCore, QtGui
from matplotlib.figure import Figure
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
from matplotlib.backends.backend_qt5agg import (FigureCanvasQTAgg as
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
class MyQtApp(main.Ui_MainWindow, QtWidgets.QMainWindow):
def __init__(self):
super(MyQtApp, self).__init__()
self.setupUi(self)
self.graphBtn.clicked.connect(self.launchGraph)
self.show()
def launchGraph(self):
if self.mycb.currrentText() == 'feature1':
df1 = ... #data from a data source
else: (#== feature2)
df1 = ... #some other data
self.mywidget.figure = Figure()
self.mywidget.canvas = FigureCanvas(self.mywidget.figure)
self.mywidget.toolbar =
NavigationToolbar(self.mywidget.canvas, self)
self.mywidget.graphLayout = QtWidgets.QVBoxLayout()
self.mywidget.graphLayout.addWidget(self.mywidget.canvas)
self.mywidget.graphLayout.addWidget(self.mywidget.toolbar)
self.mywidget.setLayout(self.mywidget.graphLayout)
ax = self.mywidget.figure.add_subplot(111)
ax.clear()
ax.plot(df1['x'], df1['y'])
self.mywidget.canvas.draw()
In Qt Designer (file main.ui comnverted into. main.py), I placed:
- one combobox, called mycb and having 2 values: [feature1, feature2]
- one push button, called graphBtn
- a simple and empty QWidget called mywidget
The problem is most likely, that when you run the launchGraph after the initial run, the function creates another ax1f1 underneath the initial one. Therefore the initial one keeps on showing and no errors are displayed.
In this particular case, you want to keep working with the initial ax1f1 instead of re-declaring another one.
Something like this could fix the problem:
def launchGraph(self):
if self.mycb.currrentText() == 'feature1':
df1 = ['some_data'] #data from a data source
else: (#== feature2)
df1 = ['some_other_data'] #some other data
self.mywidget.figure = Figure()
self.mywidget.canvas = FigureCanvas(self.mywidget.figure)
self.mywidget.toolbar = NavigationToolbar(self.mywidget.canvas, self)
self.mywidget.graphLayout = QtWidgets.QVBoxLayout()
self.mywidget.graphLayout.addWidget(self.mywidget.canvas)
self.mywidget.graphLayout.addWidget(self.mywidget.toolbar)
self.mywidget.setLayout(self.mywidget.graphLayout)
try:
self.ax1f1.clear()
except:
self.a1f1 = self.mywidget.figure.add_subplot(111)
self.ax1f1.clear()
self.ax1f1.xaxis.set_major_formatter(mdates.DateFormatter('%b%-y'))
self.ax1f1.plot(df1['x'], df1['y'], linewidth=1, color='blue')
self.ax1f1.set(title='My Little Graph')
self.mywidget.canvas.draw()

How can I get the individual points and their attributes from a scatterplot in pyqtgraph?

I was able to create a ScatterPlotItem in pyqtgraph without a hitch by promoting a Graphics View widget to a PlotWidget in Qt Designer. I plotted some random data on it and now I want to access the individual points I click on. The docs say that one can connect the sigClicked(self, points) signal, which, in theory, should return the points under the cursor. But that does not seem to be the case, because when I click on a point I get the same object regardless of which point I clicked. I suspect that this signal returns the entire ScatterPlotItem and not any specific point.
Here is my code so far:
import sys, time
from timeit import default_timer as timer
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QUrl, QEvent
from PyQt5.QtWidgets import *
from PyQt5 import QtMultimedia
from PyQt5.uic import loadUi
import pyqtgraph as pg
import numpy as np
class ScatterExample(QMainWindow):
def __init__(self):
# Main Loop
super(ScatterExample, self).__init__()
loadUi('<path/to/ui file>.ui', self)
self.setWindowTitle('ScatterExample')
self.scatter = pg.ScatterPlotItem(pxMode=False, pen=pg.mkPen(width=1, color='g'), symbol='t', size=1)
self.scatter.sigClicked.connect(self.onPointsClicked)
self.Scatter_Plot_View.addItem(self.scatter) # Scatter_Plot_View is the Graphics View I promoted to PlotWidget
n = 5
print('Number of points: ' + str(n))
data = np.random.normal(size=(2, n))
pos = [{'pos': data[:, i]} for i in range(n)]
now = pg.ptime.time()
self.scatter.setData(pos)
print(self.scatter.data)
def onPointsClicked(self, points):
print('Ain\'t getting individual points ', points)
points.setPen('b', width=2) # this turns EVERY point blue, not just the one clicked.
The above print statement prints:
Ain't getting individual points <pyqtgraph.graphicsItems.ScatterPlotItem.ScatterPlotItem object at 0x000001C36577F948>
How can I get the points I click on and their corresponding attributes, such as x and y coordinates?
As eyllansec was kind enough to suggest, I changed my def onPointsClicked(self, points): to def onPointsClicked(self, obj, points): and now pyqtgraph works a expected.

How would I constantly update a variable within a script/program?

I am attempting to make a thermostat of sorts. To do this, I am using a Pi3 with a DHT22 Temperature sensor, and Python3.
What I need is for the temperature to be polled and the corresponding variable to update on its own.
Attempting to do so with any sort of While True: statements results in the gui I'm testing with, not opening.
I'm lost (And yes, this code is hacked together from others. LOL)
#! python3
import time
import RPi.GPIO as GPIO
import string
import tkinter
import tkinter.ttk
import Adafruit_DHT
from tkinter import messagebox
from tkinter import *
root = Tk()
root.title('PiTEST')
root.configure(background='black')
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sensor = Adafruit_DHT.DHT22
pin = 4
def PRINTTEST():
print(temperature, humidity)
TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")
B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
temperature = temperature * 9/5.0 + 32
root.mainloop()
GPIO.cleanup()
Here is a code example without your GPIO things:
#! python3
import time
import string
import tkinter
import random
from tkinter import messagebox
from tkinter import *
root = Tk()
root.title('PiTEST')
root.configure(background='black')
def PRINTTEST():
temperature = random.randint(0,100)
humidity = random.randint(0,100)
print(temperature, humidity)
root.after(1000, PRINTTEST)
TESTTEXT = Label(root,text="TESTING",fg="white",bg="black",font='Consolas 20 bold')
TESTTEXT.grid(row=1,column=1,sticky="W,S,E")
B1 = tkinter.Button(root,bd=5,text="TEST",bg="gray",fg="white",command=PRINTTEST,height=4,width=20)
B1.grid(row=2,column=1,sticky="N,S,E,W",padx=8,pady=8)
root.mainloop()
This will print 2 random integers every second in your terminal.

Not able to click 3d objects and move them

I want to click on the loaded models and move them around. I used the code from chess sample examples and panda 3d tutorial without any success. Can someone figure out whats wrong with the code.
Thanks
from math import pi, sin, cos
import sys
from direct.showbase.ShowBase import ShowBase
import direct.directbase.DirectStart
from direct.task import Task
from panda3d.core import TextNode
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from panda3d.core import Point3, Vec3, Vec4, BitMask32
from direct.showbase.DirectObject import DirectObject
from panda3d.core import AmbientLight, DirectionalLight, LightAttrib
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape', sys.exit)
#base.disableMouse()
# load the box model
self.box = self.loader.loadModel("models/xbox")
self.box.reparentTo(camera)
self.box.setScale(2.0, 2.0, 2.0)
self.box.setPos(8, 50, 0)
self.keyMap = {
"w" :False ,
"s" :False,
"a": False,
"d": False,
"mouse1": False,
"mouse3": False,
}
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
self.box.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP, self.pq)
self.mouseTask = taskMgr.add(self.mouseTask, 'mouseTask')
self.accept("mouse1", self.setKey, ["mouse1", True])
def mouseTask(self,task):
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.picker.getEntry(0).getIntoNodePath()
def setKey(self,key,value):
self.keyMap[key] = value
app = MyApp()
app.run()
I was just trying to do the same thing, when I found your question.
Thanks for your code, it help me to start!
I've manage to get it working :)
Just a remark: you use a task, with no return, this make the task run once.
You should have used: return task.cont
Anyway, here my working code for panda3d devel (1.8.0+):
import sys
from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import *
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape',sys.exit)
#base.disableMouse()
# load the box model
box = self.loader.loadModel("models/box")
box.reparentTo(render)
box.setScale(2.0, 2.0, 2.0)
box.setPos(8, 50, 0)
panda = base.loader.loadModel("models/panda")
panda.reparentTo(render)
panda.setPos(0, 10, 0)
panda.setScale(0.1, 0.1, 0.1)
cNodePanda = panda.attachNewNode(CollisionNode('cnode_panda'))
cNodePanda.node().addSolid(CollisionSphere(0,0,5,5))
cNodePanda.show()
# CollisionTraverser and a Collision Handler is set up
self.picker = CollisionTraverser()
self.picker.showCollisions(render)
self.pq = CollisionHandlerQueue()
self.pickerNode = CollisionNode('mouseRay')
self.pickerNP = camera.attachNewNode(self.pickerNode)
self.pickerNode.setFromCollideMask(BitMask32.bit(1))
box.setCollideMask(BitMask32.bit(1))
panda.setCollideMask(BitMask32.bit(1))
self.pickerRay = CollisionRay()
self.pickerNode.addSolid(self.pickerRay)
self.picker.addCollider(self.pickerNP,self.pq)
self.accept("mouse1",self.mouseClick)
def mouseClick(self):
print('mouse click')
# check if we have access to the mouse
if base.mouseWatcherNode.hasMouse():
# get the mouse position
mpos = base.mouseWatcherNode.getMouse()
# set the position of the ray based on the mouse position
self.pickerRay.setFromLens(base.camNode,mpos.getX(),mpos.getY())
self.picker.traverse(render)
# if we have hit something sort the hits so that the closest is first and highlight the node
if self.pq.getNumEntries() > 0:
self.pq.sortEntries()
pickedObj = self.pq.getEntry(0).getIntoNodePath()
print('click on ' + pickedObj.getName())
app = MyApp()
app.run()

Resources