wxpy: 用 Python 玩微信机器人

安装:python

pip install -U wxpy -i "https://pypi.doubanio.com/simple/"

代码:json

# coding:utf-8
from wxpy import *

# 实例化,并登陆微信
bot = Bot(cache_path=True)

# 查找到要使用机器人来聊天的好友
#my_friend = bot.friends().search('xxx')[0]
my_friend = ensure_one(bot.search(u'xxx'))

# 调用图灵机器人API
#api_key能够网上找,也能够到官网注册http://www.tuling123.com/
tuling = Tuling(api_key='759e94b5631f4cc39d9de36b1a3e0811') # 4a0488cdce684468b95591a641f0971d

# 使用图灵机器人自动与指定好友聊天
@bot.register(my_friend)

def reply_my_friend(msg):
    tuling.do_reply(msg)

embed()
bot.logout

itchat版本代码:api

import requests
import itchat

#像图灵机器人官网注册申请http://www.tuling123.com/
KEY = '2c242b43e94a4e0ca984629828d4e164'

def get_response(msg):
    # 构造了要发送给服务器的数据
    # 使用图灵机器人提供的接口
    apiUrl = 'http://www.tuling123.com/openapi/api'
    #一个发动的api的数据
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        #使用post方法去请求
        r = requests.post(apiUrl, data=data).json()
        # 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常
        return r.get('text')
    # 为了防止服务器没有正常响应致使程序异常退出,这里用try-except捕获了异常
    # 若是服务器没能正常交互(返回非json或没法链接),那么就会进入下面的return
    except:
        # 将会返回一个None
        return

# 使用装饰器
@itchat.msg_register(itchat.content.TEXT)
#获取图灵机器人返回的数据
#处理图灵机器人出现异常的时候
def tuling_reply(msg):
    # 为了保证在图灵Key出现问题的时候仍旧能够回复,这里设置一个默认回复
    defaultReply = 'I received: ' + msg['Text']
    # 若是图灵Key出现问题,那么reply将会是None
    reply = get_response(msg['Text'])
    # a or b的意思是,若是a有内容,那么返回a,不然返回b
    # 有内容通常就是指非空或者非None,你能够用`if a: print('True')`来测试
    return reply or defaultReply

# 为了让实验过程更加方便(修改程序不用屡次扫码),咱们使用热启动
itchat.auto_login(hotReload=True)
itchat.run()

参考:服务器

wxpy: 用 Python 玩微信微信

用python玩微信(聊天机器人,好友信息统计)post

相关文章
相关标签/搜索