python实现抖音、微信自动回复
·

原理:使用pyautogui,识别新消息,控制鼠标键盘自动回复
抖音版:
import pyautogui as pg
#import pytesseract
import time
import random
import easyocr,cv2,urllib,requests,pyperclip
import numpy as np
#from selenium import webdriver
#from selenium.webdriver.common.by import By
from PIL import Image
reader = easyocr.Reader(['ch_sim','en'],gpu=False,download_enabled=False)
index_box = None
a = 0.8
TESSERACT_PATH = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# 配置参数
DOUYIN_URL = 'https://www.douyin.com/'
ICON_PATH = 'new_message_icon.png' # 抖音消息红点图标截图
REPLY_TEMPLATES = {
"加群": "请添加微信号:xxx",
"价格": "商品价格详见橱窗",
"默认": "hello"
}
#pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# 初始化浏览器(需提前配置WebDriver)
def init_browser():
driver = webdriver.Edge()
driver.maximize_window()
driver.get(DOUYIN_URL)
# 加载已保存的Cookie(需提前登录)
try:
with open("douyin_cookie.pickle", 'rb') as file:
cookies = pickle.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
except FileNotFoundError:
print("未找到Cookie文件,请先登录")
return driver
def qingyunke_api(msg):
"""增强版智能回复[5](@ref)"""
try:
params = {
'key': 'free',
'appid': 0,
'msg': urllib.parse.quote(msg[:100]) # 限制输入长度
}
response = requests.get('http://api.qingyunke.com/api.php',
params=params,
timeout=8)
return response.json().get("content", "服务繁忙").replace("{br}", "\n")
except Exception as e:
print(f"API异常:{str(e)}")
return None
# 检测新消息红点
def check_new_message():
try:
icon_pos = pg.locateOnScreen(ICON_PATH, confidence=0.6)
except pg.ImageNotFoundException:
print("未找到图标,继续运行程序")
icon_pos = None
if icon_pos:
pg.click(icon_pos)
return True
return False
# OCR识别消息内容
def read_message():
# 截取消息区域(根据实际窗口调整坐标)
#try:
message_area = pg.screenshot(region=(1138, 668, 417, 86))
cv_image = cv2.cvtColor(np.array(message_area), cv2.COLOR_RGB2BGR) # 中英文识别
text = reader.readtext(cv_image, detail=0, paragraph=True) # 合并段落
#except:
'''print('重试')
read_message()'''
print(text)
if text == [] or text == ['']:
return None
return text
# 自动回复逻辑
def auto_reply(text):
global index_box,a
'''reply = REPLY_TEMPLATES["默认"]
for keyword in REPLY_TEMPLATES:
if keyword in text:
reply = REPLY_TEMPLATES[keyword]
break'''
reply = qingyunke_api(text[0])
# 定位输入框并发送(动态定位更稳定)
try:
input_box = pg.locateOnScreen('input_box_icon.png', confidence=a)
except:
print('重来')
a-=0.1
auto_reply(text)
else:
pg.click(input_box)
pyperclip.copy(reply)
print(reply)
pg.hotkey('ctrl', 'v')
pg.press('enter')
pg.press('enter')
# 主循环
def main():
#driver = init_browser()
while True:
pg.click((1238,668))
pg.scroll(-10)
time.sleep(random.uniform(1, 2)) # 模拟人工延迟
message = read_message()
if message:
auto_reply(message)
else:
print('无新消息')
#pg.press('esc') # 返回消息列表
time.sleep(10) # 每10秒检测一次
main()
微信版:
import pyautogui as pg
#import pytesseract
import time
import random
import easyocr,cv2,urllib,requests,pyperclip
import numpy as np
#from selenium import webdriver
#from selenium.webdriver.common.by import By
from PIL import Image
reader = easyocr.Reader(['ch_sim','en'],gpu=False,download_enabled=False)
index_box = None
TESSERACT_PATH = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# 配置参数
DOUYIN_URL = 'https://www.douyin.com/'
ICON_PATH = 'new_message_icon.png' # 抖音消息红点图标截图
REPLY_TEMPLATES = {
"加群": "请添加微信号:xxx",
"价格": "商品价格详见橱窗",
"默认": "hello"
}
#pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# 初始化浏览器(需提前配置WebDriver)
def init_browser():
driver = webdriver.Edge()
driver.maximize_window()
driver.get(DOUYIN_URL)
# 加载已保存的Cookie(需提前登录)
try:
with open("douyin_cookie.pickle", 'rb') as file:
cookies = pickle.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
except FileNotFoundError:
print("未找到Cookie文件,请先登录")
return driver
def qingyunke_api(msg):
"""增强版智能回复[5](@ref)"""
try:
params = {
'key': 'free',
'appid': 0,
'msg': urllib.parse.quote(msg[:100]) # 限制输入长度
}
response = requests.get('http://api.qingyunke.com/api.php',
params=params,
timeout=8)
return response.json().get("content", "服务繁忙").replace("{br}", "\n")
except Exception as e:
print(f"API异常:{str(e)}")
return None
# 检测新消息红点
def check_new_message():
try:
icon_pos = pg.locateOnScreen(ICON_PATH, confidence=0.6)
except pg.ImageNotFoundException:
print("未找到图标,继续运行程序")
icon_pos = None
if icon_pos:
pg.click(icon_pos)
return True
return False
# OCR识别消息内容
def read_message():
# 截取消息区域(根据实际窗口调整坐标)
#try:
message_area = pg.screenshot(region=(707, 595, 326, 134))
cv_image = cv2.cvtColor(np.array(message_area), cv2.COLOR_RGB2BGR) # 中英文识别
text = reader.readtext(cv_image, detail=0, paragraph=True) # 合并段落
#except:
'''print('重试')
read_message()'''
print(text)
if text == [] or text == ['']:
return None
return text
# 自动回复逻辑
def auto_reply(text):
global index_box
'''reply = REPLY_TEMPLATES["默认"]
for keyword in REPLY_TEMPLATES:
if keyword in text:
reply = REPLY_TEMPLATES[keyword]
break'''
reply = qingyunke_api(text[0])
# 定位输入框并发送(动态定位更稳定)
try:
input_box = pg.locateOnScreen('input_box_icon.png', confidence=0.4)
except:
print('重来')
auto_reply(text)
else:
print(input_box)
left, top, width, height = input_box
random_x = random.randint(left, left + width-100)
random_y = random.randint(top+100, top + height)
pg.moveTo(random_x, random_y, duration=random.uniform(0.2, 0.5))
pg.click(random_x, random_y, interval=random.uniform(0.1, 0.3))
pyperclip.copy(reply)
print(reply)
pg.hotkey('ctrl', 'v')
pg.press('enter')
pg.press('enter')
# 主循环
def main():
#driver = init_browser()
while True:
time.sleep(random.uniform(1, 2)) # 模拟人工延迟
message = read_message()
if message:
auto_reply(message)
else:
print('无新消息')
#pg.press('esc') # 返回消息列表
time.sleep(10) # 每10秒检测一次
main()
需下载easyocr所需文件,准备输入框的截图,根据实际情况修改坐标
更多推荐
所有评论(0)