打造有趣的个人微信机器人

2018-01-16  本文已影响73人  清晨的麦田

先上图

机器人.png

首先先安装python环境 2.7,最后我会附上python3.0的代码,看官如果是python3.0+的环境直接拉到最后

安装完毕执行下面的命令安装itchat模块

pip install itchat

第一个文件:创建 weixin_robot.py 文件

代码如下:

# -*- coding:utf-8 -*-
import itchat
from tuling import get_response
from itchat.content import *

itchat.auto_login(hotReload=True,enableCmdQR=2)

@itchat.msg_register(TEXT)
def text_reply(msg):
    return get_response(msg['Text'])
itchat.run(debug=True)

第二个文件:创建 tuling.py

代码如下:

#coding=utf8
import sys, os
import requests, json

try:
    with open('tuling.json') as f: key = json.loads(f.read())['key']
except:
    key = '' # if key is '', get_response will return None
    # raise Exception('There is something wrong with the format of you plugin/config/tuling.json')

def get_response(msg, storageClass = None, userName = None, userid = 'wanghuli'):
    url = 'http://www.tuling123.com/openapi/api'
    payloads = {
        'key': key,
        'info': msg,
        'userid': userid,
    }
    try:
        r = requests.post(url, data = json.dumps(payloads)).json()
    except:
        return
    if not r['code'] in (100000, 200000, 302000, 308000, 313000, 314000): return
    if r['code'] == 100000: # 文本类
        return '\n'.join([r['text'].replace('<br>','\n')])
    elif r['code'] == 200000: # 链接类
        return '\n'.join([r['text'].replace('<br>','\n'), r['url']])
    elif r['code'] == 302000: # 新闻类
        l = [r['text'].replace('<br>','\n')]
        for n in r['list']: l.append('%s - %s'%(n['article'], n['detailurl']))
        return '\n'.join(l)
    elif r['code'] == 308000: # 菜谱类
        l = [r['text'].replace('<br>','\n')]
        for n in r['list']: l.append('%s - %s'%(n['name'], n['detailurl']))
        return '\n'.join(l)
    elif r['code'] == 313000: # 儿歌类
        return '\n'.join([r['text'].replace('<br>','\n')])
    elif r['code'] == 314000: # 诗词类
        return '\n'.join([r['text'].replace('<br>','\n')])

if __name__ == '__main__':
    try:
        ipt = raw_input
        ipt = lambda: raw_input('>').decode(sys.stdin.encoding)
    except:
        ipt = lambda: input('>')
    while True:
        a = ipt()
        print(get_response(a, 'ItChat'))

第三个文件:创建tuling.json 文件,代码如下:

key 为图灵网站申请,地址: http://www.tuling123.com

{
    "key": "xxxxxxxx"
}

第四个文件:执行脚本供参考(可不用):

创建:run.sh
代码如下:

python weixin_robot.py

第五个文件: 配合第四个使用(可不用)

创建:start.sh
代码如下:

nohup sh +x run.sh >log.log 2>&1 &

最后如果环境是python 3.0+的请使用以下步骤:

安装 wxpy 模块

pip install wxpy

创建rebootpython3.py 文件:
代码如下:

# coding: utf-8
from wxpy import *
# 扫码登陆
bot = Bot()
# 初始化图灵机器人 (API key 申请: http://tuling123.com)
tuling = Tuling(api_key='xxxxxxxxx')
# 自动回复所有文字消息
@bot.register(msg_types=TEXT)
def auto_reply_all(msg):
    tuling.do_reply(msg)
# 开始运行
bot.join()

key 需要看官去:http://www.tuling123.com申请,可以使用免费的,另外如果终端是白色的,最好改成黑色,原因二维码生成会有问题,扫码不成功大多是此问题。

上一篇 下一篇

猜你喜欢

热点阅读