bot.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from wxbot import *
  4. import ConfigParser
  5. import json
  6. import logging
  7. import logging.config
  8. class TulingWXBot(WXBot):
  9. def __init__(self):
  10. WXBot.__init__(self)
  11. self.tuling_key = ""
  12. self.robot_switch = True
  13. try:
  14. cf = ConfigParser.ConfigParser()
  15. cf.read('conf/conf.ini')
  16. self.tuling_key = cf.get('main', 'key')
  17. except Exception:
  18. pass
  19. logging.info('tuling_key:'+self.tuling_key)
  20. # 自动回复函数self:发送方用户id, uid, msg
  21. def tuling_auto_reply(self, uid, msg):
  22. if self.tuling_key:
  23. url = "http://www.tuling123.com/openapi/api"
  24. user_id = uid.replace('@', '')[:30]
  25. body = {'key': self.tuling_key, 'info': msg.encode('utf8'), 'userid': user_id}
  26. r = requests.post(url, data=body)
  27. respond = json.loads(r.text)
  28. result = ''
  29. if respond['code'] == 100000:
  30. result = respond['text'].replace('<br>', ' ')
  31. elif respond['code'] == 200000:
  32. result = respond['url']
  33. elif respond['code'] == 302000:
  34. for k in respond['list']:
  35. result = result + u"【" + k['source'] + u"】 " + \
  36. k['article'] + "\t" + k['detailurl'] + "\n"
  37. else:
  38. result = respond['text'].replace('<br>', ' ')
  39. logging.info(' ROBOT:'+ result)
  40. return result
  41. else:
  42. return u"知道啦,我是天问机器人,主人马上就来!"
  43. def auto_switch(self, msg):
  44. msg_data = msg['content']['data']
  45. stop_cmd = [u'退下', u'走开', u'关闭', u'关掉', u'休息', u'滚开']
  46. start_cmd = [u'出来', u'启动', u'工作']
  47. if self.robot_switch:
  48. for i in stop_cmd:
  49. if i == msg_data:
  50. self.robot_switch = False
  51. self.send_msg_by_uid(u'[Robot]' + u'机器人已关闭!', msg['to_user_id'])
  52. else:
  53. for i in start_cmd:
  54. if i == msg_data:
  55. self.robot_switch = True
  56. self.send_msg_by_uid(u'[Robot]' + u'机器人已开启!', msg['to_user_id'])
  57. # msg dict: {'content': {'data': u'\u53bb', 'type': 0}, 'msg_id': u'3808887025959048251', 'msg_type_id': 4, 'to_user_id': u'@97745d23f2d3bbe5241cede14a3d8baa45809a1842e762b5a33fc1353f6efa3a', 'user': {'id': u'@f95a572b1284a0f75dd550a4ed9a93d788ded42a856db023cd3494faab623311', 'name': u'\u5929\u95ee'}}
  58. def handle_msg_all(self, msg):
  59. if not self.robot_switch and msg['msg_type_id'] != 1:
  60. return
  61. if msg['msg_type_id'] == 1 and msg['content']['type'] == 0: # reply to self
  62. self.auto_switch(msg)
  63. # msg_type_id=4 发送文字
  64. elif msg['msg_type_id'] == 4 and msg['content']['type'] == 0: # text message from contact
  65. self.send_msg_by_uid(self.tuling_auto_reply(msg['user']['id'], msg['content']['data']), msg['user']['id'])
  66. elif msg['msg_type_id'] == 3 and msg['content']['type'] == 0: # group text message
  67. if 'detail' in msg['content']:
  68. my_names = self.get_group_member_name(self.my_account['UserName'], msg['user']['id'])
  69. if my_names is None:
  70. my_names = {}
  71. if 'NickName' in self.my_account and self.my_account['NickName']:
  72. my_names['nickname2'] = self.my_account['NickName']
  73. if 'RemarkName' in self.my_account and self.my_account['RemarkName']:
  74. my_names['remark_name2'] = self.my_account['RemarkName']
  75. is_at_me = False
  76. for detail in msg['content']['detail']:
  77. if detail['type'] == 'at':
  78. for k in my_names:
  79. if my_names[k] and my_names[k] == detail['value']:
  80. is_at_me = True
  81. break
  82. if is_at_me:
  83. src_name = msg['content']['user']['name']
  84. reply = 'to ' + src_name + ': '
  85. if msg['content']['type'] == 0: # text message
  86. reply += self.tuling_auto_reply(msg['content']['user']['id'], msg['content']['desc'])
  87. else:
  88. reply += u"对不起,只认字,其他杂七杂八的我都不认识,,,Ծ‸Ծ,,"
  89. self.send_msg_by_uid(reply, msg['user']['id'])
  90. else:
  91. src_name = msg['user']['name']
  92. reply = 'to ' + src_name + ': '
  93. reply += u"主人马上就来!"
  94. #self.send_msg_by_uid(reply, msg['user']['id'])
  95. '''
  96. 主函数,执行TulingWXBot类里面的run方法
  97. '''
  98. def main():
  99. logging.config.fileConfig("conf/logger.conf")
  100. logger=logging.getLogger("example01")
  101. bot = TulingWXBot()
  102. bot.DEBUG = True
  103. bot.conf['qr'] = 'png'
  104. bot.run()
  105. if __name__ == '__main__':
  106. main()