目录
代码
代码功能详解
注意事项
致谢
代码
import io
import traceback
import win32clipboard
import pyautogui
import pyperclip
import win32gui # 替换为pywin32的正确模块名
import pandas as pd
import time
from PIL import Imageclass QQAutoMessage:def __init__(self):self.contacts_file = r".\students.xlsx" # Excel表位置self.qq_search_pos = (191, 56) # 搜索框坐标self.contact_pos = (600, 857) # 聊天输入框坐标self.first_contact_pos = (244, 155) # 第一个符合条件的坐标self.send_delay = 1self.pictures = [r"test.png"] # 图片路径列表def load_file(self):return pd.read_excel(self.contacts_file, engine='openpyxl')def find_qq_window(self):hwnd = win32gui.FindWindow(None, "QQ")if hwnd == 0:raise Exception("未检测到QQ主窗口,请确认已登录")return hwnddef search_contact(self, student_id):pyautogui.moveTo(self.qq_search_pos)pyautogui.click()time.sleep(0.5)pyautogui.hotkey('ctrl', 'a')pyautogui.press('backspace')time.sleep(0.5)pyautogui.typewrite(str(student_id))time.sleep(1)pyautogui.moveTo(self.first_contact_pos)pyautogui.doubleClick()def send_message(self, message):time.sleep(1)pyautogui.moveTo(self.contact_pos)pyautogui.click()time.sleep(2)pyperclip.copy(message)pyautogui.hotkey('ctrl', 'v')time.sleep(1)pyautogui.press('enter')# send pictures ?if self.pictures:for picture_path in self.pictures:copy_image_to_clipboard(picture_path)pyautogui.hotkey('ctrl', 'v')time.sleep(1)pyautogui.press('enter')return Truedef run(self):contacts = self.load_file()qq_hwnd = self.find_qq_window()if qq_hwnd == 0:exit(-1)# begin send messagefor index, row in contacts.iterrows():try:self.search_contact(row['学号'])success = self.send_message(row['消息内容'])if success:print(f"成功发送给:{row['姓名']}(内容:{row['消息内容']}...)")else:print(f"发送失败:{row['姓名']}")time.sleep(self.send_delay)except Exception as e:traceback.print_exc()print(e)continuedef copy_image_to_clipboard(image_path):image = Image.open(image_path)output = io.BytesIO()image.convert("RGB").save(output, "BMP")data = output.getvalue()[14:]output.close()win32clipboard.OpenClipboard()try:win32clipboard.EmptyClipboard()win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)finally:win32clipboard.CloseClipboard()if __name__ == "__main__":bot = QQAutoMessage()bot.run()
代码功能详解
加载Excel文件,根据文件中的学号在QQ搜索框中进行搜索,并选择第一个符合搜索条件的对象进行对话,发送聊天文本,并发送图片。
注意事项
- 需要安装对应的包
- 需要修改文件中的变量内容:contacts_file、pictures
- 合理修改以下变量:qq_search_pos、contact_pos、first_contact_pos【这部分内容分别指代QQ搜索框的坐标、聊天文字输入框的坐标、搜索到的第一个符合条件的坐标,本人选择的是将QQ界面最大化】
- 需要创建一个Excel表格,表格形式如下:
姓名 | 学号 | 发送文字 |
---|---|---|
张三 | 00000000 | 今晚有约吗? |
致谢
我亲爱的女朋友给了我灵感和动力。
羡林i提供的复制图片到剪切板的函数。