def __init__(self, bot): # self.group = group self.api_key = api_key self.log = Logger() self.ycy = YcyReplier() self.tuling = Tuling(api_key=TULING_KEY) self.user = User() self.group = Group() self.rsp_game_player_map = {} self.bot = bot self.draw_lots_game = DrawLots() self.user_lots_map = {} self.user_lots_read_map = {} self.answer = "" self.red_bag_num = 0 ''' 开启每日定时器,每日零时清空抽签内容 ''' self.scheduler = BackgroundScheduler() self.scheduler.add_job(self.init_lots_map, 'cron', hour='0') self.scheduler.start()
def start_tuling(bot): groups = bot.groups(update=True) junwei_group = ensure_one(groups.search(GroupNames.JUNWEI)) morning_group = ensure_one(groups.search(GroupNames.MORNING)) tianya_group = ensure_one(groups.search('天涯')) sunjiaxiao_group = ensure_one(groups.search('孙家小群')) sunjiada_group = ensure_one(groups.search('孙家大群')) tuling = Tuling(api_key=TuLingConfig.API_KEY) @bot.register([junwei_group, morning_group, tianya_group, sunjiaxiao_group, sunjiada_group], TEXT) def forward_msg(msg): if msg.is_at: tuling.do_reply(msg, at_member=True)
def __init__(self, bot_=None, path_=None, config_=WechatDefaultConfig.AUTO_REPLIER_CONFIG, logger_=None): super(WechatAutoReplier, self).__init__(bot_=bot_, path_=path_, config_=config_, logger_=logger_) self._tuling = Tuling(api_key=self._tuling_api_key) self._xiaoi = XiaoI(key=self._xiaoi_key, secret=self._xiaoi_secret) self._set_replier(tuling_=self._config['auto_replier']['tuling'], xiaoi_=self._config['auto_replier']['xiaoi'])
class MyWindow(QtWidgets.QWidget, Ui_Form): # 注意Ui_Form要跟UI文件中的匹配 def __init__(self): super(MyWindow, self).__init__() self.setupUi(self) # QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Fusion')) # 风格 self.setWindowFlags(QtCore.Qt.FramelessWindowHint) # 没有标题栏 self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 设置窗口背景透明 self.setWindowOpacity(0.95) # 窗体透明度 self.addSystemTray() # 调用托盘函数 # 初始化标签、文本框提示,禁用不需要输入的文本框 self.output_info("请点击左侧的扫码按钮!") self.lineEdit_busy.setText("您好,我现在忙,不方便回复您!有事请留言![微笑]") self.lineEdit_file_dir.setEnabled(False) self.lineEdit_file_dir_1.setEnabled(False) # 点击左侧按钮联动stackedWidget对应页面 self.toolButton_11friend.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(0)) self.toolButton_11friend.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(0)) self.toolButton_12chatroom.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(1)) self.toolButton_12chatroom.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(1)) self.toolButton_13more.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(2)) # 更多功能中,还对应三个按钮 def btn_more_clicked(): if self.toolButton_21remote.isChecked(): self.stackedWidget_2.setCurrentIndex(2) elif self.toolButton_22reply.isChecked(): self.stackedWidget_2.setCurrentIndex(3) elif self.toolButton_23help.isChecked(): self.stackedWidget_2.setCurrentIndex(4) else: self.stackedWidget_2.setCurrentIndex(2) self.toolButton_13more.clicked.connect(btn_more_clicked) self.toolButton_21remote.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(2)) self.toolButton_22reply.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(3)) self.toolButton_23help.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(4)) # 按钮 self.toolButton_18login.clicked.connect(self.login) self.toolButton_19logout.clicked.connect(self.logout) self.toolButton_search.clicked.connect( lambda: self.lineEdit_search.setText("该功能尚未启用!")) self.pushButton_text_helper.clicked.connect(self.text_to_helper) self.pushButton_text_friend.clicked.connect(self.text_to_friend) self.pushButton_text_chatroom.clicked.connect(self.text_to_chatroom) self.pushButton_open_file.clicked.connect(self.open_file) self.pushButton_open_file_1.clicked.connect(self.open_file) self.pushButton_file_helper.clicked.connect(self.file_to_helper) self.pushButton_file_friend.clicked.connect(self.file_to_friend) self.pushButton_file_chatroom.clicked.connect(self.file_to_chatroom) # 自动回复等功能选项复选框 self.checkBox_remote.setChecked(True) # 默认勾选 self.checkBox_busy.stateChanged.connect(self.check_busy) self.checkBox_robot.stateChanged.connect(self.check_robot) self.checkBox_remote.stateChanged.connect(self.check_remote) # 设置自动回复等功能选项默认开关 self.remote_pc = True self.reply_busy = False self.reply_robot = False # 登陆微信前,使按钮失效 # self.toolButton_19logout.setEnabled(False) self.pushButton_text_helper.setEnabled(False) self.pushButton_text_friend.setEnabled(False) self.pushButton_text_chatroom.setEnabled(False) self.pushButton_open_file.setEnabled(False) self.pushButton_open_file_1.setEnabled(False) self.pushButton_file_helper.setEnabled(False) self.pushButton_file_friend.setEnabled(False) self.pushButton_file_chatroom.setEnabled(False) # 提示信息 text_help = '\n' \ '========== ★ 感谢使用 MineWechat V4.1 ★ ========== By Jenas\n\n' \ '1. 作者只是初学者,程序尚有很多Bug,请多包涵,欢迎反馈!\n\n' \ '2. 好友、群聊列表支持 Ctrl、Shift 多选,双击清空选择。\n\n' \ '3. 获取微信远控指令:手机微信编辑“#帮助”发送至“文件传输助手”。\n\n' \ '4. 发送文件的文件名不可以是中文,但路径可以包含中文。\n\n' \ '5. 隐藏窗口后,可以在系统托盘中打开程序界面。\n\n' \ '6. 锁定屏幕会导致部分功能失效,所以,挂机的话请关闭睡眠和锁屏。\n\n' \ '7. 想起来再补……' self.textEdit_help.setText(text_help) # 按住鼠标,拖动窗口 def mousePressEvent(self, event): if event.button() == QtCore.Qt.LeftButton: self.m_flag = True self.m_Position = event.globalPos() - self.pos() # 获取鼠标相对窗口的位置 event.accept() self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor)) # 更改鼠标图标 def mouseMoveEvent(self, QMouseEvent): if QtCore.Qt.LeftButton and self.m_flag: self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置 QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_flag = False self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) # 托盘菜单 def addSystemTray(self): # 在系统托盘处显示图标 self.tp = QtWidgets.QSystemTrayIcon(self) self.tp.setIcon(QtGui.QIcon(":/img/images/wechat.png")) # 设置系统托盘图标的菜单 a1 = QtWidgets.QAction('&显示(Show)', self, triggered=self.show) a2 = QtWidgets.QAction('&隐藏(Hide)', self, triggered=self.hide) a3 = QtWidgets.QAction( '&退出(Exit)', self, triggered=self.quitApp) # 不用self.close()是因为windows中退出程序,托盘图标还会残留 self.tpMenu = QtWidgets.QMenu(self) self.tpMenu.addAction(a1) self.tpMenu.addAction(a2) self.tpMenu.addSeparator() self.tpMenu.addAction(a3) self.tp.setContextMenu(self.tpMenu) self.tp.show() # 不调用show不会显示系统托盘 # 托盘信息提示,参数1:标题,参数2:内容,参数3:图标(0没有图标 1信息图标 2警告图标 3错误图标),0还是有一个小图标 # self.tp.showMessage('MineWechat','隐藏窗口,我在这里!',icon=0) # 鼠标点击托盘图标 self.tp.activated.connect(self.act) def act(self, reason): # 鼠标点击托盘图标 # 鼠标点击icon传递的信号会带有一个整形的值,1是表示单击右键,2是双击,3是单击左键,4是用鼠标中键点击 # if reason == 2 : if reason == 3: self.show() def quitApp(self): # windows系统中,应用程序关闭后,托盘图标还不会自动消失, # 直到你的鼠标移动到上面去后,才会消失, # 可以通过将其setVisible(False)来完成的。 QtCore.QCoreApplication.instance().quit() self.tp.setVisible(False) #################################################### # 包含:登陆、注销、系统信息、好友列表 #################################################### # 获取当前时间戳,并转格式 def get_now_time(self): now_time = time.strftime("%m-%d %H:%M:%S") time_msg = '[%s]' % now_time return time_msg # 记录底部的系统信息 def output_info(self, info): time_msg = self.get_now_time() self.textEdit_output.append(time_msg + ' ' + info) # 登陆按钮 def login(self): self.thread = MyThread() # 创建线程 # 线程的信号槽,依次关联:写微信聊天记录、获取微信用户名、写微信远控信息、更新好友列表、更新群聊列表、截图 self.thread._signal_1.connect(self.write_log) self.thread._signal_2.connect(self.get_username) self.thread._signal_3.connect(self.output_remote_info) self.thread._signal_4.connect(self.update_friends) self.thread._signal_5.connect(self.update_chatrooms) self.thread._signal_6.connect(self.screenshot) self.thread.start() # 开始线程 # 注销退出按钮 def logout(self): # myshow.thread.bot.logout() # time.sleep(0.2) self.quitApp() #底部托盘的方法 # 自己的微信用户名 def get_username(self, username): self.username = username self.label_name.setText(self.username) self.output_info('登录成功,%s,欢迎使用!' % self.username) # UI按钮启用,更新好友列表时顺带调用 def ui_enabled(self): self.toolButton_18login.setEnabled(False) self.toolButton_19logout.setEnabled(True) self.pushButton_text_helper.setEnabled(True) self.pushButton_text_friend.setEnabled(True) self.pushButton_text_chatroom.setEnabled(True) self.pushButton_open_file.setEnabled(True) self.pushButton_open_file_1.setEnabled(True) self.pushButton_file_helper.setEnabled(True) self.pushButton_file_friend.setEnabled(True) self.pushButton_file_chatroom.setEnabled(True) # 左侧好友列表 def update_friends(self, friends_list): self.ui_enabled() # 启用ui按钮 self.slm_1 = QtCore.QStringListModel() # 实例化列表模型 self.qList_1 = friends_list self.slm_1.setStringList(self.qList_1) # 加载数据列表 self.listView_friend.setModel(self.slm_1) # 设置列表视图的模型 self.listView_friend.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_friend.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) # 不能对表格进行修改(双击重命名等) self.listView_friend.clicked.connect(self.friends_clicked) self.listView_friend.doubleClicked.connect( self.listView_friend.clearSelection) # 点击左侧好友列表 def friends_clicked(self): friends_clicked_name = '' friends_clicked_list = [] for i in self.listView_friend.selectedIndexes(): friend_Name = i.data() friends_clicked_name += friend_Name + ' ' friends_clicked_list.append(friend_Name) num = len(friends_clicked_list) if num > 1: friends_num = friends_clicked_name + '共计[' + str(num) + ']人' self.label_text_friend.setStyleSheet( "QLabel#label_text_friend{font: 10pt;}") # 多选好友时,字号变小 else: friends_num = friends_clicked_name self.label_text_friend.setStyleSheet( "QLabel#label_text_friend{font: 16pt;}") self.label_text_friend.setText(friends_num) return friends_clicked_list # 左侧群聊列表 def update_chatrooms(self, chatrooms_list): self.slm_2 = QtCore.QStringListModel() # 实例化列表模型 self.qList_2 = chatrooms_list self.slm_2.setStringList(self.qList_2) # 加载数据列表 self.listView_chatroom.setModel(self.slm_2) # 设置列表视图的模型 self.listView_chatroom.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_chatroom.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) # 禁止对列表修改(双击重命名) self.listView_chatroom.clicked.connect(self.chatrooms_clicked) self.listView_chatroom.doubleClicked.connect( self.listView_chatroom.clearSelection) # 点击左侧群聊列表 def chatrooms_clicked(self): chatrooms_clicked_name = '' chatrooms_clicked_list = [] for i in self.listView_chatroom.selectedIndexes(): chatroom_Name = i.data() chatrooms_clicked_name += chatroom_Name + ' ' chatrooms_clicked_list.append(chatroom_Name) num = len(chatrooms_clicked_list) if num > 1: chatrooms_num = chatrooms_clicked_name + '共计[' + str(num) + ']个群' self.label_text_chatroom.setStyleSheet( "QLabel#label_text_chatroom{font: 10pt;}") else: chatrooms_num = chatrooms_clicked_name self.label_text_chatroom.setStyleSheet( "QLabel#label_text_chatroom{font: 16pt;}") self.label_text_chatroom.setText(chatrooms_num) return chatrooms_clicked_list # pyqt5截图 def screenshot(self, img_name): # print('截图') # 新建screenshot文件夹,并cd进入 isPathExist = os.path.exists("screenshot") if not isPathExist: os.makedirs("screenshot") os.chdir("screenshot") #pyqt5的截图在子进程中会报错,试试用信号通知主线程截图,可行。 QtWidgets.QApplication.primaryScreen().grabWindow( QtWidgets.QApplication.desktop().winId()).save(img_name) ############################################# # 功能选项,及远控信息 ############################################# # 微信忙碌回复功能开关 def check_busy(self): check_state = self.checkBox_busy.checkState() #print(check_state) if check_state == QtCore.Qt.Checked: self.output_info('已打开[忙碌回复]功能') self.reply_busy = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[忙碌回复]功能') self.reply_busy = False # 微信机器人回复功能开关 def check_robot(self): check_state = self.checkBox_robot.checkState() #print(check_state) if check_state == QtCore.Qt.Checked: self.output_info('已打开[机器人回复]功能') self.reply_robot = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[机器人回复]功能') self.reply_robot = False # 调用图灵机器人的api,利用爬虫,根据聊天消息返回回复内容 tuling = Tuling(api_key='9489eda6f3704a65b0221a3f65e0b98b') # wxpy整合了图灵机器人 # 微信远程控制功能开关 def check_remote(self): check_state = self.checkBox_remote.checkState() #print(check_state) if check_state == QtCore.Qt.Checked: self.output_info('已打开[微信远控]功能') self.remote_pc = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[微信远控]功能') self.remote_pc = False # 记录远程控制相关信息 def output_remote_info(self, message): time_msg = self.get_now_time() self.textEdit_remote.append(time_msg + ' ' + message) ###################################### # 微信发送文字、文件 ###################################### # 记录聊天信息,包含:发送信息、接收信息 # 参数:是否群聊,消息内容,消息时间, 依次类型: bool,str,int def write_log(self, fromChatroom, message, send_time): myTime = time.strftime(r"%m-%d %H:%M:%S", time.localtime(send_time)) msg_data = '[' + myTime + '] ' + message if fromChatroom == False: self.textEdit_friend_record.append(msg_data) else: self.textEdit_chatroom_record.append(msg_data) # 发送文字到助手 def text_to_helper(self): text_send = self.textEdit_text_friend.toPlainText() self.thread.bot.file_helper.send(text_send) fromChatroom = False # 做个记号,不是群聊 message = "Python→助手:" + text_send # 编辑聊天记录内容 send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 # 发送文字到好友 def text_to_friend(self): text_send = self.textEdit_text_friend.toPlainText() text_friends = self.friends_clicked() #print(text_friends) if len(text_friends) == 0: # 没有勾选,列表空 self.output_info("您还没有选择好友!") else: for friend_element in text_friends: search_name = self.thread.bot.friends().search( friend_element)[0] #print(search_name) if search_name: search_name.send(text_send) fromChatroom = False message = "Python→" + search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom, message, send_time) else: self.output_info("找不到该好友!") # 发送文字到群聊 def text_to_chatroom(self): text_send = self.textEdit_text_chatroom.toPlainText() text_chatrooms = self.chatrooms_clicked() if len(text_chatrooms) == 0: self.output_info("您还没有选择群聊!") else: for chatroom_element in text_chatrooms: search_name = self.thread.bot.groups().search( chatroom_element)[0] #print(search_name) if search_name: search_name.send(text_send) fromChatroom = True message = "Python→" + search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom, message, send_time) else: self.output_info("找不到该群聊!") # 选择要发送的文件 def open_file(self): file_name = QtWidgets.QFileDialog.getOpenFileName( self, "选取文件", ".", "All Files (*)")[0] self.lineEdit_file_dir.setText(file_name) self.lineEdit_file_dir_1.setText(file_name) # 发送文件给谁 def file_to_who(self, somebody): file_send = self.lineEdit_file_dir.text() send_OK = False # 是否发送成功 try: if imghdr.what(file_send): # 判断文件是否是图片格式 somebody.send_image(file_send) else: somebody.send_file(file_send) send_OK = True except: self.output_info("发送文件失败!请检查文件的路径!") #wxpy 发送文件失败,升级itchat就能解决 return send_OK # 发送文件到助手 def file_to_helper(self): file_helper = self.thread.bot.file_helper send_OK = self.file_to_who(file_helper) if send_OK: fromChatroom = False # 做个记号,不是群聊 message = "Python→助手:成功发送文件!" # 编辑聊天记录内容 send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 # 发送文件到好友 def file_to_friend(self): file_friends = self.friends_clicked() if len(file_friends) == 0: self.output_send("您还没有选择好友!") else: for friend in file_friends: search_name = self.thread.bot.friends().search(friend)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: fromChatroom = False # 做个记号,不是群聊 message = "Python→" + search_name.name + ':成功发送文件!' send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 else: self.output_send("找不到该好友!") # 发送文件到群聊 def file_to_chatroom(self): file_chatrooms = self.chatrooms_clicked() if len(file_chatrooms) == 0: self.output_send("您还没有选择群聊!") else: for chatroom in file_chatrooms: search_name = self.thread.bot.groups().search(chatroom)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: fromChatroom = True # 做个记号,不是群聊 message = "Python→" + search_name.name + ':成功发送文件!' send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 else: self.output_send("找不到该群聊!")
from flask import current_app from wxpy import Tuling from wxpy.api.consts import TEXT description = """ 图灵机器人,触发条件: @群主 即可 """ try: from config import TULING_KEY except: TULING_KEY = '5194eb3277ec4a86b404695f8f991706' tuling = Tuling(api_key=TULING_KEY) class TulingPlugin: name = 'TulingPlugin' version = '0.1' msg_types = TEXT description = description @classmethod def main(cls, msg): nick_name = current_app.nick_name if current_app else None if nick_name is not None: at = '@{}'.format(nick_name) text = msg.text if at in text: msg.text = text.replace(at, '').replace('\u2005', '').strip() tuling.do_reply(msg)
# -*- coding: utf-8 -*- """ Created on Tue Mar 13 19:09:05 2018 @author: Snailclimb @description使用图灵机器人自动与指定好友聊天 """ from wxpy import Bot, Tuling, embed, ensure_one bot = Bot() my_friend = ensure_one(bot.search('郑凯')) #想和机器人聊天的好友的备注 tuling = Tuling(api_key='72bce33cb2b248a199d07175225a5264') @bot.register(my_friend) # 使用图灵机器人自动与指定好友聊天 def reply_my_friend(msg): tuling.do_reply(msg) embed()
class MyWindow(QtWidgets.QWidget,Ui_Form): # 注意Ui_Form要跟UI文件中的匹配 def __init__(self): super(MyWindow, self).__init__() self.setupUi(self) QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Fusion')) # 风格 self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint) # 右上角只有关闭按钮 # 初始化标签、文本框提示,禁用不需要输入的文本框 self.output_info("请点击左侧的“扫码登录”按钮!") self.lineEdit_busy.setText("您好,我现在忙,不方便回复您!有事请留言![微笑]") self.lineEdit_text_friend.setEnabled(False) self.lineEdit_text_chatroom.setEnabled(False) self.lineEdit_file_dir.setEnabled(False) self.lineEdit_file_friend.setEnabled(False) self.lineEdit_file_chatroom.setEnabled(False) # tabWidget切换,联动toolBox self.tabWidget.currentChanged['int'].connect(self.toolBox.setCurrentIndex) # 按钮 self.pushButton_login.clicked.connect(self.login) self.pushButton_logout.clicked.connect(self.logout) self.pushButton_text_helper.clicked.connect(self.text_to_helper) self.pushButton_text_friend.clicked.connect(self.text_to_friend) self.pushButton_text_chatroom.clicked.connect(self.text_to_chatroom) self.pushButton_open_file.clicked.connect(self.open_file) self.pushButton_file_helper.clicked.connect(self.file_to_helper) self.pushButton_file_friend.clicked.connect(self.file_to_friend) self.pushButton_file_chatroom.clicked.connect(self.file_to_chatroom) # 复选框 self.checkBox_remote.setChecked(True) # 默认勾选 self.checkBox_busy.stateChanged.connect(self.check_busy) self.checkBox_robot.stateChanged.connect(self.check_robot) self.checkBox_remote.stateChanged.connect(self.check_remote) # 登陆微信前,使按钮失效 #self.pushButton_logout.setEnabled(False) self.pushButton_text_helper.setEnabled(False) self.pushButton_text_friend.setEnabled(False) self.pushButton_text_chatroom.setEnabled(False) self.pushButton_open_file.setEnabled(False) self.pushButton_file_helper.setEnabled(False) self.pushButton_file_friend.setEnabled(False) self.pushButton_file_chatroom.setEnabled(False) # 提示信息 text_help = '\n' text_help += '========== ★ 感谢使用 MineWechat V3.5.4 ★ ========== By Jenas\n\n' text_help += '1. 作者是初学者,程序尚有很多Bug,请多包涵,欢迎反馈!\n\n' text_help += '2. 好友、群聊列表支持 Ctrl、Shift 多选,双击清空选择。\n\n' text_help += '3. 获取微信远控指令:手机微信编辑“#帮助”发送至“文件传输助手”。\n\n' text_help += '4. 发送文件的文件名不可以是中文,但路径可以是中文。\n\n' text_help += '5. 锁定屏幕会导致部分功能失效,所以,挂机的话请关闭睡眠和锁屏。\n\n' text_help += '6. 想起来再补……' self.textEdit_help.setText(text_help) ############################################################################################ # 包含:登陆、注销、系统信息、好友列表 ############################################################################################ # 获取当前时间戳,并转格式,外面再套上方括号,就像这样:[18/09/17 18:12:38] def get_now_time(self): now_time = time.strftime("%y/%m/%d %H:%M:%S") time_msg = '[%s]' % now_time return time_msg # 记录底部的系统信息 def output_info(self,info): time_msg = self.get_now_time() self.textEdit_output.append(time_msg+' '+info) # 登陆按钮 def login(self): self.thread = MyThread() # 创建线程 # 线程的信号槽,依次关联:写微信聊天记录、写系统信息、写微信远控信息、更新好友列表、更新群聊列表 self.thread._signal_1.connect(self.write_log) self.thread._signal_2.connect(self.output_info) self.thread._signal_3.connect(self.output_remote_info) self.thread._signal_4.connect(self.update_friends) self.thread._signal_5.connect(self.update_chatrooms) self.thread.start() # 开始线程 # 注销退出按钮 def logout(self): myshow.thread.bot.logout() time.sleep(1) quitApp() # UI按钮启用,更新好友列表时顺带调用 def ui_enabled(self): self.pushButton_login.setEnabled(False) self.pushButton_logout.setEnabled(True) self.pushButton_text_helper.setEnabled(True) self.pushButton_text_friend.setEnabled(True) self.pushButton_text_chatroom.setEnabled(True) self.pushButton_open_file.setEnabled(True) self.pushButton_file_helper.setEnabled(True) self.pushButton_file_friend.setEnabled(True) self.pushButton_file_chatroom.setEnabled(True) # 左侧好友列表 def update_friends(self,friends_list): self.ui_enabled() # 启用ui按钮 self.slm_1 = QtCore.QStringListModel() # 实例化列表模型 self.qList_1 = friends_list self.slm_1.setStringList(self.qList_1) # 加载数据列表 self.listView_friend.setModel(self.slm_1) # 设置列表视图的模型 self.listView_friend.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_friend.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) # 不能对表格进行修改(双击重命名等) self.listView_friend.clicked.connect(self.friends_clicked) self.listView_friend.doubleClicked.connect(self.listView_friend.clearSelection) # 点击左侧好友列表 def friends_clicked(self): friends_clicked_name = '' friends_clicked_list = [] for i in self.listView_friend.selectedIndexes(): friend_Name = i.data() friends_clicked_name += friend_Name + ',' friend_NickName = friend_Name.split('[')[0] friends_clicked_list.append(friend_NickName) num =len(friends_clicked_list) friends_num = friends_clicked_name + '共计['+str(num)+']人' self.lineEdit_text_friend.setText(friends_num) self.lineEdit_file_friend.setText(friends_num) return friends_clicked_list # 左侧群聊列表 def update_chatrooms(self,chatrooms_list): self.slm_2 = QtCore.QStringListModel() # 实例化列表模型 self.qList_2 = chatrooms_list self.slm_2.setStringList(self.qList_2) # 加载数据列表 self.listView_chatroom.setModel(self.slm_2) # 设置列表视图的模型 self.listView_chatroom.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_chatroom.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) # 禁止对列表修改(双击重命名) self.listView_chatroom.clicked.connect(self.chatrooms_clicked) self.listView_chatroom.doubleClicked.connect(self.listView_chatroom.clearSelection) # 点击左侧群聊列表 def chatrooms_clicked(self): chatrooms_clicked_name = '' chatrooms_clicked_list = [] for i in self.listView_chatroom.selectedIndexes(): chatroom_Name = i.data() chatrooms_clicked_name += chatroom_Name + ',' chatrooms_clicked_list.append(chatroom_Name) num = len(chatrooms_clicked_list) chatrooms_num = chatrooms_clicked_name+'共计['+str(num)+']个群' self.lineEdit_text_chatroom.setText(chatrooms_num) self.lineEdit_file_chatroom.setText(chatrooms_num) return chatrooms_clicked_list ############################################################################### # 功能选项,及远控信息 ############################################################################### # 微信忙碌回复功能开关 def check_busy(self): check_state = self.checkBox_busy.checkState() #print(check_state) global reply_busy if check_state == QtCore.Qt.Checked: self.output_info('已打开[忙碌回复]功能') reply_busy =True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[忙碌回复]功能') reply_busy = False # 微信机器人回复功能开关 def check_robot(self): check_state = self.checkBox_robot.checkState() #print(check_state) global reply_robot if check_state == QtCore.Qt.Checked: self.output_info('已打开[机器人回复]功能') reply_robot =True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[机器人回复]功能') reply_robot = False # 调用图灵机器人的api,利用爬虫,根据聊天消息返回回复内容 tuling = Tuling(api_key='9489eda6f3704a65b0221a3f65e0b98b') # wxpy整合了图灵机器人 # 微信远程控制功能开关 def check_remote(self): check_state = self.checkBox_remote.checkState() #print(check_state) global remote_pc if check_state == QtCore.Qt.Checked: self.output_info('已打开[微信远控]功能') remote_pc = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[微信远控]功能') remote_pc = False # 记录远程控制相关信息 def output_remote_info(self,message): time_msg = self.get_now_time() self.textEdit_remote.append(time_msg+' '+message) ####################################################################################### # 微信发送文字、文件 ####################################################################################### # 记录聊天信息,包含:发送信息、接收信息 # 参数:是否群聊,消息内容,消息时间, 依次类型: bool,str,int def write_log(self,fromChatroom,message,send_time,): myTime = time.strftime("%m-%d %H:%M:%S", time.localtime(send_time)) # "%Y/%m/%d %H:%M:%S" msg_data = '['+myTime+'] '+message if fromChatroom == False : self.textEdit_friend_record.append(msg_data) else: self.textEdit_chatroom_record.append(msg_data) # 发送文字到助手 def text_to_helper(self): text_send = self.textEdit_text_friend.toPlainText() self.thread.bot.file_helper.send(text_send) #self.output_info("成功发送文字至:文件传输助手") fromChatroom = False # 做个记号,不是群聊 message = "Python→助手:" + text_send # 编辑聊天记录内容 send_time = time.time() # 获取当前时间 self.write_log(fromChatroom,message, send_time) # 写聊天记录 # 发送文字到好友 def text_to_friend(self): text_send = self.textEdit_text_friend.toPlainText() text_friends = self.friends_clicked() #print(text_friends) if len(text_friends) == 0: # 没有勾选,列表空 self.output_info("您还没有选择好友!") else: for friend in text_friends: search_name = self.thread.bot.friends().search(friend)[0] #print(search_name) if search_name: search_name.send(text_send) #self.output_info("成功发送文字至好友:%s" % search_name.name) fromChatroom = False message = "Python→"+ search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom,message,send_time) else: self.output_info("找不到该好友!") # 发送文字到群聊 def text_to_chatroom(self): text_send = self.textEdit_text_chatroom.toPlainText() text_chatrooms = self.chatrooms_clicked() if len(text_chatrooms) == 0: self.output_info("您还没有选择群聊!") else: for chatroom in text_chatrooms: search_name = self.thread.bot.groups().search(chatroom)[0] #print(search_name) if search_name: search_name.send(text_send) #self.output_info("成功发送文字至群聊:%s" % search_name.name) fromChatroom = True message = "Python→" + search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom,message, send_time) else: self.output_info("找不到该群聊!") # 记录发送文件的信息 def output_send(self,info): time_msg = self.get_now_time() self.textEdit_send_record.append(time_msg +' '+info) # 选择要发送的文件 def open_file(self): file_name = QtWidgets.QFileDialog.getOpenFileName(self,"选取文件",".","All Files (*)")[0] self.lineEdit_file_dir.setText(file_name) # 发送文件给谁 def file_to_who(self,file_name): file_send = self.lineEdit_file_dir.text() send_OK = False # 是否发送成功 try: if imghdr.what(file_send): # 判断文件是否是图片格式 file_name.send_image(file_send) else: file_name.send_file(file_send) send_OK = True except: self.output_send("发送文件失败!请检查文件的路径!") # wxpy发送文件失败,升级itchat就能解决 return send_OK # 发送文件到助手 def file_to_helper(self): file_helper = self.thread.bot.file_helper send_OK = self.file_to_who(file_helper) if send_OK: self.output_send("成功发送文件至:文件传输助手") # 发送文件到好友 def file_to_friend(self): file_friends = self.friends_clicked() if len(file_friends) == 0: self.output_send("您还没有选择好友!") else: for friend in file_friends: search_name = self.thread.bot.friends().search(friend)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: self.output_send("成功发送文件至好友:%s" % search_name.name) else: self.output_send("找不到该好友!") # 发送文件到群聊 def file_to_chatroom(self): file_chatrooms = self.chatrooms_clicked() if len(file_chatrooms) == 0: self.output_send("您还没有选择群聊!") else: for chatroom in file_chatrooms: search_name = self.thread.bot.groups().search(chatroom)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: self.output_send("成功发送文件至群聊:%s" % search_name.name) else: self.output_send("找不到该群聊!")
class MyWindow(QtWidgets.QWidget, Ui_Form): # 注意Ui_Form要跟UI文件中的匹配 def __init__(self): super(MyWindow, self).__init__() self.setupUi(self) #QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Fusion')) # 风格 #self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint) # 右上角只有关闭按钮 self.setWindowFlags(QtCore.Qt.FramelessWindowHint) # 没有标题栏 self.setWindowOpacity(0.95) # 透明 # 初始化标签、文本框提示,禁用不需要输入的文本框 self.output_info("请点击左侧的“扫码登录”按钮!") self.lineEdit_busy.setText("您好,我现在忙,不方便回复您!有事请留言![微笑]") self.lineEdit_file_dir.setEnabled(False) self.lineEdit_file_dir_1.setEnabled(False) # 点击button联动stackedWidget对应页面 self.toolButton_11friend.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(0)) self.toolButton_11friend.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(0)) self.toolButton_12chatroom.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(1)) self.toolButton_12chatroom.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(1)) # 更多功能中,还对应三个按钮 self.toolButton_13more.clicked.connect( lambda: self.stackedWidget_1.setCurrentIndex(2)) #self.toolButton_13more.clicked.connect(lambda: self.stackedWidget_2.setCurrentIndex(3)) def btn_more_clicked(): if self.toolButton_21remote.isChecked(): #print('按钮的isChecked返回True/False') self.stackedWidget_2.setCurrentIndex(2) if self.toolButton_22reply.isChecked(): self.stackedWidget_2.setCurrentIndex(3) elif self.toolButton_23help.isChecked(): self.stackedWidget_2.setCurrentIndex(4) else: self.stackedWidget_2.setCurrentIndex(2) self.toolButton_13more.clicked.connect(btn_more_clicked) self.toolButton_21remote.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(2)) self.toolButton_22reply.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(3)) self.toolButton_23help.clicked.connect( lambda: self.stackedWidget_2.setCurrentIndex(4)) # 按钮 self.toolButton_18login.clicked.connect(self.login) self.toolButton_19logout.clicked.connect(self.logout) self.toolButton_search.clicked.connect( lambda: self.lineEdit_search.setText("该功能尚未启用!")) self.pushButton_text_helper.clicked.connect(self.text_to_helper) self.pushButton_text_friend.clicked.connect(self.text_to_friend) self.pushButton_text_chatroom.clicked.connect(self.text_to_chatroom) self.pushButton_open_file.clicked.connect(self.open_file) self.pushButton_open_file_1.clicked.connect(self.open_file) self.pushButton_file_helper.clicked.connect(self.file_to_helper) self.pushButton_file_friend.clicked.connect(self.file_to_friend) self.pushButton_file_chatroom.clicked.connect(self.file_to_chatroom) # 复选框 self.checkBox_remote.setChecked(True) # 默认勾选 self.checkBox_busy.stateChanged.connect(self.check_busy) self.checkBox_robot.stateChanged.connect(self.check_robot) self.checkBox_remote.stateChanged.connect(self.check_remote) # 登陆微信前,使按钮失效 #self.toolButton_19logout.setEnabled(False) self.pushButton_text_helper.setEnabled(False) self.pushButton_text_friend.setEnabled(False) self.pushButton_text_chatroom.setEnabled(False) self.pushButton_open_file.setEnabled(False) self.pushButton_open_file_1.setEnabled(False) self.pushButton_file_helper.setEnabled(False) self.pushButton_file_friend.setEnabled(False) self.pushButton_file_chatroom.setEnabled(False) # 提示信息 text_help = '\n' text_help += '========== ★ 感谢使用 MineWechat V4.0 ★ ========== By Jenas\n\n' text_help += '1. 作者是初学者,程序尚有很多Bug,请多包涵,欢迎反馈!\n\n' text_help += '2. 好友、群聊列表支持 Ctrl、Shift 多选,双击清空选择。\n\n' text_help += '3. 获取微信远控指令:手机微信编辑“#帮助”发送至“文件传输助手”。\n\n' text_help += '4. 发送文件的文件名不可以是中文,但路径可以是中文。\n\n' text_help += '5. 锁定屏幕会导致部分功能失效,所以,挂机的话请关闭睡眠和锁屏。\n\n' text_help += '6. 想起来再补……' self.textEdit_help.setText(text_help) # 按住鼠标,拖动窗口 def mousePressEvent(self, event): if event.button() == QtCore.Qt.LeftButton: self.m_flag = True self.m_Position = event.globalPos() - self.pos() # 获取鼠标相对窗口的位置 event.accept() self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor)) # 更改鼠标图标 def mouseMoveEvent(self, QMouseEvent): if QtCore.Qt.LeftButton and self.m_flag: self.move(QMouseEvent.globalPos() - self.m_Position) # 更改窗口位置 QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_flag = False self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) ############################################################################################ # 包含:登陆、注销、系统信息、好友列表 ############################################################################################ # 获取当前时间戳,并转格式,外面再套上方括号,就像这样:[18/09/17 18:12:38] def get_now_time(self): now_time = time.strftime("%m-%d %H:%M:%S") time_msg = '[%s]' % now_time return time_msg # 记录底部的系统信息 def output_info(self, info): time_msg = self.get_now_time() self.textEdit_output.append(time_msg + ' ' + info) # 登陆按钮 def login(self): self.thread = MyThread() # 创建线程 # 线程的信号槽,依次关联:写微信聊天记录、写系统信息、写微信远控信息、更新好友列表、更新群聊列表 self.thread._signal_1.connect(self.write_log) #self.thread._signal_2.connect(self.output_info) self.thread._signal_2.connect(self.get_username) self.thread._signal_3.connect(self.output_remote_info) self.thread._signal_4.connect(self.update_friends) self.thread._signal_5.connect(self.update_chatrooms) self.thread.start() # 开始线程 # 注销退出按钮 def logout(self): # myshow.thread.bot.logout() # time.sleep(0.2) quitApp() #底部托盘的方法 # 用户名 def get_username(self, username): self.username = username self.label_name.setText(self.username) self.output_info('登录成功,%s,欢迎使用!' % self.username) # UI按钮启用,更新好友列表时顺带调用 def ui_enabled(self): self.toolButton_18login.setEnabled(False) self.toolButton_19logout.setEnabled(True) self.pushButton_text_helper.setEnabled(True) self.pushButton_text_friend.setEnabled(True) self.pushButton_text_chatroom.setEnabled(True) self.pushButton_open_file.setEnabled(True) self.pushButton_open_file_1.setEnabled(True) self.pushButton_file_helper.setEnabled(True) self.pushButton_file_friend.setEnabled(True) self.pushButton_file_chatroom.setEnabled(True) # 左侧好友列表 def update_friends(self, friends_list): self.ui_enabled() # 启用ui按钮 self.slm_1 = QtCore.QStringListModel() # 实例化列表模型 self.qList_1 = friends_list self.slm_1.setStringList(self.qList_1) # 加载数据列表 self.listView_friend.setModel(self.slm_1) # 设置列表视图的模型 self.listView_friend.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_friend.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) # 不能对表格进行修改(双击重命名等) self.listView_friend.clicked.connect(self.friends_clicked) self.listView_friend.doubleClicked.connect( self.listView_friend.clearSelection) # 点击左侧好友列表 def friends_clicked(self): friends_clicked_name = '' friends_clicked_list = [] for i in self.listView_friend.selectedIndexes(): friend_Name = i.data() friends_clicked_name += friend_Name + ' ' friends_clicked_list.append(friend_Name) num = len(friends_clicked_list) if num > 1: friends_num = friends_clicked_name + '共计[' + str(num) + ']人' self.label_text_friend.setStyleSheet( "QLabel#label_text_friend{font: 10pt;}") else: friends_num = friends_clicked_name self.label_text_friend.setStyleSheet( "QLabel#label_text_friend{font: 16pt;}") self.label_text_friend.setText(friends_num) return friends_clicked_list # 左侧群聊列表 def update_chatrooms(self, chatrooms_list): self.slm_2 = QtCore.QStringListModel() # 实例化列表模型 self.qList_2 = chatrooms_list self.slm_2.setStringList(self.qList_2) # 加载数据列表 self.listView_chatroom.setModel(self.slm_2) # 设置列表视图的模型 self.listView_chatroom.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) # 多选列表 self.listView_chatroom.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) # 禁止对列表修改(双击重命名) self.listView_chatroom.clicked.connect(self.chatrooms_clicked) self.listView_chatroom.doubleClicked.connect( self.listView_chatroom.clearSelection) # 点击左侧群聊列表 def chatrooms_clicked(self): chatrooms_clicked_name = '' chatrooms_clicked_list = [] for i in self.listView_chatroom.selectedIndexes(): chatroom_Name = i.data() chatrooms_clicked_name += chatroom_Name + ' ' chatrooms_clicked_list.append(chatroom_Name) num = len(chatrooms_clicked_list) if num > 1: chatrooms_num = chatrooms_clicked_name + '共计[' + str(num) + ']个群' self.label_text_chatroom.setStyleSheet( "QLabel#label_text_chatroom{font: 10pt;}") else: chatrooms_num = chatrooms_clicked_name self.label_text_chatroom.setStyleSheet( "QLabel#label_text_chatroom{font: 16pt;}") self.label_text_chatroom.setText(chatrooms_num) return chatrooms_clicked_list ############################################################################### # 功能选项,及远控信息 ############################################################################### # 微信忙碌回复功能开关 def check_busy(self): check_state = self.checkBox_busy.checkState() #print(check_state) global reply_busy if check_state == QtCore.Qt.Checked: self.output_info('已打开[忙碌回复]功能') reply_busy = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[忙碌回复]功能') reply_busy = False # 微信机器人回复功能开关 def check_robot(self): check_state = self.checkBox_robot.checkState() #print(check_state) global reply_robot if check_state == QtCore.Qt.Checked: self.output_info('已打开[机器人回复]功能') reply_robot = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[机器人回复]功能') reply_robot = False # 调用图灵机器人的api,利用爬虫,根据聊天消息返回回复内容 tuling = Tuling(api_key='9489eda6f3704a65b0221a3f65e0b98b') # wxpy整合了图灵机器人 # 微信远程控制功能开关 def check_remote(self): check_state = self.checkBox_remote.checkState() #print(check_state) global remote_pc if check_state == QtCore.Qt.Checked: self.output_info('已打开[微信远控]功能') remote_pc = True elif check_state == QtCore.Qt.Unchecked: self.output_info('已关闭[微信远控]功能') remote_pc = False # 记录远程控制相关信息 def output_remote_info(self, message): time_msg = self.get_now_time() self.textEdit_remote.append(time_msg + ' ' + message) ####################################################################################### # 微信发送文字、文件 ####################################################################################### # 记录聊天信息,包含:发送信息、接收信息 # 参数:是否群聊,消息内容,消息时间, 依次类型: bool,str,int def write_log(self, fromChatroom, message, send_time): myTime = time.strftime(r"%m-%d %H:%M:%S", time.localtime(send_time)) msg_data = '[' + myTime + '] ' + message if fromChatroom == False: self.textEdit_friend_record.append(msg_data) else: self.textEdit_chatroom_record.append(msg_data) # 发送文字到助手 def text_to_helper(self): text_send = self.textEdit_text_friend.toPlainText() self.thread.bot.file_helper.send(text_send) fromChatroom = False # 做个记号,不是群聊 message = "Python→助手:" + text_send # 编辑聊天记录内容 send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 # 发送文字到好友 def text_to_friend(self): text_send = self.textEdit_text_friend.toPlainText() text_friends = self.friends_clicked() #print(text_friends) if len(text_friends) == 0: # 没有勾选,列表空 self.output_info("您还没有选择好友!") else: for friend_element in text_friends: search_name = self.thread.bot.friends().search( friend_element)[0] #print(search_name) if search_name: search_name.send(text_send) fromChatroom = False message = "Python→" + search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom, message, send_time) else: self.output_info("找不到该好友!") # 发送文字到群聊 def text_to_chatroom(self): text_send = self.textEdit_text_chatroom.toPlainText() text_chatrooms = self.chatrooms_clicked() if len(text_chatrooms) == 0: self.output_info("您还没有选择群聊!") else: for chatroom_element in text_chatrooms: search_name = self.thread.bot.groups().search( chatroom_element)[0] #print(search_name) if search_name: search_name.send(text_send) fromChatroom = True message = "Python→" + search_name.name + ':' + text_send send_time = time.time() self.write_log(fromChatroom, message, send_time) else: self.output_info("找不到该群聊!") # 选择要发送的文件 def open_file(self): file_name = QtWidgets.QFileDialog.getOpenFileName( self, "选取文件", ".", "All Files (*)")[0] self.lineEdit_file_dir.setText(file_name) self.lineEdit_file_dir_1.setText(file_name) # 发送文件给谁 def file_to_who(self, file_name): file_send = self.lineEdit_file_dir.text() send_OK = False # 是否发送成功 try: if imghdr.what(file_send): # 判断文件是否是图片格式 file_name.send_image(file_send) else: file_name.send_file(file_send) send_OK = True except: self.output_info("发送文件失败!请检查文件的路径!") #wxpy 发送文件失败,升级itchat就能解决 return send_OK # 发送文件到助手 def file_to_helper(self): file_helper = self.thread.bot.file_helper send_OK = self.file_to_who(file_helper) if send_OK: fromChatroom = False # 做个记号,不是群聊 message = "Python→助手:成功发送文件!" # 编辑聊天记录内容 send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 # 发送文件到好友 def file_to_friend(self): file_friends = self.friends_clicked() if len(file_friends) == 0: self.output_send("您还没有选择好友!") else: for friend in file_friends: search_name = self.thread.bot.friends().search(friend)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: fromChatroom = False # 做个记号,不是群聊 message = "Python→" + search_name.name + ':成功发送文件!' send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 else: self.output_send("找不到该好友!") # 发送文件到群聊 def file_to_chatroom(self): file_chatrooms = self.chatrooms_clicked() if len(file_chatrooms) == 0: self.output_send("您还没有选择群聊!") else: for chatroom in file_chatrooms: search_name = self.thread.bot.groups().search(chatroom)[0] #print(search_name) if search_name: send_OK = self.file_to_who(search_name) if send_OK: fromChatroom = True # 做个记号,不是群聊 message = "Python→" + search_name.name + ':成功发送文件!' send_time = time.time() # 获取当前时间 self.write_log(fromChatroom, message, send_time) # 写聊天记录 else: self.output_send("找不到该群聊!")
from wxpy import Bot, Tuling, embed, ensure_one bot = Bot(cache_path=True) # 想和机器人聊天的好友的备注 # my_friend = ensure_one(bot.search('Say Hello')) # 记得把名字改成想用机器人的群 my_group = bot.groups().search('chatbot')[0] tuling = Tuling(api_key='29fcb3f764504aea9301df5630ed52dd') # 使用图灵机器人自动与指定好友聊天 @bot.register(my_group, except_self=False) def reply_my_friend(msg): tuling.do_reply(msg) embed()
class Replier(object): """消息回复""" level_map = { 1: "隔壁村的幼稚鬼", 2: "村子里的弟中弟", 3: "村民中的初学者", 4: "村子里的高中生", 5: "合格的成年村民", } q_a_list = { "生日": ["杨超越的生日是什么时候 a)7月31 b)7月29 c)7月28", "a"], "演艺": ["杨超越获得了哪年的演艺人物奖?a)2017 b)2018 c)2019", "b"], "主食": ["杨超越最新欢的主食是?a)土豆 b)米饭 c)燕麦片", "b"] } jokes = [ '''美国外交代表团到苏联访问,苏修接待官员陪他们参观“建设的伟大成就”,并且得意的说:“到了下一个五年计划,每个苏联家庭都可以拥有一架私人飞机!”\n美国人惊讶的问:“ 他们要飞机干什么呢?”\n苏修官员说:“当然有用啊……譬如你在莫斯科听说列宁格勒开始供应面包了,你可以马上开飞机赶去排队啊。''', '''斯大林、赫鲁晓夫和勃列日涅夫乘坐火车出门。开着开着,火车突然停了。\n斯大林把头伸出车窗外,怒吼道:“枪毙火车司机!”可是车还是没有动。\n接着赫鲁晓夫说:“给火车司机恢复名誉!”车仍然没有动。\n勃列日涅夫说:“同志们,不如拉上窗帘,坐在座位上自己摇动身体,做出列车还在前进的样子……”''', '''美术馆里有一幅描写亚当和夏娃的画。\n一个英国人看了,说:“他们一定是英国人,男士有好吃的东西就和女士分享。\n一个法国人看了,说:“他们一定是法国人,情侣裸体散步。\n一个苏联人看了,说:“他们一定是苏联人,他们没有衣服,吃得很少,却还以为自己在天堂!''', '''杨村制度的优越性在哪里?\n成功克服了其他制度里不存在的问题。''', '''黑子:哈哈哈,杨超越这么重要的场合居然口误?\n路人:什么场合?\n黑子:不知道?\n路人:那你看了这么久的视频在看什么?\n黑子:在看杨超越!''' ] def __init__(self, bot): # self.group = group self.api_key = api_key self.log = Logger() self.ycy = YcyReplier() self.tuling = Tuling(api_key=TULING_KEY) self.user = User() self.group = Group() self.rsp_game_player_map = {} self.bot = bot self.draw_lots_game = DrawLots() self.real_estate = RealEstate() self.user_lots_map = {} self.user_lots_read_map = {} self.answer = "" self.red_bag_num = 0 ''' 开启每日定时器,每日零时清空抽签内容 ''' self.scheduler = BackgroundScheduler() self.scheduler.add_job(self.init_lots_map, 'cron', hour='0') self.scheduler.start() def init_lots_map(self): """ 清空抽签内容,可以重新开始抽签 """ self.user_lots_map = {} self.user_lots_read_map = {} self.log.info("=== Init Lots ===") def random_img(self, msg) -> tuple: """ 随机获取图片 :return: """ print("===天降超越===") print(msg.text) if "天降超越" in msg.text or "天将超越" in msg.text: # todo 待增加 list_dir = os.listdir(os.path.join('resources', 'pics')) path = choice(list_dir) self.log.info('choose:-->{}'.format(path)) self.log.debug(os.path.join('resources', 'pics', path)) return 'img', os.path.join('resources', 'pics', path), '' return empty_result def robot_init(self, msg) -> tuple: """ 机器人初始化 :param msg: :return: """ real_msg = msg.text.split() if msg.member.puid == self.group.admin_puid and len( real_msg) != 1: # 如果是管理员 if real_msg[len(real_msg) - 1] == "初始化": self.log.info(msg.sender) # self.group.update_group(msg.sender, self.api_key) self.user.update_users(msg.sender, self.api_key) self.log.info("初始化完成!") return 'text', "初始化完成!", '' elif real_msg[1] == "口令红包": self.log.info("设置口令红包!") print("===口令红包信息===") print(real_msg[2]) print(real_msg[3]) try: self.red_bag_num = int(real_msg[2]) except: self.red_bag_num = 0 if real_msg[3] in self.q_a_list: item = self.q_a_list[real_msg[3]] self.answer = item[1] return 'text', item[0], '' else: self.answer = real_msg[3] return 'text', "口令红包设置完成!", '' else: return empty_result return empty_result def update_user_info(self, msg): self.log.info("更新用户信息中……") self.user.update_users(msg.sender, self.api_key) self.log.info("用户信息更新完毕……") def chaoyue_ana(self, msg) -> tuple: """ 超越语录 :return: """ real_msg = msg.text.split() respond_msg = self.ycy.reply_text(real_msg[len(real_msg) - 1]) # 超越语录无需要@ if respond_msg: return 'text', '@' + msg.member.name + ' ' + respond_msg, '' return empty_result def set_group(self, puid): self.group.set_group(puid) def handle_leave_message(self, msg) -> tuple: """ 处理留言 :param msg: :return: """ if "村头留言板" in msg.text: return "text", "@我并回复:「留言:你想说的话」,则可在村头留言板上留下你的留言内容哦", "" is_leave_message = re.search(r'(留言:|留言:)(.*)', msg.text) if is_leave_message: content = is_leave_message.group(2).strip() # 获取第二组内容并去除前后空格 self.log.info('留言内容:{}'.format(content)) status = create_messages( name=msg.member.name, content=content, fans_id=msg.member.puid, ) if status == "ok": return 'text', '@' + msg.member.name + ' ' + "留言成功!点击 {} 可查看你的留言".format( 'http://ahasmarter.com/', ), '' else: return 'text', '@' + msg.member.name + ' ' + "留言失败!稍后再尝试吧", '' return empty_result def get_group_introduction(self, msg) -> tuple: """ 获取群介绍 :param msg: :return: """ real_msg = msg.text.split() if real_msg[len(real_msg) - 1] == "群信息" or real_msg[len(real_msg) - 1] == "群简介": return 'text', self.group.intro, '' return empty_result def finger_guessing_game(self, msg) -> tuple: """ 猜拳游戏 :param msg: :return: """ group_id = msg.member.group.puid # 群组唯一id name = msg.member.name # 玩家名 user_id = msg.member.puid # 玩家id real_msg = msg.text.split() if real_msg[len(real_msg) - 1] == "石头剪刀布" or real_msg[len(real_msg) - 1] == "剪刀石头布" \ or real_msg[len(real_msg) - 1] == "猜拳": self.log.debug('---init猜拳----') # { 群组id : {玩家id: [游戏对象 , 开始游戏的时间, 玩家名]}} self.rsp_game_player_map.update( { group_id: [user_id, RspGame(1), now_to_datetime4(), name], }, ) self.rsp_game_player_map[group_id][1].start(name) # 开始游戏 return 'text', '@' + msg.member.name + \ " 石头剪刀布开始,你先出吧,赢了我有奖励哦(1局定胜)", '' return empty_result def play_game(self, msg) -> tuple: """ 游戏 :param msg: :return: """ if "超越猜拳" in msg.text: return "text", "@我并回复你的出招(比如「剪刀」)就能跟我玩猜拳游戏,赢了我会奖励3积分,输了扣除3积分,如果积分不够则不会进行奖惩", "" real_msg = msg.text.split() if "石头" in real_msg[len(real_msg) - 1] or "剪刀" in real_msg[len(real_msg) - 1] \ or "布" in real_msg[len(real_msg) - 1]: game = RspGame(1) game.start(msg.member.name) cancel, result, pic = game.play(msg) return 'both', pic, result else: return empty_result """ group_id = msg.member.group.puid user_id = msg.member.puid player_map = self.rsp_game_player_map self.log.info(player_map) # 如果字典中包含群组id并且 玩家id在字典中 if player_map.get(group_id): is_overtime = now_to_datetime4() > two_minutes_later(player_map[group_id][2]) self.log.info('游戏是否超时:%s' % is_overtime) if is_overtime: msg = '@' + str(player_map[group_id][3]) + ' 游戏已经超时自动终止了呀!' msg.chat.send_msg(msg) player_map.pop(group_id) # 超时删除群组id对应的字典 if player_map.get(group_id): # 超时可能会pop掉该key,需要重新判断 if user_id not in player_map.get(group_id, []): # 不是玩家的消息,不进行回应 return 'text', '@' + msg.member.name + " 先等等哦,我正在跟@" + \ player_map[group_id][3] + " 玩石头剪刀布", '' else: cancel, result, pic = player_map[group_id][1].play(msg) # 玩游戏 self.log.debug('game result:{} pic:{}'.format(result, pic)) if cancel == 1: player_map.pop(group_id) # 如果游戏结束, 删除群组id对应的字典 return 'both', pic, result typ, content1, content2 = self.finger_guessing_game(msg) # 猜拳游戏 if typ == 'text': return typ, content1, content2 return empty_result""" def red_bag(self, msg) -> tuple: if "口令红包" in msg.text: return "text", "管理员会在某些时间在群里发出超越百科抢答红包,回答正确会得到超越积分,多多留意~", "" real_msg = msg.text.split() if self.red_bag_num == 0: #如果红包剩余数量为 0 self.answer = "" # answer清零 else: print(self.answer) if self.answer == real_msg[1] and msg.is_at: user_puid = msg.member.puid bot_id = self.bot.self.puid result = self.user.transfer(bot_id, user_puid, self.group.puid, 3, self.api_key) self.red_bag_num -= 1 if result["status"] == "success": return 'text', " 口令正确!奖励给" + msg.member.name + " 3 个超越积分!", '' else: return 'text', '红包领完啦!', '' return empty_result def draw_lots(self, msg) -> tuple: if "超越抽签" in msg.text: return "text", "每日0点过后,@我并回复「抽签」,可以抽出你当日的运势签,@我并回复「解签」会解释抽签内容~", "" real_msg = msg.text.split() user_id = msg.member.puid if real_msg[len(real_msg) - 1] == "抽签": if user_id in self.user_lots_map: return 'text', '@' + msg.member.name + ' 今日你的运势签: ' + self.user_lots_map[ user_id], '' else: msg1, msg2 = self.draw_lots_game.play() self.user_lots_map[user_id] = msg1 self.user_lots_read_map[user_id] = msg2 return 'text', '@' + msg.member.name + ' 今日你的运势签: ' + msg1, '' elif real_msg[len(real_msg) - 1] == "解签": if user_id in self.user_lots_read_map: return 'text', '@' + msg.member.name + ' 解签: ' + self.user_lots_read_map[ user_id], '' else: return 'text', '@' + msg.member.name + ' 今日还未进行抽签哦,请@我回复抽签', '' else: return empty_result def reward(self, msg) -> tuple: """ 打赏 :param msg: :return: """ if str.find(msg.text, "打赏") != -1: str_after_dashang = msg.text[str.find(msg.text, "打赏") + 3:].split() to = self.user.find_user_by_name(msg.sender, str_after_dashang[0]) from_puid = msg.member.puid self.log.info(from_puid) self.log.info(to.puid) result = self.user.transfer( from_puid, to.puid, self.group.puid, int(str_after_dashang[1], ), self.api_key, ) if result["status"] == "success": payload = '打赏成功!' + msg.member.name + " 打赏给 " + \ to.name + " " + str_after_dashang[1] + "个超越积分!" return 'text', payload, '' else: return 'text', '打赏失败!', '' return empty_result def integral(self, msg) -> tuple: """ 积分相关 :return: """ real_msg = msg.text.split() if real_msg[len(real_msg) - 1] == "超越积分": msg = "超越积分可以用来干很多好玩的事情,后续推出虚拟房产和虚拟商店,可作为购买力进行交易哦,还支持个人打赏,@我并回复「余额」来查看你的积分总额。" return 'text', msg, '' if real_msg[len(real_msg) - 1] in ["余额", "积分"]: user_puid = msg.member.puid print("想拿余额的puid:") print(user_puid) balance = self.user.get_balance_by_puid(user_puid, self.group.puid) msg = "你有" + str(balance) + "超越积分" return 'text', msg, '' if real_msg[len(real_msg) - 1] == "等级": user_puid = msg.member.puid level = self.user.get_level_by_puid(user_puid, self.group.puid) msg = "你现在是" + str(level) + "级: " + self.level_map[int(level)] return 'text', msg, '' return empty_result def houses(self, msg) -> tuple: """ 房产相关 :return: """ real_msg = msg.text.split() try: if "超越买房" in msg.text: return "text", "超越买房是实验性功能,@我并回复「看房」查看目前「超越大陆」上的房产所有者\n\n"+\ "@我并回复「买房 房产名 价格」可以进行房产购买,例如「@全村的希望 买房 火炉堡 30」\n"+\ "注意!!!你出的价格至少要比当前的价格大 1,才能买房成功 \n" +\ "如果你是房产所有者,@我并回复「房产名 签名:「你要签名的内容」」可进行签名,例如「@全村的希望 火炉堡 签名:靓仔」", "" if real_msg[len(real_msg) - 1] == "看房": print("=== 看房ing ===") msg = self.real_estate.look() return 'text', msg, '' elif re.search(r'(签名:|签名:)(.*)', msg.text): print("=== 签名ing ===") house_name = real_msg[1] print(msg.text) signature = msg.text[msg.text.find("签名") + 3:] print(house_name) print(self.api_key) print(msg.member.puid) print(self.group.puid) print(signature) res = self.real_estate.leave_sig(msg.member.puid, self.group.puid, signature, house_name, self.api_key) print(res) if res["result"] == "success": payload = "你在" + house_name + "上留下了你的签名:" + signature return 'text', payload, '' else: payload = "签名失败!" return 'text', payload, '' elif real_msg[1] == "买房": print("=== 买房ing ===") house_name = real_msg[2] amount = int(real_msg[3]) print(house_name) print(amount) res = self.real_estate.buy_house(msg.member.puid, self.group.puid, house_name, amount, self.api_key) if res["result"] == "success": payload = "买房成功!\n你现在是 " + house_name + " 的领主!" return 'text', payload, '' else: payload = "买房失败!" return 'text', payload, '' return empty_result except: return empty_result def extra(self, msg) -> tuple: """ 额外添加 :param msg: :return: """ real_msg = msg.text.split() if real_msg[len(real_msg) - 1] in ["致谢", "鸣谢"]: return 'text', "感谢「心理医生聪」与「禹sen」,提供超越语录的支持!", '' if real_msg[len(real_msg) - 1] in ["帮助", "?", "?"]: payload = "本 AI 目前支持以下功能: \n" + \ "- 超越积分\n" + \ "- 天降超越\n" + \ "- 超越猜拳\n" + \ "- 村头留言板\n" + \ "- 超越抽签\n" + \ "- 超越接龙\n" + \ "- 口令红包(管理员功能)\n" + \ "- 超越买房" return 'text', payload, '' if real_msg[len(real_msg) - 1] == "投票": payload = "https://ke.qq.com/cates/ccyy/index.html?act_id=1&work_id=29&mmticket= ⬅ 欢迎猛戳链接投票" return 'text', payload, '' if real_msg[len(real_msg) - 1].find("笑话") != -1: payload = choice(self.jokes) return 'text', payload, '' return empty_result def handle_solo_msg(self, msg): """ 处理私聊回复 :param msg: :return: """ friend = msg.sender # 向新的好友发送消息 friend.send('你好呀,我是全村的希望!') friend.send('参与内测看我朋友圈的图片,扫二维码加群') # friend.send_image('group.jpeg') def handle_group_msg(self, msg) -> tuple: """ 处理群组回复消息 :param msg: :return: """ self.log.info('receive: %s' % msg.text) typ, content1, content2 = self.reward(msg) # 打赏可能被@ 也可能不被@ if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.robot_init(msg) # 紧急情况下的初始化 以及口令红包的初始化 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.red_bag(msg) # 口令红包 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.random_img(msg) # 天降超越 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.chaoyue_ana(msg) # 超越语录 if typ: self.log.info(content1) return typ, content1, content2 if msg.is_at: # 如果@到机器人,才进行的回应 typ, content1, content2 = self.play_game( msg) # 玩游戏,高优先级,内部存在拦截其他回复 if typ: self.log.info(content1) user_puid = msg.member.puid bot_id = self.bot.self.puid user_balance = self.user.get_balance_by_puid( user_puid, msg.member.group.puid) bot_balance = self.user.get_balance_by_puid( bot_id, msg.member.group.puid) if user_balance < 3: payload = " 由于你余额不足 3 积分,所以本次游戏没有奖惩哦~" elif bot_balance < 3: payload = " 超越宝宝的钱包瘪了,所以本次游戏没有奖惩哦~" else: if "游戏结束,恭喜你赢了" in content2: from_puid = bot_id print(from_puid) to_puid = user_puid result = self.user.transfer(from_puid, to_puid, self.group.puid, 3, self.api_key) if result["status"] == "success": payload = " 奖励给 " + msg.member.name + " 3 个超越积分!" else: payload = " 但是我没钱啦~" elif "你输了" in content2: from_puid = user_puid to_puid = bot_id result = self.user.transfer(from_puid, to_puid, self.group.puid, 3, self.api_key) if result["status"] == "success": payload = " 扣除 " + msg.member.name + " 3 个超越积分!" else: payload = " 你钱不够,接下来的游戏会没有奖励哦~" else: payload = "" return typ, content1, content2 + payload typ, content1, content2 = self.draw_lots(msg) # 抽签 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.handle_leave_message(msg) # 处理留言请求 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.get_group_introduction(msg) # 群简介 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.integral(msg) # 积分相关 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.houses(msg) # 积分相关 if typ: self.log.info(content1) return typ, content1, content2 typ, content1, content2 = self.extra(msg) # 额外信息 if typ: self.log.info(content1) return typ, content1, content2 tuling_reply = self.tuling.reply_text(msg).replace( "图灵机器人", "超越宝宝").replace("清华大学硕士杨超?", "杨超越最美不允许反驳").replace("你接错了", "我不会接") self.log.info(tuling_reply) return 'text', tuling_reply, '' return empty_result
# 实例化,并登录微信,cache_path=True:缓存,并不需要每次都登录微信 bot = Bot(cache_path=True) # 查找到要使用机器人来聊天的好友 # my_friend = ensure_one(bot.search(u'****')) # friend_name_list = [] # # 获取好友 friends = bot.friends() # # for friend in friends: # friend_name_list.append(friend.name) # 调用图灵机器人API 获取地址:http://www.tuling123.com/ tuling = Tuling(api_key='×××××××××××××××××××××××××××') def handle_info(friend): # 使用图灵机器人自动与所有好友聊天 # @bot.register([my_friend, Group], TEXT) # @bot.register([friend], msg_types=['TEXT', 'RECORDING', 'PICTURE']) @bot.register(friend) def reply_my_friend(msg): tuling.do_reply(msg) bot.join() # 发送消息
from ludaweb.models.applications import Application test_key = "ujr4acjvzXNA" test_sec = "9lghG7BDzv1ggMZ1CkzU" signature_ask = ibotcloud.IBotSignature(app_key=test_key, app_sec=test_sec, uri="/ask.do", http_method="POST") params_ask = ibotcloud.AskParams(platform="custom", user_id="abc", url="http://nlp.xiaoi.com/ask.do", response_format="xml") ask_session = ibotcloud.AskSession(signature_ask, params_ask) tuling = Tuling(api_key='') @app.endpoint('webhook') def mphook(): applist = ['全市通办'] if request.method == 'GET': token = '69b3f633cd9e4136bfdd8be812a34e28' # 微信配置所需的token data = request.args signature = data.get('signature', '') timestamp = data.get('timestamp', '') nonce = data.get('nonce', '') echostr = data.get('echostr', '') s = [timestamp, nonce, token] s.sort() s = ''.join(s).encode()
# -*- coding:utf-8 -*- # -*- coding: utf-8 -*- """ Created on Tue Mar 13 19:09:05 2018 @author: Snailclimb @description使用图灵机器人自动与指定好友聊天 """ from wxpy import Bot, Tuling, embed, ensure_one bot = Bot() my_friend = ensure_one(bot.search('郑凯')) #想和机器人聊天的好友的备注 tuling = Tuling(api_key='你申请的apikey') @bot.register(my_friend) # 使用图灵机器人自动与指定好友聊天 def reply_my_friend(msg): tuling.do_reply(msg) embed() ''' # -*- coding: utf-8 -*- """ Created on Tue Mar 13 18:55:04 2018 @author: Administrator """