做一个简单的微信机器人

不多说,直接上code

#!/usr/bin/env python 
# coding:utf-8
# @Date    : 2017/10/30 11:30
# @File    : wechat.py
# @Author  : sevck (sevck@jdsec.cn)
# @Link    : https://www.javasec.cn                  
# -------------------------------------------------------------------------
import itchat, time, re
from itchat.content import *
import urllib2, urllib
import json

'''
更新日志:
    1.添加初版,群聊,私聊功能

'''
status = True

# 群聊功能
@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    global status
    info = msg['Text'].encode("UTF-8")
    url = "http://www.tuling123.com/openapi/api"
    if info in "开启":
        status = True
    if info in  "闭嘴":
        status = False
    if status:
        data = {u"key": "xxxxx", u"info": info, u"loc": "", u"userid": msg.fromUserName}
        data = urllib.urlencode(data)
        url2 = urllib2.Request(url=url, data=data)
        response = urllib2.urlopen(url2)
        apicontent = response.read()
        s = json.loads(apicontent, encoding="utf-8")
        print('s==', s)
        if s['code'] == 100000:
            itchat.send(s['text'], msg['FromUserName'])
        if s['code'] == 200000:
            itchat.send_msg(s['text'] + "\r\n" + s['url'], msg['FromUserName'])

# 私聊功能
@itchat.msg_register(TEXT)
def text_replys(msg):
    global status
    info = msg['Text'].encode("UTF-8")
    url = "http://www.tuling123.com/openapi/api"
    if info in "开启":
        status = True
    if info in "闭嘴":
        status = False
    if status:
        data = {u"key": "xxxxxxx", u"info": info, u"loc": "", u"userid": msg.fromUserName}
        data = urllib.urlencode(data)
        url2 = urllib2.Request(url=url, data=data)
        response = urllib2.urlopen(url2)
        apicontent = response.read()
        s = json.loads(apicontent, encoding="utf-8")
        print('s==', s)
        if s['code'] == 100000:
            itchat.send(s['text'], msg['FromUserName'])
        if s['code'] == 200000:
            itchat.send_msg(s['text'] + "\r\n" + s['url'], msg['FromUserName'])


itchat.auto_login(enableCmdQR=1, hotReload=True)
itchat.run(debug=True)

 

效果:

 

 

最后提供一下学习教程:

http://itchat.readthedocs.io/zh/latest/

 我的机器人是用的图灵的API

posted @ 2017-10-31 10:30  sevck  阅读(640)  评论(0编辑  收藏  举报