def handle_groups_message(msg): """ 处理群消息, :param msg: :return: """ uuid = msg.fromUserName # 群 uid ated_uuid = msg.actualUserName # 艾特你的用户的uuid ated_name = msg.actualNickName # 艾特你的人的群里的名称 text = msg['Text'] # 发送到群里的消息。 conf = config.get('group_helper_conf') if not conf.get('is_open'): return # 自己通过手机端微信发出的消息不作处理 if ated_uuid == config.get('wechat_uuid'): return # 如果开启了 『艾特才回复』,而群用户又没有艾特你。走垃圾分类 if conf.get('is_at') and not msg.isAt: return is_all = conf.get('is_all', False) group_uuids = conf.get('group_name_black_list') if is_all else conf.get( 'group_name_white_list') # 开启回复所有群,而群组是黑名单,不处理消息 if is_all: for group_name in group_uuids: chatrooms = itchat.search_chatrooms(name=f'''{group_name}''') # print(chatrooms) for room in chatrooms: if uuid == room['UserName']: return # 未开启回复所有群,而群组不是白名单,不处理消息 in_white_flag = False if not is_all: for group_name in group_uuids: chatrooms = itchat.search_chatrooms(name=f'''{group_name}''') for room in chatrooms: if uuid == room['UserName']: in_white_flag = True if not in_white_flag: return # 去掉 at 标记 text = re.sub(at_compile, '', text) reply_text = get_auto_reply(text, ated_uuid) # 获取自动回复 if reply_text: # 如内容不为空,回复消息 reply_text = common_msg.format(ated_name=ated_name, text=reply_text) itchat.send(reply_text, uuid) # print('回复{}:{}'.format(ated_name, reply_text)) else: print('自动回复失败\n')
def add_friends_msg(msg): """ 监听添加好友请求 为了自动同意好友请求 """ conf = config.get('auto_reply_info') IS_AUTO_ADD_FRIEND = conf.get('is_auto_add_friend') add_friend_keys = ''.join(conf.get('auto_add_friend_keywords')) note_first_meet_text = '''等你等的好辛苦,很高心您的加入! ''' # 好友成功后的第一句话 add_friend_compile = re.compile('|'.join(i.strip() for i in re.split(r'[,,]+', add_friend_keys) if i), re.I) # 通过关键词同意加好友请求 itchat.get_friends(update=True) # 更新好友数据。 if not IS_AUTO_ADD_FRIEND: # 如果是已关闭添加好友功能,则直接返回 return userid = msg['RecommendInfo']['UserName'] nickname = msg['RecommendInfo']['NickName'] content = msg['RecommendInfo']['Content'] # 获取验证消息 if add_friend_compile.findall(content): time.sleep(random.randint(1, 2)) # 随机休眠(1~3)秒,用于防检测机器人 itchat.add_friend(**msg['Text']) # 同意加好友请求 time.sleep(random.randint(1, 2)) itchat.send(note_first_meet_text, userid) # 给刚交的朋友发送欢迎语句 note = '已添加好友:{}'.format(nickname) set_system_notice(note) else: note = '添加好友失败:用户「{}」 发来的验证消息「{}」。'.format(nickname, content) set_system_notice(note)
def handle_friends_message(msg): """ 处理好友信息 """ try: # 自己通过手机微信发送给别人的消息(文件传输助手除外)不作处理。 if msg['FromUserName'] == config.get( 'wechat_uuid') and msg['ToUserName'] != FILEHELPER: return conf = config.get('auto_reply_info') if not conf.get('is_auto_reply'): return # 获取发送者的用户id uuid = FILEHELPER if msg['ToUserName'] == FILEHELPER else msg[ 'FromUserName'] is_all = conf.get('is_auto_reply_all') auto_uuids = conf.get( 'auto_reply_black_uuids') if is_all else conf.get( 'auto_reply_white_uuids') # 开启回复所有人,当用户是黑名单,不回复消息 if is_all and uuid in auto_uuids: return # 关闭回复所有人,当用户不是白名单,不回复消息 if not is_all and uuid not in auto_uuids: return receive_text = msg.text # 好友发送来的消息内容 # 好友叫啥,用于打印 nick_name = FILEHELPER if uuid == FILEHELPER else msg.user.nickName reply_text = get_auto_reply(receive_text, uuid) # 获取自动回复 if reply_text: # 如内容不为空,回复消息 time.sleep(random.randint(1, 2)) # 休眠一秒,保安全。想更快的,可以直接注释。 prefix = conf.get('auto_reply_prefix', '') # 前缀 if prefix: reply_text = '{}{}'.format(prefix, reply_text) suffix = conf.get('auto_reply_suffix', '') # 后缀 if suffix: reply_text = '{}{}'.format(reply_text, suffix) itchat.send(reply_text, toUserName=uuid) else: set_system_notice( f'''自动回复失败:\n『{nick_name}』发来信息:{receive_text} \n''') except Exception as exception: print(str(exception))
def init_data(): """ 初始化微信所需数据 """ set_system_notice('登录成功') itchat.get_friends(update=True) # 更新好友数据。 itchat.get_chatrooms(update=True) # 更新群聊数据。 conf = config.get('group_helper_conf') group_name_list = conf.get('group_name_white_list') init_chatsroom(group_name_list) init_wechat_config() # 初始化所有配置内容 init_alarm() print('初始化完成,开始正常工作。')
def is_white_group(uuid) -> bool: ''' 判断传入的uuid,是否属于我们的群 :param uuid: :return: ''' helper = config.get('group_helper_conf') auto_uuids = helper.get('group_name_white_list') for auid in auto_uuids: chatrooms = itchat.search_chatrooms(name=auid) print(f'''room: {chatrooms}''') for chat in chatrooms: if chat.UserName == str(uuid): return True return False
def get_nlp_textchat(text, userId): """ 智能闲聊(腾讯)<https://ai.qq.com/product/nlpchat.shtml> 接口文档:<https://ai.qq.com/doc/nlpchat.shtml> :param text: 请求的话 :param userId: 用户标识 :return: str """ try: # config.init() info = config.get('auto_reply_info')['qqnlpchat_conf'] app_id = info['app_id'] app_key = info['app_key'] if not app_id or not app_key: print('app_id 或 app_key 为空,请求失败') return # 产生随机字符串 nonce_str = ''.join( random.sample(string.ascii_letters + string.digits, random.randint(10, 16))) time_stamp = int(time.time()) # 时间戳 params = { 'app_id': app_id, # 应用标识 'time_stamp': time_stamp, # 请求时间戳(秒级) 'nonce_str': nonce_str, # 随机字符串 'session': md5_encode(userId), # 会话标识 'question': text # 用户输入的聊天内容 } # 签名信息 params['sign'] = getReqSign(params, app_key) resp = requests.get(URL, params=params) if resp.status_code == 200: # print(resp.text) content_dict = resp.json() if content_dict['ret'] == 0: data_dict = content_dict['data'] return data_dict['answer'] print('智能闲聊 获取数据失败:{}'.format(content_dict['msg'])) return None except Exception as exception: print(str(exception))
def handle_group_pictures(msg): ''' :return: ''' # 自己通过手机微信发送给别人的消息(文件传输助手除外)不作处理。 if msg['FromUserName'] == config.get('wechat_uuid') and msg['ToUserName'] != FILEHELPER: return # 判断是否来自指定群 uuid = msg.fromUserName # 群 uid # print(f'''这个群聊的id是{uuid}''') # ated_uuid = msg.actualUserName # 发送人的用户uuid # ated_name = msg.actualNickName # 发送人群里的名称 # file_name = msg['FileName'] # 文件默认文件名 msg.download(msg.fileName) if is_white_group(uuid): if QRcode_detection(msg.fileName): itchat.delete_member_from_chatroom(msg.FromUserName, [{'UserName': msg.ActualUserName}]) del_pic(msg.fileName)
def handle_groups_message(msg): """ 处理群消息, :param msg: :return: """ uuid = msg.fromUserName # 群 uid ated_uuid = msg.actualUserName # 艾特你的用户的uuid ated_name = msg.actualNickName # 艾特你的人的群里的名称 # print(msg) # 自己通过手机端微信发出的消息不作处理 if ated_uuid == config.get('wechat_uuid'): return conf = config.get('group_helper_conf') text = msg['Text'] # 发送到群里的消息。 # 如果是我们的群,不是管理组人员发送的消息,且长度大于30,直接踢 # 我们认为 wechat 中一个人的聊天长度不会超过30, # 特别是对于一个优惠券群来说, # 一个可跟你说30个字以上的又如此“谆谆教导”的人值得被踢 # 对于广告,宁可错杀不放过一个,随有极端但不菲是一种办法 # TODO 此处需要文本审核,但市面上的文本审核都付费,如有免费的请及时通知我 group_admins = conf.get('group_admin') if is_white_group(uuid) and (ated_name not in group_admins): if len(str(text)) >= 30: itchat.delete_member_from_chatroom(uuid, [{'UserName': msg.ActualUserName}]) if not conf.get('is_open'): return # 如果开启了 『艾特才回复』,而群用户又没有艾特你。走垃圾分类 if conf.get('is_at') and not msg.isAt: return is_all = conf.get('is_all', False) group_uuids = conf.get('group_name_black_list') if is_all else conf.get('group_name_white_list') # 开启回复所有群,而群组是黑名单,不处理消息 if is_all: for group_name in group_uuids: chatrooms = itchat.search_chatrooms(name=f'''{group_name}''') # print(chatrooms) for room in chatrooms: if uuid == room['UserName']: return # 未开启回复所有群,而群组不是白名单,不处理消息 in_white_flag = False if not is_all: for group_name in group_uuids: chatrooms = itchat.search_chatrooms(name=f'''{group_name}''') for room in chatrooms: if uuid == room['UserName']: in_white_flag = True if not in_white_flag: return # 去掉 at 标记 text = re.sub(at_compile, '', text) reply_text = get_auto_reply(text, ated_uuid) # 获取自动回复 if reply_text: # 如内容不为空,回复消息 reply_text = common_msg.format(ated_name=ated_name, text=reply_text) itchat.send(reply_text, uuid) # print('回复{}:{}'.format(ated_name, reply_text)) else: print('自动回复失败\n')
def log_all_config(): """ 用于打印设置日志 :return: """ print('=' * 80) channel = config.get('auto_reply_info').get('bot_channel', 7) source = 'ownthink_robot' addon = import_module('everyday_wechat.control.bot.' + source, __package__) bot_name = addon.BOT_NAME print('自动回复机器人渠道:{}'.format(bot_name)) # start ----------------------------------- 微信好友自动回复的功能日志 ----------------------------------- start reply = config.get('auto_reply_info', None) if not reply or not reply.get('is_auto_reply'): print('未开启微信好友自动回复。') else: if reply.get('is_auto_reply_all'): auto_uuids = reply.get('auto_reply_black_uuids') nicknames = [] for auid in auto_uuids: if auid == 'filehelper': nicknames.append(auid) else: friends = itchat.search_friends(userName=auid) nickname = friends.nickName nicknames.append(nickname) nns = ','.join(nicknames) print('开启对全部微信好友全部回复,除了:{}'.format(nns)) else: auto_uuids = reply.get('auto_reply_white_uuids') nicknames = [] for auid in auto_uuids: if auid == 'filehelper': nicknames.append(auid) else: friends = itchat.search_friends(userName=auid) nickname = friends.nickName nicknames.append(nickname) nns = ','.join(nicknames) print('对微信好友 {},进行自动回复'.format(nns)) print('=' * 80) # start ----------------------------------- 群功能日志说明 ----------------------------------- start helper = config.get('group_helper_conf') if not helper or not helper.get('is_open'): print('未开启群助手功能。') else: if helper.get('is_all'): auto_uuids = helper.get('group_black_uuids') nicknames = [] for auid in auto_uuids: chatrooms = itchat.search_chatrooms(userName=auid) nickname = chatrooms['NickName'] # 群聊名称 nicknames.append(nickname) nns = ','.join(nicknames) print('已开启对全部微信群的监听,除了群:{}。'.format(nns)) else: auto_uuids = helper.get('group_white_uuids') nicknames = [] for auid in auto_uuids: chatroom = itchat.search_chatrooms(userName=auid) nickname = chatroom['NickName'] # 群聊名称 nicknames.append(nickname) nns = ','.join(nicknames) print('已对微信群:{},开启了群助手功能。'.format(nns)) if helper.get('is_at'): print('只有群里用户@机器人,才会触发群助手功能。') if helper.get('is_auto_reply'): print('已开启对微信群内用户的自动回复。') if helper.get('is_weather'): print('已开启天气查询功能,具体使用方法请输入:“help” 查看。') if helper.get('is_calendar'): print('已开启日志查询功能,具体使用方法请输入:“help” 查看。') if helper.get('is_rubbish'): print('已开启垃圾分类查询功能,具体使用方法请输入:“help” 查看。') if helper.get('is_moviebox'): print('已开启票房查询功能,具体使用方法请输入:“help” 查看。') if helper.get('is_air_quality'): print('已开启空气质量查询功能,具体使用方法请输入:“help” 查看。') print('=' * 80) # start ----------------------------------- 提醒功能的日志说明 ----------------------------------- start alarm = config.get('alarm_info') if not alarm or not alarm.get('is_alarm'): print('未开启每日提醒功能。') else: print('已开启定时发送提醒功能。') alarm_dict = alarm.get('alarm_dict') for value in alarm_dict.values(): nickname_list = value.get('nickname_list') nns = ','.join(nickname_list) # temp_dict = {'hour': hour, 'minute': minute, 'uuid_list': uuid_list, 'nickname_list': nickname_list} hour = value.get('hour') minute = value.get('minute') alarm_time = "{hour:0>2d}:{minute:0>2d}".format(hour=hour, minute=minute) # 计算在哪个区间给朋友发送信息 jitter = value.get("alarm_jitter", 0) if jitter != 0: set_time = datetime.strptime(alarm_time, '%H:%M') jitter_time = timedelta(seconds=jitter) start_time = (set_time - jitter_time).strftime("%H:%M") end_time = (set_time + jitter_time).strftime("%H:%M") alarm_time = "{start_time}——{end_time} 期间".format(start_time=start_time, end_time=end_time) print('定时:{alarm_time},给:{nicknames},发送提醒内容一次。'.format(alarm_time=alarm_time, nicknames=nns)) print('=' * 80)