|
You last visited: Today at 14:01
Advertisement
WARZONE AFK/DERANK BOT SRC
Discussion on WARZONE AFK/DERANK BOT SRC within the Call of Duty Hacks, Bots, Cheats & Exploits forum part of the Call of Duty category.
08/17/2024, 00:59
|
#1
|
elite*gold: 0
Join Date: Sep 2020
Posts: 6
Received Thanks: 6
|
WARZONE AFK/DERANK BOT SRC
100% python, doesnt touch the game.
launch game unbind the H key from auto run in game.
run main.py from console.
start resurgance/plunder match
once in the loading screen for the match
H+4 keys pressed together toggles the afk program on
Z+Y keys pressed together toggles the afk program off
instructions are on screen
make sure you are in the cod window before walking away.
it uses ctypes library to move around at "random" and in the background
it loops screenshots of the part of the screen that the play again button is located,
when you die it pops up, it gets clicked, it verifies the button is gone, and then clicks yes,
if it finds buttons, it stops the movement loops and recycles the garbage data/memory and starts the loop for searching for buttons again.
if for some reason it cant find the buttons, it will just manually click their location as a back up.
this throws you into que for a new match and loops endlessly, or until it cant find a button 5-10 games down the road.
if it doesnt work for you in resurgance, i suggest playing plunder as it auto connects at the end regardless.
replacing the png images of the buttons with your own screenshots, or just editing the manual coordinates for the clicks in the code to your resolution if it doesnt work, or if you are using a different resolution.
it runs long enough to get you into some absolute shitter lobbies and lowers your KD quite a bit. it helps curve the manual reports as well.
its not 100% polished, some paste and the keyinput.py file i stole from the internet, if you want to add to it, or make it less clunky feel free.
main.py
Code:
import sys
import ctypes
import time
import win32gui
import win32process
import threading
import psutil
import gc
import numpy as np
import cv2
import pyautogui
from PIL import ImageGrab
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from pynput import keyboard
import random
import keyinput # Import keyinput.py
# The target process name for "Call of Duty® HQ"
target_process_name = "cod.exe"
target_pid = -1 # This will be updated dynamically
window_found = False
# Movement control flag
movement_enabled = False
detection_thread_active = False # Flag to prevent multiple detection threads
# Set up the interval for checking screenshots
check_interval = 1.5 # seconds for faster button detection
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Function to load the templates
def load_templates():
global template_play_again, template_play_again_hovered, template_yes
global template_play_again_w, template_play_again_h
global template_play_again_hovered_w, template_play_again_hovered_h
global template_yes_w, template_yes_h
template_play_again = cv2.imread('play_again_template.png', cv2.IMREAD_GRAYSCALE)
template_play_again_hovered = cv2.imread('playagainhovered.png', cv2.IMREAD_GRAYSCALE)
template_yes = cv2.imread('yes.png', cv2.IMREAD_GRAYSCALE)
template_play_again_w, template_play_again_h = template_play_again.shape[::-1]
template_play_again_hovered_w, template_play_again_hovered_h = template_play_again_hovered.shape[::-1]
template_yes_w, template_yes_h = template_yes.shape[::-1]
# Load the templates initially
load_templates()
# Function to perform random movements using WASD keys and press F key
def perform_random_movement():
global movement_enabled
while movement_enabled:
# Randomly choose a key: W (0x11), A (0x1E), S (0x1F), D (0x20)
key_to_press = random.choice([keyinput.W, keyinput.A, keyinput.S, keyinput.D])
# Hold the key for a random duration between 0.2 and 1 second
hold_duration = random.uniform(0.2, 1.0)
keyinput.holdKey(key_to_press, hold_duration)
# Wait for a random duration between 1 and 3 seconds before the next move
time.sleep(random.uniform(1, 3))
# Randomly press the F key every 5 seconds
keyinput.pressKey(0x21) # F key (hex code for 'F' is 0x21)
keyinput.releaseKey(0x21)
print("Pressed F key")
time.sleep(5) # Wait for 5 seconds
# Find the PID of the process by its name
def find_pid_by_name(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
# Find the window associated with the specific PID
def get_window_by_pid(hwnd, extra):
global window_x, window_y, window_width, window_height, window_found, target_pid
_, pid = win32process.GetWindowThreadProcessId(hwnd)
window_title = win32gui.GetWindowText(hwnd)
# Check if the PID matches
if pid == target_pid:
window_found = True
rect = win32gui.GetClientRect(hwnd)
window_pos = win32gui.ClientToScreen(hwnd, (0, 0))
window_x = window_pos[0]
window_y = window_pos[1]
window_width = rect[2]
window_height = rect[3]
# Watchdog function to ensure the process is still running and the window is found
def process_watchdog():
global window_found, target_pid
while True:
time.sleep(60)
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
continue
window_found = False
win32gui.EnumWindows(get_window_by_pid, None)
if not window_found:
print("No window found for the target process")
# Function to click at the specified location
def click(x, y):
time.sleep(0.1) # Add a short delay before the click
pyautogui.click(x, y, duration=0.2)
time.sleep(0.1) # Add a short delay after the click
# Function to stop movement
def stop_movement():
global movement_enabled, detection_thread_active
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
print("Movement stopped")
# Function to resume movement
def resume_movement():
global movement_enabled, detection_thread_active
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
detection_thread_active = False # Reset detection thread state
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Start the detection process again
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
print("Looking for buttons")
# Function to detect and click the "YES" button after "PLAY AGAIN"
def detect_and_click_yes():
global detection_thread_active
print("Looking for the YES button...")
time.sleep(3) # Give some time for the YES screen to appear
max_attempts = 3 # Limit the number of attempts to find the YES button
for attempt in range(max_attempts):
# Capture the full screen (for YES button detection)
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
# Convert the screenshot to grayscale to reduce memory usage
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "YES" button
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
button_x = max_loc[0] + template_yes_w // 2
button_y = max_loc[1] + template_yes_h // 2
for _ in range(5): # Click the "YES" button 5 times at human speed
click(button_x, button_y)
time.sleep(random.uniform(0.3, 0.7)) # Add random delay between clicks
print(f"Clicked YES at position: ({button_x}, {button_y})")
# Recheck to see if the button is still there
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "YES" button is not found, confirm success
print("YES button successfully clicked and no longer detected.")
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
return
else:
print("YES button still detected, retrying...")
print(f"Attempt {attempt + 1} to click YES button failed.")
time.sleep(check_interval) # Wait for a while before retrying
# If all attempts fail, click predefined coordinates as a backup
print(f"Clicking predefined coordinates for YES button: {yes_button_coords}")
click(yes_button_coords[0], yes_button_coords[1])
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
# Function to detect and click the "PLAY AGAIN" button in the right section
def detect_and_click_play_again():
global detection_thread_active
if detection_thread_active:
return # Exit if a detection thread is already running
detection_thread_active = True # Mark the detection thread as active
try:
while movement_enabled:
# Capture the right section of the screen
screen_width, screen_height = ImageGrab.grab().size
right_section = (screen_width * 2 // 3, 0, screen_width, screen_height)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "Play Again" button
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
stop_movement()
button_x = max_loc[0] + template_play_again_w // 2 + screen_width * 2 // 3 # Adjust x for the right section
button_y = max_loc[1] + template_play_again_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "Play Again" button is no longer found, move on
print("PLAY AGAIN button no longer detected.")
detect_and_click_yes() # Proceed to the "YES" button
return
else:
print("PLAY AGAIN button still detected, clicking again...")
click(button_x, button_y) # Click the button again if still detected
# If not found, try the hovered version
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, max_loc_hovered = cv2.minMaxLoc(result_hovered)
if max_val_hovered >= 0.8:
stop_movement()
button_x = max_loc_hovered[0] + template_play_again_hovered_w // 2 + screen_width * 2 // 3
button_y = max_loc_hovered[1] + template_play_again_hovered_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN (hovered) at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, _ = cv2.minMaxLoc(result_hovered)
if max_val_hovered < 0.8:
print("PLAY AGAIN (hovered) button no longer detected.")
detect_and_click_yes()
return
else:
print("PLAY AGAIN (hovered) button still detected, clicking again...")
click(button_x, button_y)
# Wait for the check interval before the next screenshot if neither button is found
time.sleep(check_interval)
finally:
detection_thread_active = False # Ensure the flag is reset when the thread exits
# Create a PyQt5 application and overlay window with instructions
class OverlayWindow(QWidget):
def __init__(self):
super().__init__()
# Set window properties for transparency and ignoring mouse events
self.setWindowTitle('Overlay')
screen_resolution = QApplication.desktop().screenGeometry()
screen_width, screen_height = screen_resolution.width(), screen_resolution.height()
overlay_width, overlay_height = 300, 100 # Set the overlay size
self.setGeometry((screen_width - overlay_width) // 2, screen_height - overlay_height - 50, overlay_width, overlay_height)
self.setWindowFlags(Qt.Tool | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowDoesNotAcceptFocus)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
# Create UI components
self.layout = QVBoxLayout()
self.instructions_label = QLabel("Press 'H + 4' to Start\nPress 'Z + Y' to Stop", self)
self.instructions_label.setStyleSheet("color: white; font-size: 16px;")
self.status_label = QLabel("Status: Stopped", self)
self.status_label.setStyleSheet("color: red; font-size: 16px;")
self.layout.addWidget(self.instructions_label)
self.layout.addWidget(self.status_label)
self.setLayout(self.layout)
def update_status(self, running):
if running:
self.status_label.setText("Status: Running")
self.status_label.setStyleSheet("color: green; font-size: 16px;")
else:
self.status_label.setText("Status: Stopped")
self.status_label.setStyleSheet("color: red; font-size: 16px;")
# Set ourselves as DPI aware, or else we won't get proper pixel coordinates if scaling is not 100%
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
# Start the PyQt5 application
app = QApplication(sys.argv)
overlay = OverlayWindow()
# Find the PID of the process before looking for windows
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
sys.exit(1)
# Find the window using the PID
win32gui.EnumWindows(get_window_by_pid, None)
# If the window hasn't been found, exit
if not window_found:
print("No Call of Duty® HQ window found")
sys.exit(1)
# Show the overlay window
overlay.show()
# Start the watchdog thread
watchdog_thread = threading.Thread(target=process_watchdog)
watchdog_thread.start()
# Track key press states
pressed_keys = set()
# Function to start movement
def start_movement():
global movement_enabled
if not movement_enabled: # Prevent restarting movement if already enabled
movement_enabled = True
print("Movement started")
overlay.update_status(True)
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
# Function to stop movement
# Function to stop movement and update overlay status
def stop_movement():
global movement_enabled, detection_thread_active
if movement_enabled: # Check if movement is actually enabled before stopping
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
overlay.update_status(False) # Update overlay to show stopped status
print("Movement stopped")
# Function to resume movement and update overlay status
def resume_movement():
global movement_enabled
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Set up global hotkeys using Pynput to start and stop movement
def on_press(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.add(key.char)
if 'h' in pressed_keys and '4' in pressed_keys:
start_movement()
elif 'z' in pressed_keys and 'y' in pressed_keys:
stop_movement()
except AttributeError:
pass
def on_release(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.remove(key.char)
except KeyError:
pass
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
# Main loop for the overlay
def main_loop():
while True:
if not window_found:
time.sleep(5)
continue
time.sleep(1.0) # Placeholder for movement logic
# Start the main loop in a separate thread so it doesn't block the GUI
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()
sys.exit(app.exec_())
keyinput.py
Code:
import ctypes, win32api, win32con, time
SendInput = ctypes.windll.user32.SendInput
ESC = 0x01
W = 0x11
A = 0x1E
S = 0x1F
D = 0x20
SPACE = 0x39
UP = 0xC8
DOWN = 0xD0
LEFT = 0xCB
RIGHT = 0xCD
ENTER = 0x1C
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
#thank you to whoever it is i stole this from xD
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actual Functions
def pressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def releaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0,
ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def holdKey(hexKeyCode, duration):
pressKey(hexKeyCode)
stop_time = time.time() + duration
while time.time() < stop_time:
time.sleep(0.01)
pressKey(hexKeyCode)
releaseKey(hexKeyCode)
def click(x, y, click_delay = 0.15):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
time.sleep(click_delay)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def move(x, y):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
reqirements.txt
Code:
PyQt5==5.15.4
opencv-python==4.5.5.64
Pillow==8.4.0
numpy==1.21.4
psutil==5.8.0
pynput==1.7.3
pyautogui==0.9.53
pywin32==302
play_again_template.png
playagainhovered.png
yes.png
yeshovered.png
make sure the names on the images match in the directory.
you should probably take your own screenshots, of these buttons in game and use those.
you can also just change the coordinates of the buttons from 1440p to change your resolution
Code:
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Predefined coordinates for the "PLAY AGAIN" button (example)
play_again_coords = (1500, 900)
# In the fallback scenario for "Play Again"
click(play_again_coords[0], play_again_coords[1])
|
|
|
08/20/2024, 18:38
|
#2
|
elite*gold: 1248
Join Date: Apr 2015
Posts: 123
Received Thanks: 14
|
How long does this last? Because I'd do the controller trick, and seems like after 4 games, I have to restart search. I know this is more than the controller, but just curious if I could run this all weekend, if I'd be good.
|
|
|
08/21/2024, 12:00
|
#3
|
elite*gold: 0
Join Date: Sep 2020
Posts: 6
Received Thanks: 6
|
720p (HD)
YES Button: (630, 480)
PLAY AGAIN Button: (1280, 720)
1080p (Full HD)
YES Button: (900, 640)
PLAY AGAIN Button: (1920, 1080)
1440p (Quad HD)
YES Button: (900, 800)
PLAY AGAIN Button: (2150, 1220)
4K (Ultra HD)
YES Button: (1200, 1067)
PLAY AGAIN Button: (2880, 1620)
5K (5120x2880)
YES Button: (1500, 1333)
PLAY AGAIN Button: (3840, 2160)
the coordiantes for all the different resolutions.
Code:
import sys
import time
import threading
import psutil
import subprocess
import random
import customtkinter as ctk # Use customtkinter for modern GUI
from tkinter import filedialog, Text
from tkinter.scrolledtext import ScrolledText
from pynput import keyboard
import pyautogui
import keyinput # Import keyinput.py
# Global variables
movement_enabled = False
manual_click_interval = 17 # seconds
operation_in_progress = False # Flag to prevent actions during critical operations
target_process_name = "cod.exe"
target_pid = -1
pressed_keys = set() # Initialize pressed_keys here
watchdog_thread = None
main_loop_thread = None
# Predefined coordinates for buttons
yes_button_coords = (900, 800)
play_again_button_coords = (2150, 1220)
# Function to find PID by process name
def find_pid_by_name(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
# Function to check if the game is running
def is_game_running():
global target_pid
target_pid = find_pid_by_name(target_process_name)
return target_pid is not None
# Function to stop all operations and prepare for game relaunch
def stop_all_operations():
global movement_enabled
stop_movement()
log_to_console("Game closed. Stopping operations and preparing to relaunch the game.")
# Function to relaunch the game using the provided path
def relaunch_game():
try:
subprocess.Popen([cod_exe_path.get()])
log_to_console("Game relaunched successfully.")
except Exception as e:
log_to_console(f"Failed to launch the game: {e}")
sys.exit(1)
# Function to perform actions after the game has been launched
def perform_post_launch_actions():
global operation_in_progress
operation_in_progress = True # Prevent other operations during this sequence
log_to_console("Setting operation_in_progress to True (starting post-launch actions).")
log_to_console("Performing post-launch actions...")
# Start a 90-second countdown with a timer displayed in the console
for remaining in range(90, 0, -1):
log_to_console(f"Waiting {remaining} seconds for the game to load completely...")
time.sleep(1)
keyinput.pressKey(keyinput.ESC)
keyinput.releaseKey(keyinput.ESC)
log_to_console("navigating menus")
time.sleep(2)
keyinput.pressKey(keyinput.S)
keyinput.releaseKey(keyinput.S)
log_to_console("navigating menus")
time.sleep(1)
keyinput.pressKey(keyinput.S)
keyinput.releaseKey(keyinput.S)
log_to_console("navigating menus")
time.sleep(1)
keyinput.pressKey(keyinput.S)
keyinput.releaseKey(keyinput.S)
log_to_console("navigating menus")
time.sleep(1)
keyinput.pressKey(keyinput.D)
keyinput.releaseKey(keyinput.D)
log_to_console("navigating menus")
time.sleep(1)
keyinput.pressKey(keyinput.SPACE)
keyinput.releaseKey(keyinput.SPACE)
log_to_console("navigating menus")
time.sleep(10)
keyinput.pressKey(keyinput.SPACE)
keyinput.releaseKey(keyinput.SPACE)
log_to_console("navigating menus")
time.sleep(10)
keyinput.pressKey(keyinput.SPACE)
keyinput.releaseKey(keyinput.SPACE)
log_to_console("navigating menus")
time.sleep(1)
keyinput.pressKey(keyinput.SPACE)
keyinput.releaseKey(keyinput.SPACE)
log_to_console("SEARCHING FOR MATCH!!!! :D")
# Start a 95-second countdown between searching for a match
for remaining in range(95, 0, -1):
log_to_console(f"Waiting {remaining} waiting to restart movement...")
time.sleep(1)
log_to_console("Post-launch actions completed. Resuming normal operations.")
operation_in_progress = False # Release flag after operations are complete
log_to_console("Setting operation_in_progress to False (post-launch actions completed).")
resume_movement()
# Watchdog function to monitor the game process and relaunch if needed
def process_watchdog():
while movement_enabled:
if not is_game_running():
stop_all_operations()
relaunch_game()
time.sleep(30)
perform_post_launch_actions()
time.sleep(5)
# Function to perform random movement
def perform_random_movement():
global movement_enabled
while movement_enabled:
if not operation_in_progress: # Prevent movement during critical operations
key_to_press = random.choice([keyinput.W, keyinput.A, keyinput.S, keyinput.D])
if key_to_press == keyinput.W:
keyinput.pressKey(0x2A) # Shift key
hold_duration = random.uniform(1.2, 5.0)
keyinput.holdKey(key_to_press, hold_duration)
keyinput.releaseKey(0x2A) # Release Shift key
else:
hold_duration = random.uniform(0.2, 2.0)
keyinput.holdKey(key_to_press, hold_duration)
time.sleep(random.uniform(0.1, 0.3))
keyinput.pressKey(0x21) # F key
keyinput.releaseKey(0x21)
log_to_console("Randomizing Movement :D")
time.sleep(5)
# Function to manually click buttons
def manual_click_buttons():
global movement_enabled
if not operation_in_progress: # Prevent button clicking during critical operations
log_to_console("Performing search for manual clicks on buttons...")
# Double-click "PLAY AGAIN" button
for _ in range(2):
click(play_again_button_coords[0], play_again_button_coords[1])
log_to_console(f"PEW PEW: {play_again_button_coords}")
time.sleep(0.5)
time.sleep(1.5)
# Triple-click "YES" button
for _ in range(3):
click(yes_button_coords[0], yes_button_coords[1])
log_to_console(f"still looking for buttons: {yes_button_coords}")
time.sleep(0.5)
# Function to click at the specified location
def click(x, y):
time.sleep(0.1)
pyautogui.click(x, y, duration=0.2)
time.sleep(0.1)
# Function to stop movement
def stop_movement():
global movement_enabled
movement_enabled = False
log_to_console("Movement stopped")
# Function to resume movement
def resume_movement():
global movement_enabled
if not movement_enabled:
movement_enabled = True
log_to_console("Movement resumed")
threading.Thread(target=perform_random_movement).start()
threading.Thread(target=manual_click_loop).start()
# Function to start the manual click loop
def manual_click_loop():
while movement_enabled:
if not operation_in_progress: # Prevent clicking during critical operations
manual_click_buttons()
time.sleep(manual_click_interval)
# Function to start movement
def start_movement():
global movement_enabled, watchdog_thread, main_loop_thread
if not movement_enabled:
movement_enabled = True
log_to_console("Movement started")
if watchdog_thread is None or not watchdog_thread.is_alive():
watchdog_thread = threading.Thread(target=process_watchdog)
watchdog_thread.start()
if main_loop_thread is None or not main_loop_thread.is_alive():
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()
threading.Thread(target=perform_random_movement).start()
threading.Thread(target=manual_click_loop).start()
# Set up global hotkeys using Pynput to start and stop movement
def on_press(key):
try:
if hasattr(key, 'char'):
pressed_keys.add(key.char)
if 'h' in pressed_keys and '4' in pressed_keys:
start_movement()
elif 'z' in pressed_keys and 'y' in pressed_keys:
stop_movement()
except AttributeError:
pass
def on_release(key):
try:
if hasattr(key, 'char'):
pressed_keys.remove(key.char)
except KeyError:
pass
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
# Main loop for the bot
def main_loop():
while movement_enabled:
time.sleep(1.0)
# Function to save coordinates from the GUI
def save_coordinates():
global yes_button_coords, play_again_button_coords
yes_button_coords = (int(yes_x_entry.get()), int(yes_y_entry.get()))
play_again_button_coords = (int(play_again_x_entry.get()), int(play_again_y_entry.get()))
log_to_console("Coordinates updated.")
# Function to select the cod.exe path from the GUI
def select_cod_exe():
path = filedialog.askopenfilename(filetypes=[("Executable Files", "*.exe")])
if path:
cod_exe_path.set(path)
log_to_console(f"Selected path: {path}")
# Function to log messages to the console within the GUI
def log_to_console(message):
console_text.config(state='normal')
console_text.insert('end', message + '\n')
console_text.config(state='disabled')
console_text.see('end') # Automatically scroll to the bottom
# Modern GUI setup using customtkinter
ctk.set_appearance_mode("dark") # Set dark mode for modern look
ctk.set_default_color_theme("blue") # Set theme color
root = ctk.CTk() # Create customtkinter window
root.title("H4ZY'S AFK BOT")
root.geometry("700x450") # Increase width to ensure space for fields
root.resizable(False, False) # Disable resizing
# UI Elements
cod_exe_path = ctk.StringVar()
ctk.CTkLabel(root, text="COD.exe Path:").grid(row=0, column=0, padx=10, pady=10)
ctk.CTkButton(root, text="Select", command=select_cod_exe).grid(row=0, column=1, padx=10, pady=10)
ctk.CTkLabel(root, text="Yes Button Coordinates (X, Y):").grid(row=1, column=0, padx=10, pady=10)
yes_x_entry = ctk.CTkEntry(root, width=100)
yes_y_entry = ctk.CTkEntry(root, width=100)
yes_x_entry.grid(row=1, column=1, padx=5)
yes_y_entry.grid(row=1, column=2, padx=5)
ctk.CTkLabel(root, text="Play Again Button Coordinates (X, Y):").grid(row=2, column=0, padx=10, pady=10)
play_again_x_entry = ctk.CTkEntry(root, width=100)
play_again_y_entry = ctk.CTkEntry(root, width=100)
play_again_x_entry.grid(row=2, column=1, padx=5)
play_again_y_entry.grid(row=2, column=2, padx=5)
ctk.CTkButton(root, text="Save Coordinates", command=save_coordinates).grid(row=3, column=0, padx=10, pady=10)
ctk.CTkButton(root, text="Start Game", command=relaunch_game).grid(row=3, column=1, padx=10, pady=10)
ctk.CTkButton(root, text="Start Bot", command=start_movement).grid(row=4, column=0, padx=10, pady=10)
ctk.CTkButton(root, text="Stop Bot", command=stop_movement).grid(row=4, column=1, padx=10, pady=10)
# Console for logging, match color with entry fields and make text white
console_text = ScrolledText(root, wrap='word', height=10, state='disabled', bg="#2d2d2d", fg="white")
console_text.grid(row=5, column=0, columnspan=3, padx=10, pady=10, sticky="we")
root.mainloop()
simplified no ai version. replace the main.py file with this.
|
|
|
08/22/2024, 18:53
|
#4
|
elite*gold: 0
Join Date: Oct 2023
Posts: 111
Received Thanks: 30
|
Quote:
Originally Posted by ouvs
How long does this last? Because I'd do the controller trick, and seems like after 4 games, I have to restart search. I know this is more than the controller, but just curious if I could run this all weekend, if I'd be good.
|
Questions are not allowed here.
Quote:
Originally Posted by jackgankem
its not 100% polished, some paste and the keyinput.py file i stole from the internet, if you want to add to it, or make it less clunky feel free.
|
Thanks for the share! I've been playing with Python lately, and I can see myself using part of this and improving it. If I do, I'll be sure to tag you and give credit where it's due.
|
|
|
08/22/2024, 19:29
|
#5
|
elite*gold: 1248
Join Date: Apr 2015
Posts: 123
Received Thanks: 14
|
Quote:
Originally Posted by susplayer32
Questions are not allowed here.
Thanks for the share! I've been playing with Python lately, and I can see myself using part of this and improving it. If I do, I'll be sure to tag you and give credit where it's due.
|
lol what? Okayyyy, this site has been getting more crazy by the day
|
|
|
11/29/2024, 18:00
|
#6
|
elite*gold: 0
Join Date: Feb 2022
Posts: 4
Received Thanks: 0
|
still working for bo6/warzone?
|
|
|
12/24/2024, 16:58
|
#7
|
elite*gold: 0
Join Date: Dec 2024
Posts: 56
Received Thanks: 3
|
nice thanks
|
|
|
04/30/2025, 06:52
|
#8
|
elite*gold: 0
Join Date: Jan 2021
Posts: 53
Received Thanks: 9
|
Question please
Quote:
Originally Posted by jackgankem
100% python, doesnt touch the game.
launch game unbind the H key from auto run in game.
run main.py from console.
start resurgance/plunder match
once in the loading screen for the match
H+4 keys pressed together toggles the afk program on
Z+Y keys pressed together toggles the afk program off
instructions are on screen
make sure you are in the cod window before walking away.
it uses ctypes library to move around at "random" and in the background
it loops screenshots of the part of the screen that the play again button is located,
when you die it pops up, it gets clicked, it verifies the button is gone, and then clicks yes,
if it finds buttons, it stops the movement loops and recycles the garbage data/memory and starts the loop for searching for buttons again.
if for some reason it cant find the buttons, it will just manually click their location as a back up.
this throws you into que for a new match and loops endlessly, or until it cant find a button 5-10 games down the road.
if it doesnt work for you in resurgance, i suggest playing plunder as it auto connects at the end regardless.
replacing the png images of the buttons with your own screenshots, or just editing the manual coordinates for the clicks in the code to your resolution if it doesnt work, or if you are using a different resolution.
it runs long enough to get you into some absolute shitter lobbies and lowers your KD quite a bit. it helps curve the manual reports as well.
its not 100% polished, some paste and the keyinput.py file i stole from the internet, if you want to add to it, or make it less clunky feel free.
main.py
Code:
import sys
import ctypes
import time
import win32gui
import win32process
import threading
import psutil
import gc
import numpy as np
import cv2
import pyautogui
from PIL import ImageGrab
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from pynput import keyboard
import random
import keyinput # Import keyinput.py
# The target process name for "Call of Duty® HQ"
target_process_name = "cod.exe"
target_pid = -1 # This will be updated dynamically
window_found = False
# Movement control flag
movement_enabled = False
detection_thread_active = False # Flag to prevent multiple detection threads
# Set up the interval for checking screenshots
check_interval = 1.5 # seconds for faster button detection
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Function to load the templates
def load_templates():
global template_play_again, template_play_again_hovered, template_yes
global template_play_again_w, template_play_again_h
global template_play_again_hovered_w, template_play_again_hovered_h
global template_yes_w, template_yes_h
template_play_again = cv2.imread('play_again_template.png', cv2.IMREAD_GRAYSCALE)
template_play_again_hovered = cv2.imread('playagainhovered.png', cv2.IMREAD_GRAYSCALE)
template_yes = cv2.imread('yes.png', cv2.IMREAD_GRAYSCALE)
template_play_again_w, template_play_again_h = template_play_again.shape[::-1]
template_play_again_hovered_w, template_play_again_hovered_h = template_play_again_hovered.shape[::-1]
template_yes_w, template_yes_h = template_yes.shape[::-1]
# Load the templates initially
load_templates()
# Function to perform random movements using WASD keys and press F key
def perform_random_movement():
global movement_enabled
while movement_enabled:
# Randomly choose a key: W (0x11), A (0x1E), S (0x1F), D (0x20)
key_to_press = random.choice([keyinput.W, keyinput.A, keyinput.S, keyinput.D])
# Hold the key for a random duration between 0.2 and 1 second
hold_duration = random.uniform(0.2, 1.0)
keyinput.holdKey(key_to_press, hold_duration)
# Wait for a random duration between 1 and 3 seconds before the next move
time.sleep(random.uniform(1, 3))
# Randomly press the F key every 5 seconds
keyinput.pressKey(0x21) # F key (hex code for 'F' is 0x21)
keyinput.releaseKey(0x21)
print("Pressed F key")
time.sleep(5) # Wait for 5 seconds
# Find the PID of the process by its name
def find_pid_by_name(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
# Find the window associated with the specific PID
def get_window_by_pid(hwnd, extra):
global window_x, window_y, window_width, window_height, window_found, target_pid
_, pid = win32process.GetWindowThreadProcessId(hwnd)
window_title = win32gui.GetWindowText(hwnd)
# Check if the PID matches
if pid == target_pid:
window_found = True
rect = win32gui.GetClientRect(hwnd)
window_pos = win32gui.ClientToScreen(hwnd, (0, 0))
window_x = window_pos[0]
window_y = window_pos[1]
window_width = rect[2]
window_height = rect[3]
# Watchdog function to ensure the process is still running and the window is found
def process_watchdog():
global window_found, target_pid
while True:
time.sleep(60)
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
continue
window_found = False
win32gui.EnumWindows(get_window_by_pid, None)
if not window_found:
print("No window found for the target process")
# Function to click at the specified location
def click(x, y):
time.sleep(0.1) # Add a short delay before the click
pyautogui.click(x, y, duration=0.2)
time.sleep(0.1) # Add a short delay after the click
# Function to stop movement
def stop_movement():
global movement_enabled, detection_thread_active
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
print("Movement stopped")
# Function to resume movement
def resume_movement():
global movement_enabled, detection_thread_active
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
detection_thread_active = False # Reset detection thread state
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Start the detection process again
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
print("Looking for buttons")
# Function to detect and click the "YES" button after "PLAY AGAIN"
def detect_and_click_yes():
global detection_thread_active
print("Looking for the YES button...")
time.sleep(3) # Give some time for the YES screen to appear
max_attempts = 3 # Limit the number of attempts to find the YES button
for attempt in range(max_attempts):
# Capture the full screen (for YES button detection)
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
# Convert the screenshot to grayscale to reduce memory usage
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "YES" button
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
button_x = max_loc[0] + template_yes_w // 2
button_y = max_loc[1] + template_yes_h // 2
for _ in range(5): # Click the "YES" button 5 times at human speed
click(button_x, button_y)
time.sleep(random.uniform(0.3, 0.7)) # Add random delay between clicks
print(f"Clicked YES at position: ({button_x}, {button_y})")
# Recheck to see if the button is still there
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "YES" button is not found, confirm success
print("YES button successfully clicked and no longer detected.")
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
return
else:
print("YES button still detected, retrying...")
print(f"Attempt {attempt + 1} to click YES button failed.")
time.sleep(check_interval) # Wait for a while before retrying
# If all attempts fail, click predefined coordinates as a backup
print(f"Clicking predefined coordinates for YES button: {yes_button_coords}")
click(yes_button_coords[0], yes_button_coords[1])
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
# Function to detect and click the "PLAY AGAIN" button in the right section
def detect_and_click_play_again():
global detection_thread_active
if detection_thread_active:
return # Exit if a detection thread is already running
detection_thread_active = True # Mark the detection thread as active
try:
while movement_enabled:
# Capture the right section of the screen
screen_width, screen_height = ImageGrab.grab().size
right_section = (screen_width * 2 // 3, 0, screen_width, screen_height)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "Play Again" button
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
stop_movement()
button_x = max_loc[0] + template_play_again_w // 2 + screen_width * 2 // 3 # Adjust x for the right section
button_y = max_loc[1] + template_play_again_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "Play Again" button is no longer found, move on
print("PLAY AGAIN button no longer detected.")
detect_and_click_yes() # Proceed to the "YES" button
return
else:
print("PLAY AGAIN button still detected, clicking again...")
click(button_x, button_y) # Click the button again if still detected
# If not found, try the hovered version
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, max_loc_hovered = cv2.minMaxLoc(result_hovered)
if max_val_hovered >= 0.8:
stop_movement()
button_x = max_loc_hovered[0] + template_play_again_hovered_w // 2 + screen_width * 2 // 3
button_y = max_loc_hovered[1] + template_play_again_hovered_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN (hovered) at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, _ = cv2.minMaxLoc(result_hovered)
if max_val_hovered < 0.8:
print("PLAY AGAIN (hovered) button no longer detected.")
detect_and_click_yes()
return
else:
print("PLAY AGAIN (hovered) button still detected, clicking again...")
click(button_x, button_y)
# Wait for the check interval before the next screenshot if neither button is found
time.sleep(check_interval)
finally:
detection_thread_active = False # Ensure the flag is reset when the thread exits
# Create a PyQt5 application and overlay window with instructions
class OverlayWindow(QWidget):
def __init__(self):
super().__init__()
# Set window properties for transparency and ignoring mouse events
self.setWindowTitle('Overlay')
screen_resolution = QApplication.desktop().screenGeometry()
screen_width, screen_height = screen_resolution.width(), screen_resolution.height()
overlay_width, overlay_height = 300, 100 # Set the overlay size
self.setGeometry((screen_width - overlay_width) // 2, screen_height - overlay_height - 50, overlay_width, overlay_height)
self.setWindowFlags(Qt.Tool | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowDoesNotAcceptFocus)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
# Create UI components
self.layout = QVBoxLayout()
self.instructions_label = QLabel("Press 'H + 4' to Start\nPress 'Z + Y' to Stop", self)
self.instructions_label.setStyleSheet("color: white; font-size: 16px;")
self.status_label = QLabel("Status: Stopped", self)
self.status_label.setStyleSheet("color: red; font-size: 16px;")
self.layout.addWidget(self.instructions_label)
self.layout.addWidget(self.status_label)
self.setLayout(self.layout)
def update_status(self, running):
if running:
self.status_label.setText("Status: Running")
self.status_label.setStyleSheet("color: green; font-size: 16px;")
else:
self.status_label.setText("Status: Stopped")
self.status_label.setStyleSheet("color: red; font-size: 16px;")
# Set ourselves as DPI aware, or else we won't get proper pixel coordinates if scaling is not 100%
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
# Start the PyQt5 application
app = QApplication(sys.argv)
overlay = OverlayWindow()
# Find the PID of the process before looking for windows
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
sys.exit(1)
# Find the window using the PID
win32gui.EnumWindows(get_window_by_pid, None)
# If the window hasn't been found, exit
if not window_found:
print("No Call of Duty® HQ window found")
sys.exit(1)
# Show the overlay window
overlay.show()
# Start the watchdog thread
watchdog_thread = threading.Thread(target=process_watchdog)
watchdog_thread.start()
# Track key press states
pressed_keys = set()
# Function to start movement
def start_movement():
global movement_enabled
if not movement_enabled: # Prevent restarting movement if already enabled
movement_enabled = True
print("Movement started")
overlay.update_status(True)
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
# Function to stop movement
# Function to stop movement and update overlay status
def stop_movement():
global movement_enabled, detection_thread_active
if movement_enabled: # Check if movement is actually enabled before stopping
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
overlay.update_status(False) # Update overlay to show stopped status
print("Movement stopped")
# Function to resume movement and update overlay status
def resume_movement():
global movement_enabled
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Set up global hotkeys using Pynput to start and stop movement
def on_press(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.add(key.char)
if 'h' in pressed_keys and '4' in pressed_keys:
start_movement()
elif 'z' in pressed_keys and 'y' in pressed_keys:
stop_movement()
except AttributeError:
pass
def on_release(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.remove(key.char)
except KeyError:
pass
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
# Main loop for the overlay
def main_loop():
while True:
if not window_found:
time.sleep(5)
continue
time.sleep(1.0) # Placeholder for movement logic
# Start the main loop in a separate thread so it doesn't block the GUI
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()
sys.exit(app.exec_())
keyinput.py
Code:
import ctypes, win32api, win32con, time
SendInput = ctypes.windll.user32.SendInput
ESC = 0x01
W = 0x11
A = 0x1E
S = 0x1F
D = 0x20
SPACE = 0x39
UP = 0xC8
DOWN = 0xD0
LEFT = 0xCB
RIGHT = 0xCD
ENTER = 0x1C
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
#thank you to whoever it is i stole this from xD
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actual Functions
def pressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def releaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0,
ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def holdKey(hexKeyCode, duration):
pressKey(hexKeyCode)
stop_time = time.time() + duration
while time.time() < stop_time:
time.sleep(0.01)
pressKey(hexKeyCode)
releaseKey(hexKeyCode)
def click(x, y, click_delay = 0.15):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
time.sleep(click_delay)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def move(x, y):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
reqirements.txt
Code:
PyQt5==5.15.4
opencv-python==4.5.5.64
Pillow==8.4.0
numpy==1.21.4
psutil==5.8.0
pynput==1.7.3
pyautogui==0.9.53
pywin32==302
play_again_template.png
playagainhovered.png
yes.png
yeshovered.png
make sure the names on the images match in the directory.
you should probably take your own screenshots, of these buttons in game and use those.
you can also just change the coordinates of the buttons from 1440p to change your resolution
Code:
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Predefined coordinates for the "PLAY AGAIN" button (example)
play_again_coords = (1500, 900)
# In the fallback scenario for "Play Again"
click(play_again_coords[0], play_again_coords[1])
|
Anyone get this to work in Warzone Battle Royale or Resurgence
|
|
|
05/01/2025, 14:15
|
#9
|
elite*gold: 0
Join Date: May 2020
Posts: 108
Received Thanks: 26
|
Quote:
Originally Posted by jackgankem
100% python, doesnt touch the game.
launch game unbind the H key from auto run in game.
run main.py from console.
start resurgance/plunder match
once in the loading screen for the match
H+4 keys pressed together toggles the afk program on
Z+Y keys pressed together toggles the afk program off
instructions are on screen
make sure you are in the cod window before walking away.
it uses ctypes library to move around at "random" and in the background
it loops screenshots of the part of the screen that the play again button is located,
when you die it pops up, it gets clicked, it verifies the button is gone, and then clicks yes,
if it finds buttons, it stops the movement loops and recycles the garbage data/memory and starts the loop for searching for buttons again.
if for some reason it cant find the buttons, it will just manually click their location as a back up.
this throws you into que for a new match and loops endlessly, or until it cant find a button 5-10 games down the road.
if it doesnt work for you in resurgance, i suggest playing plunder as it auto connects at the end regardless.
replacing the png images of the buttons with your own screenshots, or just editing the manual coordinates for the clicks in the code to your resolution if it doesnt work, or if you are using a different resolution.
it runs long enough to get you into some absolute shitter lobbies and lowers your KD quite a bit. it helps curve the manual reports as well.
its not 100% polished, some paste and the keyinput.py file i stole from the internet, if you want to add to it, or make it less clunky feel free.
main.py
Code:
import sys
import ctypes
import time
import win32gui
import win32process
import threading
import psutil
import gc
import numpy as np
import cv2
import pyautogui
from PIL import ImageGrab
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from pynput import keyboard
import random
import keyinput # Import keyinput.py
# The target process name for "Call of Duty® HQ"
target_process_name = "cod.exe"
target_pid = -1 # This will be updated dynamically
window_found = False
# Movement control flag
movement_enabled = False
detection_thread_active = False # Flag to prevent multiple detection threads
# Set up the interval for checking screenshots
check_interval = 1.5 # seconds for faster button detection
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Function to load the templates
def load_templates():
global template_play_again, template_play_again_hovered, template_yes
global template_play_again_w, template_play_again_h
global template_play_again_hovered_w, template_play_again_hovered_h
global template_yes_w, template_yes_h
template_play_again = cv2.imread('play_again_template.png', cv2.IMREAD_GRAYSCALE)
template_play_again_hovered = cv2.imread('playagainhovered.png', cv2.IMREAD_GRAYSCALE)
template_yes = cv2.imread('yes.png', cv2.IMREAD_GRAYSCALE)
template_play_again_w, template_play_again_h = template_play_again.shape[::-1]
template_play_again_hovered_w, template_play_again_hovered_h = template_play_again_hovered.shape[::-1]
template_yes_w, template_yes_h = template_yes.shape[::-1]
# Load the templates initially
load_templates()
# Function to perform random movements using WASD keys and press F key
def perform_random_movement():
global movement_enabled
while movement_enabled:
# Randomly choose a key: W (0x11), A (0x1E), S (0x1F), D (0x20)
key_to_press = random.choice([keyinput.W, keyinput.A, keyinput.S, keyinput.D])
# Hold the key for a random duration between 0.2 and 1 second
hold_duration = random.uniform(0.2, 1.0)
keyinput.holdKey(key_to_press, hold_duration)
# Wait for a random duration between 1 and 3 seconds before the next move
time.sleep(random.uniform(1, 3))
# Randomly press the F key every 5 seconds
keyinput.pressKey(0x21) # F key (hex code for 'F' is 0x21)
keyinput.releaseKey(0x21)
print("Pressed F key")
time.sleep(5) # Wait for 5 seconds
# Find the PID of the process by its name
def find_pid_by_name(process_name):
for proc in psutil.process_iter(['pid', 'name']):
if proc.info['name'] == process_name:
return proc.info['pid']
return None
# Find the window associated with the specific PID
def get_window_by_pid(hwnd, extra):
global window_x, window_y, window_width, window_height, window_found, target_pid
_, pid = win32process.GetWindowThreadProcessId(hwnd)
window_title = win32gui.GetWindowText(hwnd)
# Check if the PID matches
if pid == target_pid:
window_found = True
rect = win32gui.GetClientRect(hwnd)
window_pos = win32gui.ClientToScreen(hwnd, (0, 0))
window_x = window_pos[0]
window_y = window_pos[1]
window_width = rect[2]
window_height = rect[3]
# Watchdog function to ensure the process is still running and the window is found
def process_watchdog():
global window_found, target_pid
while True:
time.sleep(60)
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
continue
window_found = False
win32gui.EnumWindows(get_window_by_pid, None)
if not window_found:
print("No window found for the target process")
# Function to click at the specified location
def click(x, y):
time.sleep(0.1) # Add a short delay before the click
pyautogui.click(x, y, duration=0.2)
time.sleep(0.1) # Add a short delay after the click
# Function to stop movement
def stop_movement():
global movement_enabled, detection_thread_active
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
print("Movement stopped")
# Function to resume movement
def resume_movement():
global movement_enabled, detection_thread_active
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
detection_thread_active = False # Reset detection thread state
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Start the detection process again
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
print("Looking for buttons")
# Function to detect and click the "YES" button after "PLAY AGAIN"
def detect_and_click_yes():
global detection_thread_active
print("Looking for the YES button...")
time.sleep(3) # Give some time for the YES screen to appear
max_attempts = 3 # Limit the number of attempts to find the YES button
for attempt in range(max_attempts):
# Capture the full screen (for YES button detection)
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
# Convert the screenshot to grayscale to reduce memory usage
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "YES" button
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
button_x = max_loc[0] + template_yes_w // 2
button_y = max_loc[1] + template_yes_h // 2
for _ in range(5): # Click the "YES" button 5 times at human speed
click(button_x, button_y)
time.sleep(random.uniform(0.3, 0.7)) # Add random delay between clicks
print(f"Clicked YES at position: ({button_x}, {button_y})")
# Recheck to see if the button is still there
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab()
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_yes, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "YES" button is not found, confirm success
print("YES button successfully clicked and no longer detected.")
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
return
else:
print("YES button still detected, retrying...")
print(f"Attempt {attempt + 1} to click YES button failed.")
time.sleep(check_interval) # Wait for a while before retrying
# If all attempts fail, click predefined coordinates as a backup
print(f"Clicking predefined coordinates for YES button: {yes_button_coords}")
click(yes_button_coords[0], yes_button_coords[1])
# Reset detection process here
load_templates() # Reload templates to reset object detection
gc.collect() # Explicitly trigger garbage collection
# Indicate that the bot is ready to start looking for buttons again
print("Looking for buttons")
resume_movement()
# Function to detect and click the "PLAY AGAIN" button in the right section
def detect_and_click_play_again():
global detection_thread_active
if detection_thread_active:
return # Exit if a detection thread is already running
detection_thread_active = True # Mark the detection thread as active
try:
while movement_enabled:
# Capture the right section of the screen
screen_width, screen_height = ImageGrab.grab().size
right_section = (screen_width * 2 // 3, 0, screen_width, screen_height)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
# Perform template matching to find the "Play Again" button
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(result)
if max_val >= 0.8: # If the match is good enough, click the button
stop_movement()
button_x = max_loc[0] + template_play_again_w // 2 + screen_width * 2 // 3 # Adjust x for the right section
button_y = max_loc[1] + template_play_again_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1) # Short delay before rechecking
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result = cv2.matchTemplate(screenshot_gray, template_play_again, cv2.TM_CCOEFF_NORMED)
_, max_val, _, _ = cv2.minMaxLoc(result)
if max_val < 0.8: # If the "Play Again" button is no longer found, move on
print("PLAY AGAIN button no longer detected.")
detect_and_click_yes() # Proceed to the "YES" button
return
else:
print("PLAY AGAIN button still detected, clicking again...")
click(button_x, button_y) # Click the button again if still detected
# If not found, try the hovered version
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, max_loc_hovered = cv2.minMaxLoc(result_hovered)
if max_val_hovered >= 0.8:
stop_movement()
button_x = max_loc_hovered[0] + template_play_again_hovered_w // 2 + screen_width * 2 // 3
button_y = max_loc_hovered[1] + template_play_again_hovered_h // 2
click(button_x, button_y)
print(f"Clicked PLAY AGAIN (hovered) at position: ({button_x}, {button_y})")
# After clicking, verify if the button is still there and retry if needed
while True:
time.sleep(1)
screenshot = ImageGrab.grab(bbox=right_section)
screenshot_np = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
result_hovered = cv2.matchTemplate(screenshot_gray, template_play_again_hovered, cv2.TM_CCOEFF_NORMED)
_, max_val_hovered, _, _ = cv2.minMaxLoc(result_hovered)
if max_val_hovered < 0.8:
print("PLAY AGAIN (hovered) button no longer detected.")
detect_and_click_yes()
return
else:
print("PLAY AGAIN (hovered) button still detected, clicking again...")
click(button_x, button_y)
# Wait for the check interval before the next screenshot if neither button is found
time.sleep(check_interval)
finally:
detection_thread_active = False # Ensure the flag is reset when the thread exits
# Create a PyQt5 application and overlay window with instructions
class OverlayWindow(QWidget):
def __init__(self):
super().__init__()
# Set window properties for transparency and ignoring mouse events
self.setWindowTitle('Overlay')
screen_resolution = QApplication.desktop().screenGeometry()
screen_width, screen_height = screen_resolution.width(), screen_resolution.height()
overlay_width, overlay_height = 300, 100 # Set the overlay size
self.setGeometry((screen_width - overlay_width) // 2, screen_height - overlay_height - 50, overlay_width, overlay_height)
self.setWindowFlags(Qt.Tool | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.WindowDoesNotAcceptFocus)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
# Create UI components
self.layout = QVBoxLayout()
self.instructions_label = QLabel("Press 'H + 4' to Start\nPress 'Z + Y' to Stop", self)
self.instructions_label.setStyleSheet("color: white; font-size: 16px;")
self.status_label = QLabel("Status: Stopped", self)
self.status_label.setStyleSheet("color: red; font-size: 16px;")
self.layout.addWidget(self.instructions_label)
self.layout.addWidget(self.status_label)
self.setLayout(self.layout)
def update_status(self, running):
if running:
self.status_label.setText("Status: Running")
self.status_label.setStyleSheet("color: green; font-size: 16px;")
else:
self.status_label.setText("Status: Stopped")
self.status_label.setStyleSheet("color: red; font-size: 16px;")
# Set ourselves as DPI aware, or else we won't get proper pixel coordinates if scaling is not 100%
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
# Start the PyQt5 application
app = QApplication(sys.argv)
overlay = OverlayWindow()
# Find the PID of the process before looking for windows
target_pid = find_pid_by_name(target_process_name)
if target_pid is None:
print(f"No process found with name: {target_process_name}")
sys.exit(1)
# Find the window using the PID
win32gui.EnumWindows(get_window_by_pid, None)
# If the window hasn't been found, exit
if not window_found:
print("No Call of Duty® HQ window found")
sys.exit(1)
# Show the overlay window
overlay.show()
# Start the watchdog thread
watchdog_thread = threading.Thread(target=process_watchdog)
watchdog_thread.start()
# Track key press states
pressed_keys = set()
# Function to start movement
def start_movement():
global movement_enabled
if not movement_enabled: # Prevent restarting movement if already enabled
movement_enabled = True
print("Movement started")
overlay.update_status(True)
# Start the random movement in a separate thread
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
detection_thread = threading.Thread(target=detect_and_click_play_again)
detection_thread.start()
# Function to stop movement
# Function to stop movement and update overlay status
def stop_movement():
global movement_enabled, detection_thread_active
if movement_enabled: # Check if movement is actually enabled before stopping
movement_enabled = False
detection_thread_active = False # Allow a new detection thread to be started
overlay.update_status(False) # Update overlay to show stopped status
print("Movement stopped")
# Function to resume movement and update overlay status
def resume_movement():
global movement_enabled
if not movement_enabled: # Check if movement is not enabled before resuming
movement_enabled = True
overlay.update_status(True) # Update overlay to show running status
print("Movement resumed")
movement_thread = threading.Thread(target=perform_random_movement)
movement_thread.start()
# Set up global hotkeys using Pynput to start and stop movement
def on_press(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.add(key.char)
if 'h' in pressed_keys and '4' in pressed_keys:
start_movement()
elif 'z' in pressed_keys and 'y' in pressed_keys:
stop_movement()
except AttributeError:
pass
def on_release(key):
try:
if hasattr(key, 'char'): # If the key is a character key
pressed_keys.remove(key.char)
except KeyError:
pass
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
# Main loop for the overlay
def main_loop():
while True:
if not window_found:
time.sleep(5)
continue
time.sleep(1.0) # Placeholder for movement logic
# Start the main loop in a separate thread so it doesn't block the GUI
main_loop_thread = threading.Thread(target=main_loop)
main_loop_thread.start()
sys.exit(app.exec_())
keyinput.py
Code:
import ctypes, win32api, win32con, time
SendInput = ctypes.windll.user32.SendInput
ESC = 0x01
W = 0x11
A = 0x1E
S = 0x1F
D = 0x20
SPACE = 0x39
UP = 0xC8
DOWN = 0xD0
LEFT = 0xCB
RIGHT = 0xCD
ENTER = 0x1C
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
#thank you to whoever it is i stole this from xD
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time",ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Actual Functions
def pressKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def releaseKey(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0,
ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def holdKey(hexKeyCode, duration):
pressKey(hexKeyCode)
stop_time = time.time() + duration
while time.time() < stop_time:
time.sleep(0.01)
pressKey(hexKeyCode)
releaseKey(hexKeyCode)
def click(x, y, click_delay = 0.15):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
time.sleep(click_delay)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def move(x, y):
try:
win32api.SetCursorPos((x, y))
except:
print('Error: SetCursorPos failed')
reqirements.txt
Code:
PyQt5==5.15.4
opencv-python==4.5.5.64
Pillow==8.4.0
numpy==1.21.4
psutil==5.8.0
pynput==1.7.3
pyautogui==0.9.53
pywin32==302
play_again_template.png
playagainhovered.png
yes.png
yeshovered.png
make sure the names on the images match in the directory.
you should probably take your own screenshots, of these buttons in game and use those.
you can also just change the coordinates of the buttons from 1440p to change your resolution
Code:
# Predefined coordinates for the "YES" button based on your observations
yes_button_coords = (944, 804)
# Predefined coordinates for the "PLAY AGAIN" button (example)
play_again_coords = (1500, 900)
# In the fallback scenario for "Play Again"
click(play_again_coords[0], play_again_coords[1])
|
This gets people temp banned so i wouldnt suggest giving yourself a headache just to get banned.
|
|
|
All times are GMT +1. The time now is 14:01.
|
|