OSDN Git Service

new version
[simple-tornado-bot/simple-tornado-bot.git] / bot.py
1 # -*- coding: utf-8 -*-
2 """
3 Created on Sat Sep  1 11:18:39 2018
4
5 @author: fuke masasi
6 """
7
8 import tornado.ioloop
9 import tornado.web
10 import tornado.escape
11 import os, re, glob
12 import pytz, pymongo
13 from datetime import datetime
14 from linebot import LineBotApi, WebhookParser
15 from linebot.exceptions import InvalidSignatureError
16 from linebot.models import TextSendMessage
17
18
19 class WebHookHandler(tornado.web.RequestHandler):   
20     def get(self):
21         mes = self.get_argument('code','')
22         self.name = 'glove'
23         self.write(self.main(mes))
24         
25     def main(self,no):
26         pz = pytz.timezone('Asia/Tokyo')
27         now = datetime.now(pz)
28         t = now.hour
29         w = now.weekday()
30         if (w < 5)and(t >= 9)and(t < 16):
31             return u'仕事中.'
32         table = self.users(self.name)
33         item = table.find({'no':re.compile(no,re.IGNORECASE)})
34         if item.count() == 1:
35             x = item[0]
36             ans = x['name']+'\n'+x['no']
37         elif item.count() > 1:
38             ans = ''    
39             obj = list(item)
40             list1 = sorted(obj, key=lambda k:k['name'])
41             for x in list1:
42                 if x['name'] == list1[0]['name']:
43                     ans += x['name']+'\n'+x['no']+'\n'
44                 else:
45                     break
46             else:
47                 return ans       
48             ans = self.itr(sorted(list1, key=lambda k:k['no']))
49         else:
50             ans = self.itr(table.find().sort('no'))
51             ans = '-*-glove list-*-\n'+ans
52         return ans
53     
54     def itr(self,item):
55         ans = ''
56         for x in item:
57             ans += '【'+x['no']+'】 '
58         return ans
59     
60     def setting(self,name,dbname):
61         client = pymongo.MongoClient(uri)[ac]
62         if dbname in client.tables():
63             db = client['users']
64             item = db.find_one(name)
65             if item['dbname'] == dbname:
66                 return False
67             else:
68                 item.update({'user':name,'dbname':dbname})
69                 return True
70     
71     def users(self,name):
72         client = pymongo.MongoClient(uri)[ac]
73         db = client['users']
74         item = db.find_one(name)
75         if item:
76             return client[item['dbname']]
77         else:
78             db.insert({'name':name,'dbname':'glove'})
79             return client['glove']
80                 
81     def post(self):
82         '''
83         signature = self.request.headers['X-Line-Signature']
84         body = self.request.body
85         parser = WebhookParser(ch)
86         try:
87             parser.parse(body, signature)
88         except InvalidSignatureError:
89             tornado.web.HTTPError(404)
90             return
91         '''
92         dic = tornado.escape.json_decode(self.request.body)              
93         for event in dic['events']:
94             if 'replyToken' in event:
95                 x = event['replyToken']
96                 y = event['message']['text']
97                 if self.setting(x,y):
98                     self.name = y
99                     linebot.reply_message(x,
100                         TextSendMessage(text=u'設定完了.'))
101                 else:
102                     self.name = x
103                     linebot.reply_message(x,
104                         TextSendMessage(text=self.main(x))
105                     )
106         
107 class DummyHandler(tornado.web.RequestHandler):
108     def get(self):        
109         self.db = pymongo.MongoClient(uri)[ac]
110         for x in glob.glob('./*.txt'):
111             f = open(x)
112             data = f.read()
113             f.close()
114             self.main(x[2:-4],data)
115     
116     def main(self,name,data):
117         table = self.db[name]
118         item = []
119         for x in data.split('\n'):
120             if x[0] == '@':
121                 dic = {}
122                 dic['name'] = x[1:]
123             else:
124                 dic['no'] = x
125                 item.append(dic)
126         table.remove()
127         for x in item:
128             table.insert(x)
129
130 application = tornado.web.Application([(r'/callback',WebHookHandler),(r'/init',DummyHandler)])
131
132 if __name__ == '__main__':
133     token = os.environ['Access_Token']
134     ch = os.environ['Channel_Secret']
135     uri = os.environ['MONGODB_URI']
136     ac = os.environ['ACCOUNT']
137     port = int(os.environ.get('PORT',5000))#important in heroku
138     linebot = LineBotApi(token)
139     webhook = WebhookParser(ch)  
140     application.listen(port)
141     tornado.ioloop.IOLoop.instance().start()
142