用wxBot和圖靈機器人API實現微信群聊機器人


1 實現方案

wxBot登錄微信,接收、發送微信消息。

圖靈機器人 API對消息作回復。

2 實現效果

群聊效果

機器人會回復來自聯系人的消息,以及群里@此賬號的消息。

注意要將對應的群保存到聯系人。

3 運行方法

  1. 下載wxBot, 安裝python的依賴包。
  2. 圖靈機器人官網注冊賬號,申請圖靈key: 圖靈key申請地址
  3. 在bot.py文件所在目錄下新建conf.ini文件,內容為(key字段內容為申請到的圖靈key):

    [main]
    key=1d2678900f734aa0a23734ace8aec5b1
  4. 運行bot.py

4 完整代碼

bot.py

#!/usr/bin/env python
# coding: utf-8

from wxbot import *
import ConfigParser
import json


class TulingWXBot(WXBot):
def __init__(self):
WXBot.__init__(self)

self.tuling_key = ""

try:
cf = ConfigParser.ConfigParser()
cf.read('conf.ini')
self.tuling_key = cf.get('main', 'key')
except Exception:
pass
print 'tuling_key:', self.tuling_key

def tuling_auto_reply(self, uid, msg):
if self.tuling_key:
url = "http://www.tuling123.com/openapi/api"
user_id = uid.replace('@', '')[:30]
body = {'key': self.tuling_key, 'info': msg.encode('utf8'), 'userid': user_id}
r = requests.post(url, data=body)
respond = json.loads(r.text)
result = ''
if respond['code'] == 100000:
result = respond['text'].replace('<br>', ' ')
elif respond['code'] == 200000:
result = respond['url']
else:
result = respond['text'].replace('<br>', ' ')

return result
else:
return u"知道啦"

def handle_msg_all(self, msg):
if msg['msg_type_id'] == 4 and msg['content']['type'] == 0: # text message from contact
self.send_msg_by_uid(self.tuling_auto_reply(msg['user']['id'], msg['content']['data']), msg['user']['id'])
elif msg['msg_type_id'] == 3: # group message
if msg['content']['data'].find('@') >= 0: # someone @ another
my_names = self.get_group_member_name(msg['user']['id'], self.user['UserName'])
if my_names is None:
my_names = {}
if 'NickName' in self.user and len(self.user['NickName']) > 0:
my_names['nickname2'] = self.user['NickName']
if 'RemarkName' in self.user and len(self.user['RemarkName']) > 0:
my_names['remark_name2'] = self.user['RemarkName']
is_at_me = False
text_msg = ''
for _ in my_names:
if msg['content']['data'].find('@'+my_names[_]) >= 0:
is_at_me = True
text_msg = msg['content']['data'].replace('@'+my_names[_], '').strip()
break
if is_at_me: # someone @ me
snames = self.get_group_member_name(msg['user']['id'], msg['content']['user']['id'])
src_name = ''
if 'display_name' in snames:
src_name = snames['display_name']
elif 'nickname' in snames:
src_name = snames['nickname']
elif 'remark_name' in snames:
src_name = snames['remark_name']

if src_name != '':
reply = '@' + src_name + ' '
if msg['content']['type'] == 0: # text message
reply += self.tuling_auto_reply(msg['content']['user']['id'], text_msg)
else:
reply += u"對不起,只認字,其他雜七雜八的我都不認識,,,Ծ‸Ծ,,"
self.send_msg_by_uid(reply, msg['user']['id'])


def main():
bot = TulingWXBot()
bot.DEBUG = True
bot.conf['qr'] = 'png'
bot.run()


if __name__ == '__main__':
main()

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com