用python做一个微信聊天机器人

版权声明:本文为博主(风轻云淡)原创文章,未经博主允许不得转载。CSDN https://blog.csdn.net/qq_20343517/article/details/88656121

先去图灵机器人申请一个账号,得到 key

新建文件wx.py写入如下内容

import requests
import itchat


def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'   #改成你自己的图灵机器人的api
    data={
        'key': '*******************************',  # Tuling Key
        'info': msg,  # 这是我们发出去的消息
        'userid': 'wechat-robot',  # 这里可随意修改
    }
    # 通过如下命令发送一个post请求
    r = requests.post(apiUrl, data=data).json()
    return r.get('text')


@itchat.msg_register(itchat.content.TEXT)
# 用于接收来自朋友间的对话消息  #如果不用这个,朋友发的消息便不会自动回复
def print_content(msg):
    print('单人对话-'+msg['User']['NickName']+':'+msg['Text'])
    return get_response(msg['Text'])


# 用于接收群里面的对话消息
@itchat.msg_register([itchat.content.TEXT], isGroupChat=True)
def print_content(msg):
    print('多人对话-'+msg['User']['NickName']+':'+msg['Text'])
    return get_response(msg['Text'])


itchat.auto_login(True)
itchat.run()

安装python,用 pip 安装缺少的包,然后在文件所在目录打开命令行输入

$ python wx.py

用微信扫码登录,(出于安全考虑,2018年之后注册的微信号已经不能登录网页版) 就可以愉快的玩耍了

猜你喜欢

转载自blog.csdn.net/qq_20343517/article/details/88656121