def get_uin(msg): global JSF, IsSendMsgNow if '朋友验证请求' in msg['Text'] or '对方拒收' in msg['Text']: JSF = JSF + 1 itchat.set_alias(msg['FromUserName'], 'A00000【僵尸粉】%s' % JSF) if '过于频繁' in msg['Text']: IsSendMsgNow = False
def set_alias(self, param=""): refresh = False if param: if param.startswith("-r "): refresh = True param = param[2:] param = param.split(maxsplit=1) if len(param) == 1: cid = param[0] alias = "" else: cid, alias = param else: return self.set_alias.desc if not cid.isdecimal(): return "ID must be integer, \"%s\" given." % cid else: cid = int(cid) l = itchat.get_friends(refresh)[1:] if cid < 0: return "ID must between 0 and %s inclusive, %s given." % (len(l) - 1, cid) if cid >= len(l): return "You may not set alias to a group or a MPS contact." itchat.set_alias(l[cid]['UserName'], alias) if alias: return "Chat \"%s\" is set with alias \"%s\"." % ( l[cid]["NickName"], alias) else: return "Chat \"%s\" has removed its alias." % l[cid]["NickName"]
def add_friend(msg): valify_msg = msg['Text']['autoUpdate'][ 'Content'] # 验证消息格式:auth_code+mid,amid+dmid li = valify_msg.split('+', 1) if len(li) == 2 and check_int(li[0]) and check_int(li[1]): robot_nickname = itchat.search_friends( userName=msg['ToUserName'])['NickName'] d = { "authCode": str(li[0]), "mid": str(li[1]), "robName": robot_nickname } rd = send_post_request_to_java(type=add_friend_request_type, data=d) # result print(rd) if int(rd[success]) == 1: # 成功 itchat.add_friend(userName=msg['RecommendInfo']['UserName'], status=3) # 同意加为好友 add_name = rd[data]['name'] # itchat.send_msg(add_name + ":感谢您加我为好友!" + '我的名字叫:' + robot_nickname, msg['RecommendInfo']['UserName']) itchat.send_msg( '您好;机器人代开房授权成功!欢迎使用牵手开房神器。\n\n' + '按如下操作,即可开通服务;\n' + '1.打开游戏客户端,找到机器人开房配置进行配置\n' + '2.私聊机器人,发送“配置”,即可看到所有的房间类型\n' + '3.根据机器人返回消息提示,完成对该机器人的配置\n' + '4.在群中编辑发送“开心”,即可开房。', msg['RecommendInfo']['UserName']) itchat.set_alias(userName=msg['RecommendInfo']['UserName'], alias="QS_" + str(li[0]) + "_" + str(li[1])) # 修改备注名称 else: print(int(rd[error])) else: print("msg not match !")
def apply_friends(msg): if msg.content.find('十一班') != -1: msg.user.verify() itchat.set_alias(msg.user['UserName'], 'user') itchat.send( '您好,欢迎您使用十一班作业查询机器人!\n我不能保证这个机器人在任何时间都正常工作,\n也不能保证推送的作业准确无误。\n请勿向我频繁发送大量消息!', msg.user['UserName']) wrong_cmd(msg.user['UserName'])
def add_friend(msg): # print('add_friend->NickName:',msg['RecommendInfo']['NickName']) # print('add_friend->UserName:'******'RecommendInfo']['UserName']) # print('add_friend->Alias:',msg['RecommendInfo']['Alias']) # print('FromUserName:'******'FromUserName']) rt = oneshot.register(msg['RecommendInfo']['Alias']) # # print('rt:',rt) if rt == 404: return user_id = rt['id'] itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录 itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName']) # itchat.set_alias(msg['FromUserName'], user_id) itchat.set_alias(msg['RecommendInfo']['UserName'], user_id)
def registe_data(self,contacts,unregist_name_list,available_num_l): """ 为有标注但是无序号的微信好友增加序号 !!Warning: 该方法会修改微信的备注数据,慎用 contacts: 微信获取的好友信息 unregist_name_list: 需要处理的有备注但是没有序号的名称列表 id_num: 可以使用的序号的第一个 """ # 生成指定的序号 # TODO: 这里的序号生成不够通用,另外需要生成的序号也是需要指定的 from random import randint from time import sleep # 构造对应的序号 #for i in range(int(id_num),int(id_num)+100): # s_num.append('z' + str('{0:04}'.format(i))) num_l = [''.join(['z',str('{0:04}'.format(_i))])for _i in available_num_l] # 构造对应的userID userid_list = [] for i in unregist_name_list: for el in contacts[2:]: if el[8] == i: userid_list.append(el[1]) # 进行处理 flag = 0 for i in userid_list: print(i,unregist_name_list[flag]+'.'+num_l[flag]) print(itchat.set_alias(userName=i, alias=unregist_name_list[flag]+'.'+num_l[flag])) flag += 1 sleep(randint(5,15))
def set_alias(msg): log.debug('set_alias ->> msg:%s' % msg) check_code = re.search(r'[0-9]+', msg['Content']).group() if len(check_code) > 6: user_id = check_code[6:] code = check_code[0:6] user_name = botDao.get_user_name(user_id, code) if user_name: itchat.set_alias(msg['FromUserName'], user_name) message = '识别成功' else: message = '识别码错误' else: message = '识别码格式错误' log.debug('set_alias <<- message:%s' % message) return message
def set_alias(user_name, alias): ''' set alias for a friend for options - user_name: 'user_name' key of info dict - alias: new alias it is defined in components/contact.py ''' return itchat.set_alias(user_name, alias)
def run(self): friends = itchat.get_friends(True) for friend in friends: try: if friend.RemarkName: user_id = int(friend.RemarkName) new_user_id = class_database_op.update_user( friend.UserName, user_id) if new_user_id: itchat.set_alias(friend.UserName, str(user_id)) user_id = new_user_id else: user_id = self.class_database_op.put_user(friend.UserName) itchat.set_alias(friend.UserName, str(user_id)) except: pass
def add_friend(msg): # 你可以设置好友认证信息,以便将好友加至对应群组 VerList = load_dict_from_file(info.configFil) if msg['RecommendInfo']['Content'] in VerList: # 该操作会自动将新好友的消息录入,不需要重载通讯录 itchat.add_friend(**msg['Text']) # 根据验证消息更改新加好友的备注 itchat.set_alias( msg['RecommendInfo']['UserName'], u'%s--%s' % (VerList[msg['RecommendInfo']['Content']], msg['RecommendInfo']['NickName'])) else: itchat.add_friend(**msg['Text']) itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])
def msg_handle_task(self, msg, msg_opt): user = itchat.search_friends(userName = msg['FromUserName']) user_id = None if user.get('RemarkName'): user_id = int(user.get('RemarkName')) new_user_id = self.class_database_op.update_user(msg['FromUserName'], user_id) if new_user_id: itchat.set_alias(msg['FromUserName'], str(user_id)) user_id = new_user_id else: user_id = self.class_database_op.put_user(msg['FromUserName']) itchat.set_alias(msg['FromUserName'], str(user_id)) print('%s: %s' % (msg['FromUserName'], msg.text)) return_str = self.command_dict_class.step_process(msg, user_id, msg_opt) if return_str: itchat.send_msg(return_str, msg['FromUserName'])
def add_friend(msg): print(msg) itchat.add_friend(**msg['Text']) # 该操作会自动将新好友的消息录入,不需要重载通讯录 response_list = [ '你好,很高兴认识你,我是' + robot_name, '你好,上知天文下知地理的' + robot_name + '就是我啦~', '太好了,终于遇见你,以后多多指教哦,我是' + robot_name ] userName = msg['RecommendInfo']['UserName'] itchat.send_msg(random.choice(response_list), userName) uid = generate_short_uid() print(itchat.set_alias(userName, uid))
def clean_spcial_sign(contacts,to_clean_l): userid_list = get_userid_list(contacts,to_clean_l,8) print('userid_list:',userid_list) flag = 0 for i in userid_list: print(to_clean_l[flag]) r = itchat.set_alias(userName=i,alias=to_clean_l[flag].replace('\n','')) flag += 1 if r['BaseResponse']['Ret'] != 0: print('Total {},Sucess {}, now failed and exit'.format(len(userid_list),flag)) exit() sleep(randint(5,15))
def mySetAlias(userName, remarkName): set_Alias_lock.acquire() try: trytimes = 3 while trytimes > 0: time.sleep(random.randint(5, 30)) if itchat.set_alias(userName, remarkName): break trytimes -= 1 except Exception as e: myprint(e) finally: set_Alias_lock.release()
def update_remark_name(): friends = itchat.get_friends() updateNum = 0 for f in friends: userName = f["UserName"] nickName = f["NickName"] remarkName = f["RemarkName"] if remarkName == '': print("开始设置第" + str(updateNum) + "位好友的备注名") uid = generate_short_uid() resp = itchat.set_alias(userName, uid) print(resp) updateNum = updateNum + 1 print("NickName:" + nickName) t = random.randint(7, 15) time.sleep(t) #这里需要放慢请求微信的速度,因为请求过快,微信会阻止后续请求 #if updateNum == 10: #break if resp['BaseResponse']['Ret'] != 0: print("退出好友备注更新,机器人启动开始") break print("已更新" + str(updateNum) + "位好友的备注")
def remark_data(self,contacts,unremark_name_list): ''' set remark name for friends who don't have it. !!Warning: 该方法会修改微信的备注数据,慎用 contacts: 微信获取的好友信息 unremark_name_list: 需要处理的无备注的好友列表 ''' # 构造对应的userID userid_list = [] for i in unremark_name_list: for el in contacts[2:]: if el[13] == i: userid_list.append(el[1]) # 进行处理 flag = 0 print('userid_list:',userid_list) for i in userid_list: #print(i,unregist_name_list[flag]+'.'+num_l[flag]) print(i,unremark_name_list[flag]) print(itchat.set_alias(userName=i, alias=unremark_name_list[flag])) flag += 1 sleep(randint(5,15))
r = requests.post(apiUrl, data=data).json() return r.get('text') except: # 将会返回一个None return # 这里是我们在实现微信消息的获取的同时直接回复 @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg): time.sleep(3) # 延时函数 # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复 defaultReply = 'I received: ' + msg['Text'] # 如果图灵Key出现问题,那么reply将会是None reply = get_response(msg['Text']) return reply or defaultReply # 为了不重复扫码登陆,这里使用热启动 itchat.auto_login(hotReload=True) friend = itchat.search_friends("snail12270")[0] friend_username = friend['UserName'] itchat.send('你可以提现吗?', toUserName=friend_username) print(friend['UserName']) itchat.set_alias(friend_username, 'lili01') f = itchat.search_friends('lili01') print(f) itchat.run()
def command(text): if text.upper() in [ "SAVE", "SAFE", "SAVE PARAMS", "SAVE PARAMETERS", "SAVE_PARAMS", "SAVE_PARAMETERS", "SAVE PARAMETRES", "SAVE_PARAMETRES", "SA", "S", u"保存", u"保" ]: my_glob.params.write_all() fundamental.send_to_me(u"パラメータをセーブしました。") elif text.upper() in ["REFRESH", "UPDATE", "UP", "R", u"更", u"更新"]: my_glob.params = my_glob.system_params() fundamental.send_to_me(u"パラメータをアップデートしました。") elif text.upper() in [ "UPDATE FRIENDS", "UP FRIENDS", "REFRESH FRIENDS", "RE FRIENDS", "UF", "RF" ]: my_glob.fl = my_glob.friend_lists() fundamental.send_to_me(u"Friend list updated.") elif text in [ "blocklist", "block list", "block_list", "blacklist", "black list", "black_list", "block", "black" ]: fundamental.send_to_me( u"只今ブロックされている友たちは次の通りです:" + u" | ".join(my_glob.params.blocking_list) + u"。\nユーザーを(アン)ブロックするには、「$(un)block User1/User2」で入力してください。") elif text in [ "whitelist", "white list", "white_list", "white", "good", "good group", "good groups", "goodlist", "good list", "good_list", "good", "white" ]: fundamental.send_to_me( u"只今ホワイトリストにあるグループは次の通りです:" + u" | ".join(my_glob.params.good_groups) + u"。\nユーザーを(アン)グッドするには、「$(un)good Group1/Group2」で入力してください。") elif text.startswith("block "): for res in match(fundamental.remove_dup( text.replace("block ", "").split("/")), friend=True, group=False): my_glob.params.set(task="blocking", UserName=res, value="add") my_glob.params.write("blocking_list") fundamental.send_to_me(u"新たにブロックされた友たちは以上です。") elif text.startswith("unblock "): for res in match(fundamental.remove_dup( text.replace("unblock ", "").split("/")), friend=True, group=False): my_glob.params.set(task="blocking", UserName=res, value="remove") my_glob.params.write("blocking_list") fundamental.send_to_me(u"ブラックリストから取り除かれた友たちは以上です。") elif text.startswith("good "): for res in match(fundamental.remove_dup( text.replace("good ", "").split("/")), friend=False, group=True): my_glob.params.set(task="good_group", UserName=res, value="add") my_glob.params.write("good_groups") fundamental.send_to_me(u"新たにホワイトリストに登録されたグループは以上です。") elif text.startswith("ungood "): for res in match(fundamental.remove_dup( text.replace("ungood ", "").split("/")), friend=False, group=True): my_glob.params.set(task="good_group", UserName=res, value="remove") my_glob.params.write("good_groups") fundamental.send_to_me(u"ホワイトリストから削除されたグループは以上です。") elif text.startswith("search "): match(fundamental.remove_dup(text.replace("search ", "").split("/")), friend=True, group=True) elif text.startswith("mode ") and len(text.split(" ")) >= 3: mode = text.split(" ")[-1] text = " ".join(text.split(" ")[1:-1]) if mode == "0": mode = "CHANGE" # Shortcut elif mode == "None": mode = None elif not mode in my_glob.modes: fundamental.send_to_me(u"現在サポートされているモードは次の通りです(CHANGEは0でも可):\n" + u"\n".join(my_glob.modes)) return False ress = match([text], friend=True, group=True) if len(ress) > 1: fundamental.send_to_me(u"検索結果が複数ありますので、実行できませんでした。") return False elif len(ress) == 1: my_glob.params.set(task="mode", UserName=ress[0], value=mode) fundamental.send_to_me(u"以上のユーザーのモードを" + unicode(mode) + u"に変えました。\n") my_glob.params.write("friend_mode") elif text.startswith("redirect "): ress = match([text.replace("redirect ", "")], friend=True, group=True) if len(ress) > 1: fundamental.send_to_me(u"検索結果が複数ありますので、実行できませんでした。") return False elif len(ress) == 1: my_glob.redirect_me_to = ress[0] fundamental.send_to_me( u"会話をリダイレクトしました。Successfully redirected conversation.\n") elif text.upper() in ["STOP REDIRECT", "STOP RE"]: my_glob.redirect_me_to = my_glob.me fundamental.send_to_me(u"会話のリダイレクトを解除しました。\n") elif text.upper() in ["SLEEP", "SLEEPING"]: my_glob.sleeping = True fundamental.send_to_me(u"睡眠モードに切り替えました。\n") elif text.upper() in ["WAKE", "WAKEUP"]: my_glob.sleeping = False fundamental.send_to_me(u"睡眠モードを解除しました。\n") elif text.upper() in [ "MANMODE", "MAN_MODE", "MAN MODE", "MODE_LIST", "MODE LIST", "MODELIST", "MODENAMES", "MODE NAMES" ]: fundamental.send_to_me(u"只今サポートされているモードは:" + u"、".join(my_glob.modes[:-1]) + u"と" + my_glob.modes[-1] + u"です。") elif text.startswith("time "): for res in match(fundamental.remove_dup( text.replace("time ", "").split("/")), friend=True, group=True): my_glob.params.set(task="time", UserName=res) my_glob.params.write("times") fundamental.send_to_me(u"上記の友達とグループのラストプレータイムを現在に設定しました。") elif text.upper() in [ "USER_MODE", "USER_MODES", "USER MODE", "USER MODES" ]: return_text = u"\n".join([ user[0] + u": " + my_glob.modes[user[1]] for user in sorted(my_glob.params.friend_mode.items(), key=operator.itemgetter(1)) ]) ## Added "unicode()" to avoid None if return_text: fundamental.send_to_me(u"只今記録のあるユーザのモードは次のとおりです:\n" + return_text) else: fundamental.send_to_me(u"ユーザのモードログが見つかりませんでした。\n") elif text.upper() in [ "USER_TIME", "USER_TIMES", "USER TIME", "USER TIMES" ]: now = time.time() return_text = u"\n".join([ user[0] + u": " + unicode(now - user[1]) + u"秒前" for user in sorted(my_glob.params.friend_times.items(), key=operator.itemgetter(1)) ]) ## Added "unicode()" to avoid None if return_text: fundamental.send_to_me(u"只今記録のあるユーザのラストプレータイムは次のとおりです:\n" + return_text) else: fundamental.send_to_me(u"ユーザのラストプレータイムログが見つかりませんでした。\n") elif text.upper().startswith("MESSAGE") or text.upper().startswith( "MASSAGE") or text.upper().startswith( "MESAGE") or text.upper().startswith("MASAGE"): if not " " in text: my_glob.prompt_message = "" fundamental.send_to_me(u"プロンプトメッセージを削除しました。\n") else: text = " ".join(text.split(" ")[1:]) if text.upper() in ["NONE", "CLEAR", "REMOVE"]: my_glob.prompt_message = "" fundamental.send_to_me(u"プロンプトメッセージを削除しました。\n") else: my_glob.prompt_message = text fundamental.send_to_me(u"プロンプトメッセージを次の通りに設定しました:\n" + my_glob.prompt_message) elif text.upper().startswith("CHANGE NAME") or text.upper().startswith( "CHANGE REMARK") or text.upper().startswith( "CHANGE REMARK NAME") or text.upper().startswith( "CHANGE ALIAS") or text.upper().startswith("SET ALIAS"): text = text.replace("CHANGE NAME", "").replace("CHANGE REMARK NAME", "").replace( "CHANGE REMARK", "").replace("CHANGE ALIAS", "").replace("SET ALIAS", "").lstrip() if len(text.split("/")) != 2: fundamental.send_to_me(u"$CHANGE NAME BEFORE_NAME/AFTER_NAME\n") else: res = my_glob.search_friend(text.split("/")[0]) if res == []: fundamental.send_to_me( text.split("/")[0] + u"の検索結果が見つかりませんでした。\n") elif len(res) > 1: fundamental.send_to_me( unicode(len(res)) + u"件の検索結果が見つかりました:\n" + u"\n".join([f[0] for f in res[0:5]]) + u"\n(下略)" * (len(res) > 5)) else: old_alias = res[0][0] usern = res[0][1] new_alias = text.split("/")[1] itchat.set_alias(userName=usern, alias=new_alias) my_glob.fl = my_glob.friend_lists() if old_alias in my_glob.params.friend_mode: my_glob.params.friend_mode[ new_alias] = my_glob.params.friend_mode.pop(old_alias) if old_alias in my_glob.params.friend_params: my_glob.params.friend_params[ new_alias] = my_glob.params.friend_params.pop( old_alias) if old_alias in my_glob.params.friend_times: my_glob.params.friend_times[ new_alias] = my_glob.params.friend_times.pop(old_alias) if old_alias in my_glob.params.blocking_list: my_glob.params.blocking_list[ new_alias] = my_glob.params.blocking_list.pop( old_alias) my_glob.params.write_all() fundamental.send_to_me(old_alias + u"のアリアスを" + new_alias + u"に変えました。") elif text.upper() in ["KILL", "QUIT", "EXIT"]: raise KeyboardInterrupt else: fundamental.send_to_me(man())
def register(request): """注册""" try: # 加载注册页面,更新微信本地库(itchat.pkl),为后续检索微信是否注册做铺垫 # 写在这里是因为检索耗时,避免用户感觉卡顿 try: itchat.get_friends(update=True) except KeyError as e: pass if request.method == 'GET': return render(request, 'register.html') else: remark_name = '' username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') wechat_nickname = request.POST.get('wechat_nickname') fruit_rule = request.POST.get('fruit_rule') wechat_code = request.POST.get('wechat_code') # 后台验证注册 if register_validate(username, password, password2, wechat_nickname, fruit_rule, wechat_code): # 传递过来的是remark_name(管理员的备注名) if 'y#' in wechat_nickname: remark_name = wechat_nickname.split('y#')[-1] # 传递过来的是nickname else: # 设置备注名 users = itchat.get_friends(update=True) for user in users: if user['NickName'] == wechat_nickname: user_name = user['UserName'] remark_name = user['RemarkName'] if not remark_name: remark_name = wechat_nickname # 备注名设置为昵称 itchat.set_alias(user_name, remark_name) break Fruiter.objects.create(name=username, pwd=password, wechat_remark_name=remark_name) # 保存到django_user django_user = User.objects.create_user(username=username, password=password, is_staff=True) django_user.save() # 分配权限组,可以查看提醒(确保后台新建第一个权限为提醒) django_user.groups.add(Group.objects.get(pk=1)) # 注册后自动登录 userlogin = auth.authenticate(username=username, password=password) auth.login(request, userlogin) return redirect('/admin/') else: return HttpResponse('您的浏览器版本太老,请尝试升级为主流浏览器') except Exception as e: logger.exception(e) return HttpResponseServerError()
def set_alias(self, user_name, remark_name): return itchat.set_alias(user_name, remark_name)