前言首先你的微信號(hào)能夠登錄網(wǎng)頁版微信,才能打造你的專屬個(gè)人微信號(hào)機(jī)器人,點(diǎn)擊跳轉(zhuǎn)網(wǎng)頁版微信登錄頁面 類似的文章網(wǎng)上也都有,其實(shí)我也是受到別的文章的一些啟發(fā),因?yàn)椴皇敲總€(gè)人都想實(shí)現(xiàn)同樣的功能的,直接套用別人的代碼不嚴(yán)謹(jǐn)而且bug太多,于是就想自己動(dòng)手從零開始實(shí)現(xiàn)一個(gè)屬于自己的微信機(jī)器人,不過呢,也大同小異吧。 算下來前前后后加上寫這篇博客花了大概一周的時(shí)間,因?yàn)槎际怯昧懔闵⑸⒌臅r(shí)間進(jìn)行開發(fā)以及測(cè)試然后修改bug再加功能再開發(fā),這么一個(gè)循環(huán),從一開始的只能回復(fù)消息、到現(xiàn)在能夠:回復(fù)特定群聊消息、特殊群聊特殊處理、回復(fù)表情包、查看所有別人撤回的消息以及操控微信機(jī)器人等等等等。
好的,廢話不多說,接下來就開始吧。 一、準(zhǔn)備python3.7 (重中之重,后面會(huì)解釋)
itchat (直接用pip 命令安裝即可)
jupyter notebook (隨意,用你最喜歡的編譯器即可,不過最后還是要把代碼放在一個(gè)py文件里)
NLP 實(shí)現(xiàn)一個(gè)聊天機(jī)器人(限于本人沒學(xué)過自然語言處理,并且空閑時(shí)間也不多,其實(shí)就是因?yàn)樘y了。。那就只能先調(diào)用別人的接口啦)
二、開始ps:詳情請(qǐng)看代碼注釋,若不想分函數(shù)來看也可以直接看完整代碼 def get_friendname():friends_name={} #存儲(chǔ)好友的微信昵稱和備注friends=itchat.get_friends(update=True) #返回的是一個(gè)存儲(chǔ)所有好友信息的列表,每個(gè)好友的信息都是用一個(gè)字典來存放for friend in friends[1:]: #第一個(gè)為自己,所以這里排除了自己friends_name.update({friend['UserName']:{'nickname':friend['NickName'],'remarkname':friend['RemarkName']}})return friends_name
def get_username():chatrooms=itchat.get_chatrooms(update=True) #返回的是一個(gè)所有群聊的信息的列表,每個(gè)群聊信息都是用一個(gè)字典來存放user_name=[] #接收特定群聊@本人的消息,并回復(fù);存放特定群聊的usernameall_user_name=[] #存放全部群聊的usernamevip=[] #存放特定群聊的名稱if os.path.exists('./vip.txt'):with open('./vip.txt','r',encoding='utf-8') as f:for i in f.read().split('\n')[:-1]:vip.append(i)for chatroom in chatrooms:all_user_name.append(chatroom['UserName'])if chatroom['NickName'] in vip:user_name.append(chatroom['UserName'])return all_user_name,user_name,vip
def get_response(msg):url=''#看到請(qǐng)求url好像涉及到一些sessionid、userid等信息,可能直接復(fù)制會(huì)用不了什么的,所以你們直接去分析一下網(wǎng)頁即可拿到啦,把content參數(shù)format成msg即可headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}r=requests.get(url,headers=headers)response=re.findall('"body":{"fontStyle":0,"fontColor":0,"content":"(.*?)","emoticons":{}}}',r.text)[1].replace('\\r\\n','')return response
def get_words():words=[]if os.path.exists('./words.txt'):with open('./words.txt','r',encoding='utf-8') as f:for i in f.read().split('\n')[:-1]:words.append(i)return words
# 包括文本(表情符號(hào))、位置、名片、通知、分享、圖片(表情包)、語音、文件、視頻@itchat.msg_register([TEXT,MAP,CARD,SHARING,PICTURE,RECORDING,ATTACHMENT,VIDEO],isFriendChat=True,isGroupChat=True) #監(jiān)聽個(gè)人消息和群聊消息def download_reply_msg(msg):global flag,sj,isrun,use_info #flag判斷要不要進(jìn)入斗圖模式,sj控制斗圖的時(shí)間長(zhǎng)短,isrun判斷是否啟動(dòng)自動(dòng)回復(fù)機(jī)器人(默認(rèn)運(yùn)行中),通過向傳輸助手發(fā)指令來控制,use_info說明文檔all_user_name,user_name,vip=get_username()#每次接受消息時(shí)要拿到當(dāng)前規(guī)定的群聊和特定群聊信息,后面用來分別做處理words=get_words() #拿到當(dāng)前自定義回復(fù)消息的信息now_time=int(time.time()) #記錄獲取這條消息的時(shí)間,后面處理撤回消息的時(shí)候用到b=[] #用來記錄已經(jīng)過了可以撤回的時(shí)間的消息if len(msg_dict) != 0:for key,value in msg_dict.items():if (now_time - value['time']) >= 125: #經(jīng)過驗(yàn)證發(fā)現(xiàn)消息2分鐘之內(nèi)才能撤回,這里為了保險(xiǎn)起見加多5秒鐘b.append(key)for eachkey in list(msg_dict.keys()):if eachkey in b: #要是過了撤回時(shí)間的消息是文件類型的就把它們刪除,避免增加不必要的磁盤空間,盤大的請(qǐng)隨意if 'file' in msg_dict[eachkey].keys():os.remove(msg_dict[eachkey]['file'])msg_dict.pop(eachkey)#---------------------------------------------------------#下面開始存儲(chǔ)各類消息,主要是用來查看別人撤回的消息,后面會(huì)用到if msg['Type'] in [MAP,SHARING]: #地圖或者分享old_id=msg['MsgId']link=msg['Url']msg_dict.update({old_id:{'type':msg['Type'],'data':link,'time':now_time}})elif msg['Type'] in [PICTURE,RECORDING,ATTACHMENT,VIDEO]:if msg['ToUserName'] != 'filehelper': # 避免給文件傳輸助手發(fā)文件也傳入字典,沒必要而且傳入字典只是為了防止撤回,況且它是沒有撤回的old_id=msg['MsgId']file='./保存的文件/'+ msg['MsgId'] + '.' + msg['FileName'].split('.')[-1]msg['Text'](file)msg_dict.update({old_id:{'type':msg['Type'],'file':file,'time':now_time}})else:file='./保存的文件/'+ msg['FileName']msg['Text'](file)elif msg['Type'] == CARD: #名片old_id=msg['MsgId']link=re.findall('bigheadimgurl="(.*)" smallheadimgurl',str(msg))[0]msg_content = '來自' + msg['RecommendInfo']['Province'] +msg['RecommendInfo']['City'] + '的'+ msg['RecommendInfo']['NickName'] + '的名片' #內(nèi)容就是推薦人的昵稱和性別if msg['RecommendInfo']['Sex'] == 1:msg_content += ',男的'else:msg_content += ',女的'msg_dict.update({old_id:{'type':msg['Type'],'head':link,'data':msg_content,'time':now_time}})elif msg['Type'] == TEXT: #文本old_id=msg['MsgId']text=msg['Text']msg_dict.update({old_id:{'type':msg['Type'],'data':text,'time':now_time}})#---------------------------------------------------------#下面是自動(dòng)回復(fù)消息的(一切回復(fù)邏輯都在這里)if msg['ToUserName'] != 'filehelper': # 避免給文件傳輸助手發(fā)消息也自動(dòng)回復(fù)if isrun == '運(yùn)行中......': #操控機(jī)器人的,想停就停,想啟動(dòng)就啟動(dòng),不用關(guān)掉程序,而且不影響查看撤回消息的功能if msg['FromUserName'] in all_user_name:if msg['FromUserName'] in user_name: #當(dāng)消息來自特定群聊時(shí),下面代碼才會(huì)執(zhí)行if sj is not None:if int(time.time()) - sj >= 900: #斗圖時(shí)間:15分鐘flag=0sj=Noneif (msg['isAt'] is True)&(msg['Type'] == TEXT):myname='@' + re.findall("'Self'.*?'DisplayName': '(.*?)', 'KeyWord'",str(msg))[0] if re.findall("'Self'.*?'DisplayName': '(.*?)', 'KeyWord'",str(msg))[0] != '' else '這里填你自己的微信昵稱'if '帥哥來斗圖' in msg['Text']:flag=1sj=int(time.time())num=random.choice(os.listdir('./表情包'))msg.user.send('@img@./表情包/{}'.format(num))
|