今天我们使用python来制作一个微信机器人(基于图灵机器人)
可以假装自己有女朋友和自己聊天23333
安装wxpy:
首先,我们需要安装wxpy模块
pip install -U wxpy
登录微信:
from wxpy import * #导入模块
bot = Bot() #初始化机器人,扫码登录
如果觉得每次都需要扫码很麻烦,可以使用cache_path参数
bot = Bot(cache_path=True)
尝试发送消息:
bot.self.send('Hello World!') #给自己发送消息(这里不知道为什么会出现1204错误)
bot.file_helper.send('Hello World!') #给文件传输助手发送信息
friend_test = bot.friends().search('F')[0] #查找好友‘F’
group_test = bot.groups().search('Q')[0] #找找群聊'Q'
friend_test.send('Hello') #给好友‘F’发送信息
group_test.send('Hello') #在群聊‘Q’中发送信息
wxpy支持发送不同类型的消息:
# 发送文本
friend_test.send('Hello, WeChat!')
# 发送图片
friend_test.send_image('my_picture.png')
# 发送视频
friend_test.send_video('my_video.mov')
# 发送文件
friend_test.send_file('my_file.zip')
# 以动态的方式发送图片
friend_test.send('@img@my_picture.png')
自动处理消息:
wxpy提供了注册消息的方法,可以将各种类型的消息注册并自定义处理方式。
使用@bot.register()方法
@bot.register()
def test(msg) :
print(msg) #打印收到的消息
return 'received: {} ({})'.format(msg.text, msg.type) #自动回复消息
还可以加上一些限制,例如指定特定的朋友或群聊中@自己的
@bot.register(friend_test) #只回复friend_test
def reply_self(msg):
return 'received: {} ({})'.format(msg.text, msg.type)
@bot.register(Group, TEXT) #针对所有群聊的文本文件
def print_group_msg(msg):
if msg.is_at: #筛选所有群聊中@自己的文本消息
msg.reply(meg.text) #自动回复相同的内容
如果只写以上内容,会导致程序的主程序运行结束自然退出。wxpy给出了embed()方法,在程序末尾(或其他你想要暂停调试的地方)加上embed()方法就可以让程序保持运行,同时进入Python命令行。
使用图灵机器人:
图灵机器人是一个中文语境下的对话机器人
wxpy提供了图灵机器人的接口,我们只需要调用就好
1、我们需要先去注册一个新的机器人 http://www.tuling123.com/
注册完成后需要用到它的apikey
2、安装Requests: HTTP for Humans
pip install requests
3、测试
apikey = '机器人的apikey' #定义apikey
info_test = '你好' #定义测试消息
url_api = 'http://www.tuling123.com/openapi/api' #定义接口链接
data = {
'key' : apikey,
'info' : info_test, # 收到消息的文字内容
}
a = requests.post(url_api, data=data).json()
print(s) # 打印所获得的json查看如何使用
{'code': 100000, 'text': '嘿嘿,你也好啦~'} #我们会获得一个字典,字典包括一个编号和一个文本
完整程序:
import requests
from wxpy import *
apikey = '注册的机器人的apikey'
bot = Bot()
url_api = 'http://www.tuling123.com/openapi/api'
friend = bot.friends().search('F')[0] #选择好友
@bot.register(friend) #只对选择的好友进行消息自动处理
def reply_my_friend(msg):
"""好友自动回复"""
data = {
'key' : apikey,
'info' : msg.text, # 收到消息的文字内容
}
a = requests.post(url_api, data=data).json()
if a['code'] == 100000: #这里判断是否为文本信息
msg.reply(a['text']) # 回复消息
embed() #让程序保持运行
至此,最简单微信机器人就完成了,有兴趣的读者可以对程序进行进一步的扩展完善。
wxpy的官方文档: https://wxpy.readthedocs.io/zh/latest/bot.html#