Python-微信機器人


一、簡介

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

總而言之,可用來實現各種微信個人號的自動化操作。

https://wxpy.readthedocs.io/zh/latest/index.html

安裝:wxpy模塊(支持 Python 3.4-3.+ 以及 2.7 版本):pip3 install wxpy

安裝 pillow模塊:pip3 install pillow

安裝 pyecharts模塊:pip3 install pyecharts==0.1.9.4

二、微信登錄

from wxpy import *

bot = Bot()

掃碼登錄微信,生成bot對象,對微信進行一系列操作

但是上面的代碼有一個很明顯的缺陷,就是你不管又沒有修改你的程序,每次執行都需要重新登錄你的微信,但是呢,里面有一個參數可以幫我們解決這個問題,

它可以通過緩存的形式將我們的登錄信息保存下來,這個一來就不需要每次都進行掃碼登錄了。

from wxpy import *

bot = Bot(cache_path=True)

三、微信好友男女比例

from wxpy import *
import webbrowser
from pyecharts import Pie


bot = Bot(cache_path=True)  # 彈出二維碼登錄微信,生成bot對象

friends = bot.friends()  # 獲取所有的微信好友信息

attr = ['男盆友','女盆友','其他']  # 設置男性/女性/未知性別好友名稱

value = [0,0,0]  # 初始化對象好友數量

# 遍歷所有好友,判斷該好友性別
for friend in friends:
    if friend.sex == 1:
        value[0] += 1
    elif friend.sex == 2:
        value[1] += 1
    else:
        value[2] += 1

pie = Pie("Sean的好朋友們")

pie.add("",attr,value,is_label_show=True)

pie.render("friends.html")

webbrowser.open('friends.html')

四、微信好友地區分布

 

from wxpy import *
from pyecharts import Map
import webbrowser

bot = Bot(cache_path=True)

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("Sean的好友地域分布",width=1200,height=600)
map.add("好友地域分布",attr,value,maptype='china',is_visualmap=True)

map.render("area.html")

webbrowser.open("area.html")

五、微信聊天機器人

 1、常用方法

from wxpy import *

# bot = Bot(cache_path=True)

# 給指定朋友發送消息
# friend = bot.friends().search("tank")[0]
# friend.send("hello,達莎雕")

# 獲取所有好友
# my_friend = bot.friends(update=False)
# print("sean的好友數:"+str(len(my_friend)-1))

# 獲取所有微信群
# group = bot.groups(update=False)
# print(group)
# print("sean的微信群聊數:"+str(len(group)))

# 獲取所有關注的微信公眾號
# mp = bot.mps(update=False)
# print("sean關注的微信公眾號" + str(len(mp)))

2、給文件傳輸助手發信息

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

bot.file_helper.send('hello')

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

from wxpy import *

bot = Bot(cache_path=True)

friend = bot.friends().search('tank')[0]
friend.send("hello 達莎雕")


@bot.register(friend)
def recv_send_msg(recv_msg):
    print('收到的消息:', recv_msg)
    return '自動回復:{}'.format(recv_msg)

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

4、自動給對象回復消息

當你在宿舍打着LOL,各種騷斷腿的操作的時候,你對象讓你出來陪她逛街、吃飯,你怎么辦....

from wxpy import *

bot = Bot(cache_path=True)

girl_friend = bot.friends().search('girl_friend')[0]

@bot.register(friend)
def recv_send_friend(recv_msg):
    print("[接收]" + str(recv_msg))
    if recv_msg.type != 'Text':
        ret = "我想陪你看遍世間美景,然后告訴你,它們都不及你萬分之一。"
    elif "這是什么" in str(recv_msg):
        ret = "這是我的微信機器人"
    else:
        ret = "今晚月色真美"
    print('[發送]' + str(ret))
    return ret

embed()

5、定位微信群好友自動回復消息

from wxpy import *

bot = Bot(cache_path=True)

company_group = bot.groups()[3]  # 獲取指定群
no = company_group.members  # 獲取群內所有成員信息

@bot.register(chats=company_group) #接收從指定群發來的消息,發送者即recv_msg.sender為組
def recv_send_msg(recv_msg):
    print('收到的消息:',recv_msg.text)
    if recv_msg.member == no[0]:
        #這里不用recv_msg.render 因為render是群的名字
        recv_msg.forward(bot.file_helper,prefix='測試發言: ')
        return '你是達莎雕?'
    # elif recv_msg.member ==
    elif recv_msg.member == no[2]:
        return '鬼刀一開看不見'

embed()

6、聊天機器人

第一種方式:

1、指定好友回復

from wxpy import *
import requests
import json


# 調用圖靈機器人API,發送消息並且獲得機器人的回復
def auto_reply(text):
    url = 'http://openapi.tuling123.com/openapi/api/v2'
    api_key = '51a9bec5710941dda6ef836e164a4585'
    payload = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": text
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "上海",
                    "province": "上海",
                    "street": "御青路"
                }
            }
        },
        "userInfo": {
            "apiKey": api_key,
            "userId": "123456"
        }
    }
    re = requests.post(url, data=json.dumps(payload))
    result = json.loads(re.content)
    return "[來自sean的智能機器人]:" + result['results'][0]['values']['text']


bot = Bot(cache_path=True)
friend = bot.friends().search('好友名稱')[0]

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


embed()

2、指定群回復

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

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

# 調用圖靈機器人API,發送消息並且獲得機器人的回復
def auto_reply(text):
    url = 'http://openapi.tuling123.com/openapi/api/v2'
    api_key = '51a9bec5710941dda6ef836e164a4585'
    payload = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": text
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "上海",
                    "province": "上海",
                    "street": "御青路"
                }
            }
        },
        "userInfo": {
            "apiKey": api_key,
            "userId": "123456"
        }
    }
    re = requests.post(url, data=json.dumps(payload))
    result = json.loads(re.content)
    return "[來自sean的智能機器人]:" + result['results'][0]['values']['text']

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

embed()

3、所有人自動回復(慎用)

import json
import requests
from wxpy import *

bot = Bot(cache_path=True)

# 調用圖靈機器人API,發送消息並且獲得機器人的回復
def auto_reply(text):
    url = 'http://openapi.tuling123.com/openapi/api/v2'
    api_key = '51a9bec5710941dda6ef836e164a4585'
    payload = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": text
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {
                "location": {
                    "city": "上海",
                    "province": "上海",
                    "street": "御青路"
                }
            }
        },
        "userInfo": {
            "apiKey": api_key,
            "userId": "123456"
        }
    }
    re = requests.post(url, data=json.dumps(payload))
    result = json.loads(re.content)
    return "[來自sean的智能機器人]:" + result['results'][0]['values']['text']

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

embed()

第二種方式:

from wxpy import *

bot = Bot(cache_path=True)

friend = bot.friends().search('魏倩倩Bella')[0]
print(friend)

# wxpy自動集成了圖靈機器人的接口,我們只需要調用即可
tuling = Tuling(api_key='a2064e6849a64c16aaf29452842f40f7')

@bot.register(friend)
def forward_msg(msg):
    tuling.do_reply(msg)
embed()

 


免責聲明!

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



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