robot.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. from werobot import WeRoBot
  2. import re
  3. from werobot.replies import ArticlesReply, MusicReply, ImageReply, Article
  4. from .MemcacheStorage import MemcacheStorage
  5. from servermanager.Api.blogapi import BlogApi
  6. from servermanager.Api.commonapi import TuLing
  7. import os
  8. import json
  9. from website.utils import get_md5
  10. from django.conf import settings
  11. import jsonpickle
  12. from servermanager.models import commands
  13. robot = WeRoBot(token='lylinux', enable_session=True)
  14. memstorage = MemcacheStorage()
  15. if memstorage.is_available:
  16. robot.config['SESSION_STORAGE'] = memstorage
  17. else:
  18. from werobot.session.filestorage import FileStorage
  19. import os
  20. from django.conf import settings
  21. if os.path.exists(os.path.join(settings.BASE_DIR, 'werobot_session')):
  22. os.remove(os.path.join(settings.BASE_DIR, 'werobot_session'))
  23. robot.config['SESSION_STORAGE'] = FileStorage(filename='werobot_session')
  24. blogapi = BlogApi()
  25. tuling = TuLing()
  26. def convert_to_articlereply(articles, message):
  27. reply = ArticlesReply(message=message)
  28. from blog.templatetags.blog_tags import custom_markdown, truncatechars_content
  29. from website.utils import CommonMarkdown
  30. from django.utils.safestring import mark_safe
  31. for post in articles:
  32. imgs = re.findall(r'(?:http\:|https\:)?\/\/.*\.(?:png|jpg)', post.body)
  33. imgurl = ''
  34. if imgs:
  35. imgurl = imgs[0]
  36. article = Article(
  37. title=post.title,
  38. description=truncatechars_content(post.body),
  39. img=imgurl,
  40. url=post.get_full_url()
  41. )
  42. reply.add_article(article)
  43. return reply
  44. @robot.filter(re.compile(r"^\?.*"))
  45. def search(message, session):
  46. s = message.content
  47. searchstr = str(s).replace('?', '')
  48. result = blogapi.search_articles(searchstr)
  49. if result:
  50. articles = list(map(lambda x: x.object, result))
  51. reply = convert_to_articlereply(articles, message)
  52. return reply
  53. else:
  54. return '没有找到相关文章。'
  55. @robot.filter(re.compile(r'^category\s*$', re.I))
  56. def category(message, session):
  57. categorys = blogapi.get_category_lists()
  58. content = ','.join(map(lambda x: x.name, categorys))
  59. return '所有文章分类目录:' + content
  60. @robot.filter(re.compile(r'^recent\s*$', re.I))
  61. def recents(message, session):
  62. articles = blogapi.get_recent_articles()
  63. if articles:
  64. reply = convert_to_articlereply(articles, message)
  65. return reply
  66. else:
  67. return "暂时还没有文章"
  68. @robot.filter(re.compile('^help$', re.I))
  69. def help(message, session):
  70. return '''欢迎关注!
  71. 默认会与图灵机器人聊天~~
  72. 你可以通过下面这些命令来获得信息
  73. ?关键字搜索文章.
  74. 如?python.
  75. category获得文章分类目录及文章数.
  76. category-***获得该分类目录文章
  77. 如category-python
  78. recent获得最新文章
  79. help获得帮助.
  80. weather:获得天气
  81. 如weather:西安
  82. idcard:获得身份证信息
  83. 如idcard:61048119xxxxxxxxxx
  84. music:音乐搜索
  85. 如music:阴天快乐
  86. PS:以上标点符号都不支持中文标点~~
  87. '''
  88. @robot.filter(re.compile('^weather\:.*$', re.I))
  89. def weather(message, session):
  90. return "建设中..."
  91. @robot.filter(re.compile('^idcard\:.*$', re.I))
  92. def idcard(message, session):
  93. return "建设中..."
  94. @robot.handler
  95. def echo(message, session):
  96. handler = MessageHandler(message, session)
  97. return handler.handler()
  98. class CommandHandler():
  99. def __init__(self):
  100. self.commands = commands.objects.all()
  101. def run(self, title):
  102. cmd = list(filter(lambda x: x.title.upper() == title.upper(), self.commands))
  103. if cmd:
  104. return self.__run_command__(cmd[0].command)
  105. else:
  106. return "未找到相关命令,请输入hepme获得帮助。"
  107. def __run_command__(self, cmd):
  108. try:
  109. str = os.popen(cmd).read()
  110. return str
  111. except:
  112. return '命令执行出错!'
  113. def get_help(self):
  114. rsp = ''
  115. for cmd in self.commands:
  116. rsp += '{c}:{d}\n'.format(c=cmd.title, d=cmd.describe)
  117. return rsp
  118. cmdhandler = CommandHandler()
  119. class MessageHandler():
  120. def __init__(self, message, session):
  121. userid = message.source
  122. self.message = message
  123. self.session = session
  124. self.userid = userid
  125. try:
  126. info = session[userid]
  127. self.userinfo = jsonpickle.decode(info)
  128. except:
  129. userinfo = WxUserInfo()
  130. self.userinfo = userinfo
  131. @property
  132. def is_admin(self):
  133. return self.userinfo.isAdmin
  134. @property
  135. def is_password_set(self):
  136. return self.userinfo.isPasswordSet
  137. def savesession(self):
  138. info = jsonpickle.encode(self.userinfo)
  139. self.session[self.userid] = info
  140. def handler(self):
  141. info = self.message.content
  142. if self.userinfo.isAdmin and info.upper() == 'EXIT':
  143. self.userinfo = WxUserInfo()
  144. self.savesession()
  145. return "退出成功"
  146. if info.upper() == 'ADMIN':
  147. self.userinfo.isAdmin = True
  148. self.savesession()
  149. return "输入管理员密码"
  150. if self.userinfo.isAdmin and not self.userinfo.isPasswordSet:
  151. passwd = settings.WXADMIN
  152. if settings.TESTING:
  153. passwd='123'
  154. if passwd.upper() == get_md5(get_md5(info)).upper():
  155. self.userinfo.isPasswordSet = True
  156. self.savesession()
  157. return "验证通过,请输入命令或者要执行的命令代码:输入helpme获得帮助"
  158. else:
  159. if self.userinfo.Count >= 3:
  160. self.userinfo = WxUserInfo()
  161. self.savesession()
  162. return "超过验证次数"
  163. self.userinfo.Count += 1
  164. self.savesession()
  165. return "验证失败,请重新输入管理员密码:"
  166. if self.userinfo.isAdmin and self.userinfo.isPasswordSet:
  167. if self.userinfo.Command != '' and info.upper() == 'Y':
  168. return cmdhandler.run(self.userinfo.Command)
  169. else:
  170. if info.upper() == 'HELPME':
  171. return cmdhandler.get_help()
  172. self.userinfo.Command = info
  173. self.savesession()
  174. return "确认执行: " + info + " 命令?"
  175. rsp = tuling.getdata(info)
  176. return rsp
  177. class WxUserInfo():
  178. def __init__(self):
  179. self.isAdmin = False
  180. self.isPasswordSet = False
  181. self.Count = 0
  182. self.Command = ''
  183. """
  184. @robot.handler
  185. def hello(message, session):
  186. blogapi = BlogApi()
  187. result = blogapi.search_articles(message.content)
  188. if result:
  189. articles = list(map(lambda x: x.object, result))
  190. reply = convert_to_articlereply(articles, message)
  191. return reply
  192. else:
  193. return '没有找到相关文章。'
  194. """