微信聊天機器人


 

一 簡介

wxpy基於itchat,使用了 Web 微信的通訊協議,,通過大量接口優化提升了模塊的易用性,並進行豐富的功能擴展。實現了微信登錄、收發消息、搜索好友、數據統計等功能。

總而言之,可用來實現各種微信個人號的自動化操作。(http://wxpy.readthedocs.io/zh/latest/bot.html)

安裝:wxpy 支持 Python 3.4-3.6,以及 2.7 版本

pip install -U wxpy

安裝 pillow模塊

pip install pillow

安裝 pyecharts模塊

pip install pyecharts

安裝 pyecharts_snapshot 模塊

pip  install pyecharts_snapshot 

安裝 echarts-countries-pypkg  模塊

 

 

二 登錄微信

0 、注意說明(如果運行出現問題請看):

  1.  目前cache_path=True參數不穩定,導致wxpy微信登錄不上,或者導致微信獲取不到好友列表, 如果微信登錄后出現問題請不要使用cache_path=True參數
  2.  微信如果報錯內如如下,請安裝pyecharts_snapshot模塊.
# 如果報錯Traceback (most recent call last):
#   File "G:\Daily application\python3.6\lib\site-packages\lml\utils.py", line 43, in do_import
#     plugin_module = __import__(plugin_module_name)
# ModuleNotFoundError: No module named 'pyecharts_snapshot'

1 、 掃碼登錄微信

from wxpy import *

bot = Bot()

2、cache_path=True(現階段版本有問題不要使用這個參數)

運行上面的程序,會彈出二維碼,用手機微信掃一掃即可實現登錄。

但上面的程序有一個缺點,每次運行都要掃二維碼。不過wxpy非常貼心地提供了緩存的選項,用於將登錄信息保存下來,就不用每次都掃二維碼,如下

bot = Bot(cache_path=True) # 必須先登錄過一次以后才可以使用緩存
 

三 微信好友男女比例

 
from wxpy import *
from pyecharts import Pie
import webbrowser
bot=Bot() #注意手機確認登錄

friends=bot.friends()
#拿到所有朋友對象,放到列表里
attr=['男朋友','女朋友','未知性別']
value=[0,0,0]
for friend in friends:
    if friend.sex == 1: # 等於1代表男性
        value[0]+=1
    elif friend.sex == 2: #等於2代表女性
        value[1]+=1
    else:
        value[2]+=1


pie = Pie("朋友男女比例")
pie.add("", attr, value, is_label_show=True)
#圖表名稱str,屬性名稱list,屬性所對應的值list,is_label_show是否現在標簽
pie.render('sex.html')#生成html頁面
# 打開瀏覽器
webbrowser.open("sex.html")
 

 

 

四 微信好友地域分布

顯示中國地圖,需要裝中國地圖模塊:

全球國家地圖: echarts-countries-pypkg (1.9MB): 世界地圖和 213 個國家,包括中國地圖
中國省級地圖: echarts-china-provinces-pypkg (730KB):23 個省,5 個自治區
中國市級地圖: echarts-china-cities-pypkg (3.8MB):370 個中國城市
中國縣區級地圖: echarts-china-counties-pypkg (4.1MB):2882 個中國縣·區
中國區域地圖: echarts-china-misc-pypkg (148KB):11 個中國區域地圖,比如華南、華北。

特別注明,中國地圖在 echarts-countries-pypkg 里。需要這些地圖的朋友,可以裝 pip 命令行:

$ pip3 install echarts-countries-pypkg
$ pip3 install echarts-china-provinces-pypkg
$ pip3 install echarts-china-cities-pypkg
$ pip3 install echarts-china-counties-pypkg
$ pip3 install echarts-china-misc-pypkg

 

 
from wxpy import *
from pyecharts import Map
import webbrowser
bot=Bot()

friends=bot.friends()


area_dic={}#定義一個字典,用來存放省市以及省市人數
for friend in friends:
    if friend.province not in area_dic:
        area_dic[friend.province]=1
    else:
        area_dic[friend.province]+=1

attr = area_dic.keys()
value = area_dic.values()



map = Map("好朋友們的地域分布", width=1200, height=600)
map.add(
    "好友地域分布",
    attr,
    value,
    maptype='china',
    is_visualmap=True, #結合體VisualMap

)
#is_visualmap -> bool 是否使用視覺映射組件
#
map.render('area.html')


webbrowser.open("area.html")
 

 

 

 

五 微信聊天機器人

1、為微信傳輸助手傳送消息

這里的file_helper就是微信的文件傳輸助手,我們給文件傳輸助手發送一條消息,可以在手機端的文件傳輸助手中收到括號內的消息

bot.file_helper.send('這個碗又大又圓  開心')

2、收發消息@bot.register()

 
from wxpy import *
bot=Bot()

@bot.register()
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text) # recv_msg.text取得文本
    return '自動回復:%s' %recv_msg.text

# 進入Python命令行,讓程序保持運行
embed()
 

3、自動給老婆回復信息

當你在網吧吃着雞,操作騷出天際時,你老婆打電話讓你回家吃飯,此時你怎么辦。。。

 
from wxpy import *
bot=Bot()

girl_friend=bot.search('劉劉劉')[0]
print(girl_friend)

@bot.register() # 接收從指定好友發來的消息,發送者即recv_msg.sender為指定好友girl_friend
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text) # recv_msg.text取得文本
    if recv_msg.sender == girl_friend:
        recv_msg.forward(bot.file_helper,prefix='老婆留言: ') #在文件傳輸助手里留一份,方便自己忙完了回頭查看
        ms='老婆最美麗,我對老婆的愛如滔滔江水,連綿不絕'
        print('>>>給老婆回復的:', ms)
        return  ms#給老婆回一份

embed()
 

4、從微信群里定位好友之拍老板馬屁

 

 
from wxpy import *
bot=Bot(cache_path=True)

company_group=bot.groups().search('群名字')[0]

boss=company_group.search('老板名字')[0]


@bot.register(chats=company_group) #接收從指定群發來的消息,發送者即recv_msg.sender為組
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text)
    if recv_msg.member == boss:
        #這里不用recv_msg.render 因為render是群的名字
        recv_msg.forward(bot.file_helper,prefix='老板發言: ')
        return '老板說的好有道理,深受啟發'

embed()
 

 

5、聊天機器人

給所有人自動回復

 

 
import json
import requests
from wxpy import *
bot = Bot()

# 調用圖靈機器人API,發送消息並獲得機器人的回復
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "9df516a74fc443769b233b01eqwer42"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[來自智能機器人] " + result["text"]


@bot.register()
def forward_message(msg):
    return auto_reply(msg.text)

embed()
 

 

給指定的群回復

 
import json
import requests
from wxpy import *
bot = Bot()

group=bot.groups().search('群名字')[0]
print(group)

# 調用圖靈機器人API,發送消息並獲得機器人的回復
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "9d602fe417464cd18beb2qwe064bee6"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[來自智能機器人] " + result["text"]


@bot.register(chats=group)
def forward_message(msg):
    return auto_reply(msg.text)

embed()
 

給指定的人回復

 
import requests
from wxpy import *
bot = Bot( cache_path=True)

friend=bot.search('名字r')[0]

# 調用圖靈機器人API,發送消息並獲得機器人的回復
def auto_reply(text):
    url = "http://www.tuling123.com/openapi/api"
    api_key = "申請圖靈機器人獲取key值放到這里"
    payload = {
        "key": api_key,
        "info": text,
    }
    r = requests.post(url, data=json.dumps(payload))
    result = json.loads(r.content)
    return "[微信測試,請忽略] " + result["text"]


@bot.register()
def forward_message(msg):
    if msg.sender == friend:
        return auto_reply(msg.text)

embed()
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM