天使漫步IT工作室天使漫步IT工作室

【代码片段】20行代码将个人微信改造成机器人自动对话-python实现


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

准备工作:

  • 1.需要申请图灵机器人的key。注册地址:图灵机器人
  • 2.通过pip安装itchat(如果出现time out则可以使用更换源来解决,比如:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade itchat

更多源:设置国内pip源,加速pip更新速度

代码如下(中间需要授权登录):

import requests
import itchat

#填写自己注册的图灵机器人的APIkey
KEY = '自己的图灵机器人的APIkey'

#根据图灵机器人API的规定发送数据
def tuling_reponse(msg):
    url = 'http://www.tuling123.com/openapi/api'
    data = {
            'key' : KEY,
            'info' : msg,
            'userid' : 'xsl' #这个随便填,作为机器人识别的标志,因为一个机器人可以供多个用户使用
    }
    #rep返回的数据格式大概是这样{'code': 100000, 'text': '你好'}
    rep = requests.post(url,data).json()
    return rep.get('text')

#定义消息处理函数
#itchat.content.TEXT代表只处理文本信息,图片、语音都可以处理,自己百度一下就好
@itchat.msg_register(itchat.content.TEXT)
def get_reponse(msg):
    reponse=tuling_reponse(msg['Text'])
    return reponse

itchat.auto_login(hotReload=True)
itchat.run()

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » 【代码片段】20行代码将个人微信改造成机器人自动对话-python实现
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38