python itchat 使用记录(代码帖)

itchat 是一个调用微信的python接口,通过itchat,可以基于开发一些扩展功能。官方教程通俗易懂,官方教程入口:
http://itchat.readthedocs.io/zh/latest/tutorial/tutorial0/

下面的代码,添加了自动聊天机器人的功能,里面使用了图灵机器人,可以到官网上申请一个,官网地址:http://www.tuling123.com/

# -*-coding:utf-8-*-
import itchat
import requests

# 这里定义了一个自动聊天的用户列表
# 当以下用户发送消息时,才进行自动聊天
auto_reply_list = [        
    '家霖',
]


# 对图片的处理:对方发来图片或表情时,直接回复该图片
@itchat.msg_register(itchat.content.PICTURE)
def tuling_reply(msg):
    # 如果不在auto_reply_list列表中,则直接返回
    if msg.user.RemarkName not in auto_reply_list:
        return None
    msg.download(msg.fileName)
    itchat.send('@%s@%s' % (
        'img' if msg['Type'] == 'Picture' else 'fil', msg['FileName']),
        msg['FromUserName'])
    return '反弹~'


# 对文字的处理:对方发送来文字时,调用图灵机器人的接口,实现自动聊天
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 如果不在auto_reply_list列表中,则直接返回
    if msg.user.RemarkName not in auto_reply_list:
        return None

    print(msg.user.RemarkName +"    "+ msg['Text'])

    defaultReply = '我的主人不在,等主人回来我会将你的话告诉他的~'
    reply = get_response(msg['Text'])
    return reply or defaultReply


KEY = '' # 替换成自己的key,可以到图灵机器人官网注册并申请一个 

def get_response(msg):
    # 构造了要发送给服务器的数据
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return
itchat.auto_login(hotReload=True) # 设置为true,不用每一次都扫描二维码
itchat.run()

参考:
http://itchat.readthedocs.io/zh/latest/
https://www.cnblogs.com/Erick-L/p/6895514.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值