diff options
Diffstat (limited to 'bot.py')
-rwxr-xr-x | bot.py | 289 |
1 files changed, 289 insertions, 0 deletions
@@ -0,0 +1,289 @@ | |||
1 | # -*- coding: utf-8 -*- | ||
2 | |||
3 | import os | ||
4 | import re | ||
5 | import time | ||
6 | import json | ||
7 | import logging | ||
8 | import platform | ||
9 | import urllib | ||
10 | from selenium import webdriver | ||
11 | |||
12 | import telegram | ||
13 | from telegram.error import NetworkError, Unauthorized | ||
14 | from pymongo import MongoClient | ||
15 | |||
16 | import ingrex | ||
17 | |||
18 | Debug = True | ||
19 | bot = None | ||
20 | BOT_TOKEN = '' | ||
21 | CHANNEL_NAME = '' | ||
22 | Email = '' | ||
23 | Passwd = '' | ||
24 | PhantomjsPath = '' | ||
25 | |||
26 | LOG_FILENAME = 'voh.log' | ||
27 | logging.basicConfig(level = logging.DEBUG, | ||
28 | filename = LOG_FILENAME, | ||
29 | filemode='w') | ||
30 | console = logging.StreamHandler() | ||
31 | console.setLevel(logging.INFO) | ||
32 | # set a format which is simpler for console use | ||
33 | formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') | ||
34 | # tell the handler to use this format | ||
35 | console.setFormatter(formatter) | ||
36 | # add the handler to the root logger | ||
37 | logging.getLogger('').addHandler(console) | ||
38 | |||
39 | class CookieException(Exception): | ||
40 | ''' CookieError ''' | ||
41 | |||
42 | def getTime(): | ||
43 | return time.strftime('%x %X %Z') | ||
44 | |||
45 | def readConfig(): | ||
46 | global Email | ||
47 | global Passwd | ||
48 | global BOT_TOKEN | ||
49 | global CHANNEL_NAME | ||
50 | global PhantomjsPath | ||
51 | |||
52 | configfile = open("./config.json") | ||
53 | config = json.load(configfile) | ||
54 | Email = config["Email"] | ||
55 | Passwd = config["Passwd"] | ||
56 | BOT_TOKEN = config["BOT_TOKEN"] | ||
57 | CHANNEL_NAME = config["CHANNEL_NAME"] | ||
58 | |||
59 | osname = platform.system() | ||
60 | if osname == "Windows": | ||
61 | PhantomjsPath = 'C:\\Users\\LuciaHydrion\\AppData\\Roaming\\npm\\phantomjs.cmd' | ||
62 | elif osname == "Linux": | ||
63 | PhantomjsPath = '/home/clarkzjw/code/phantomjs-2.1.1-linux-i686/bin/phantomjs' | ||
64 | os.environ['TZ'] = 'Asia/Shanghai' | ||
65 | time.tzset() | ||
66 | |||
67 | def fetchCookie(): | ||
68 | global Debug | ||
69 | global Email | ||
70 | global Passwd | ||
71 | global PhantomjsPath | ||
72 | |||
73 | logger = logging.getLogger('fetchCookie') | ||
74 | logger.info(getTime() + ': Fetching Cookie...') | ||
75 | |||
76 | driver = webdriver.PhantomJS(PhantomjsPath) | ||
77 | driver.get('https://www.ingress.com/intel') | ||
78 | |||
79 | # get login page | ||
80 | link = driver.find_elements_by_tag_name('a')[0].get_attribute('href') | ||
81 | driver.get(link) | ||
82 | if Debug: | ||
83 | driver.get_screenshot_as_file('1.png') | ||
84 | # simulate manual login | ||
85 | driver.set_page_load_timeout(10) | ||
86 | driver.set_script_timeout(20) | ||
87 | driver.find_element_by_id('Email').send_keys(Email) | ||
88 | if Debug: | ||
89 | driver.get_screenshot_as_file('2.png') | ||
90 | driver.find_element_by_css_selector('#next').click() | ||
91 | time.sleep(3) | ||
92 | driver.find_element_by_id('Passwd').send_keys(Passwd) | ||
93 | if Debug: | ||
94 | driver.get_screenshot_as_file('3.png') | ||
95 | driver.find_element_by_css_selector('#signIn').click() | ||
96 | time.sleep(3) | ||
97 | if Debug: | ||
98 | driver.get_screenshot_as_file('3.png') | ||
99 | # get cookies | ||
100 | temp = driver.get_cookies() | ||
101 | |||
102 | csrftoken = '' | ||
103 | SACSID = '' | ||
104 | for a in temp: | ||
105 | if (a['name'] == 'csrftoken'): | ||
106 | csrftoken = a['value'] | ||
107 | if (a['name'] == 'SACSID'): | ||
108 | SACSID = a['value'] | ||
109 | |||
110 | if csrftoken == '' or SACSID == '': | ||
111 | logger.error(getTime() + ': Fetch Cookie Failed') | ||
112 | raise CookieException | ||
113 | |||
114 | with open('cookie', 'w') as file: | ||
115 | cookie = 'SACSID='+SACSID+'; csrftoken='+csrftoken+'; ingress.intelmap.shflt=viz; ingress.intelmap.lat=29.098418372855484; ingress.intelmap.lng=119.81689453125; ingress.intelmap.zoom=17' | ||
116 | file.write(cookie) | ||
117 | |||
118 | driver.quit() | ||
119 | logger.info(getTime() + ': Fetching Cookie Succeed') | ||
120 | return True | ||
121 | |||
122 | def sendMessge(bot, msg): | ||
123 | "sendMsg" | ||
124 | |||
125 | logger = logging.getLogger('sendMessage') | ||
126 | while True: | ||
127 | try: | ||
128 | url = 'https://api.telegram.org/bot' | ||
129 | url += BOT_TOKEN | ||
130 | url += '/sendMessage?chat_id=' | ||
131 | url += CHANNEL_NAME | ||
132 | url += '&text=' | ||
133 | url += urllib.parse.quote(msg) | ||
134 | |||
135 | req = urllib.request.Request(url, headers={'Content-Type': 'application/x-www-form-urlencoded'}) | ||
136 | resp = urllib.request.urlopen(req) | ||
137 | data = resp.read() | ||
138 | |||
139 | #bot.sendMessage(chat_id=CHANNEL_NAME, text=msg) | ||
140 | logger.info(getTime() + ": sendMsg " + msg) | ||
141 | break | ||
142 | except NetworkError: | ||
143 | time.sleep(1) | ||
144 | |||
145 | def sendMonitor(bot, msg): | ||
146 | logger = logging.getLogger('sendMonitor') | ||
147 | while True: | ||
148 | try: | ||
149 | bot.sendMessage(chat_id="@voamonitor", text=msg) | ||
150 | logger.info(getTime() + ": sendMsg " + msg) | ||
151 | break | ||
152 | except NetworkError: | ||
153 | time.sleep(1) | ||
154 | |||
155 | def formatMessage(raw): | ||
156 | pattern = re.compile('xmps.biz|enl.sh|ingressfarm.com|Polygon') | ||
157 | match = pattern.search(str(raw)) | ||
158 | if match: | ||
159 | return "Blocked" | ||
160 | |||
161 | msg = '' | ||
162 | plext = raw[2]['plext'] | ||
163 | markup = plext['markup'] | ||
164 | plaintext = plext['text'] | ||
165 | |||
166 | for mark in markup: | ||
167 | if mark[0] == 'SECURE': | ||
168 | msg += mark[1]['plain'] | ||
169 | elif mark[0] == 'SENDER': | ||
170 | player = mark[1]['plain'] | ||
171 | team = mark[1]['team'] | ||
172 | |||
173 | pattern = re.compile(':') | ||
174 | match = pattern.search(player) | ||
175 | if match: | ||
176 | if team == 'RESISTANCE': | ||
177 | player = player[:match.span()[0]] + ' 🐳' + player[match.span()[0]:] | ||
178 | elif team == 'ENLIGHTENED': | ||
179 | player = player[:match.span()[0]] + ' 🐸' + player[match.span()[0]:] | ||
180 | msg += player | ||
181 | |||
182 | elif mark[0] == 'PLAYER' or mark[0] == 'AT_PLAYER': | ||
183 | player = mark[1]['plain'] | ||
184 | team = mark[1]['team'] | ||
185 | |||
186 | msg += player | ||
187 | if team == 'RESISTANCE': | ||
188 | msg += ' 🐳' | ||
189 | elif team == 'ENLIGHTENED': | ||
190 | msg += ' 🐸' | ||
191 | |||
192 | elif mark[0] == 'TEXT': | ||
193 | msg += mark[1]['plain'] | ||
194 | |||
195 | pattern = re.compile('\[secure\]') | ||
196 | match = pattern.search(msg) | ||
197 | if match: | ||
198 | if msg.find(':') != -1: | ||
199 | msg = msg[:9] + '@' + msg[9:] | ||
200 | else: | ||
201 | msg = msg[:10] + '@' + msg[10:] | ||
202 | else: | ||
203 | msg = '@' + msg | ||
204 | |||
205 | return msg | ||
206 | |||
207 | def insertDB(time, msg): | ||
208 | logger = logging.getLogger('insertDB') | ||
209 | Conn = MongoClient() | ||
210 | database = Conn['COMM_Hangzhou'] | ||
211 | mycollection = database.entries | ||
212 | post = {"time": time, "msg": msg} | ||
213 | mycollection.insert(post) | ||
214 | |||
215 | |||
216 | def main(): | ||
217 | logger = logging.getLogger('main') | ||
218 | |||
219 | field = { | ||
220 | 'minLngE6':119618783, | ||
221 | 'minLatE6':29912919, | ||
222 | 'maxLngE6':121018722, | ||
223 | 'maxLatE6':30573739, | ||
224 | } | ||
225 | |||
226 | mints = -1 | ||
227 | maxts=-1 | ||
228 | reverse=False | ||
229 | tab='all' | ||
230 | |||
231 | while True: | ||
232 | try: | ||
233 | if fetchCookie(): | ||
234 | break | ||
235 | except CookieException: | ||
236 | time.sleep(3) | ||
237 | |||
238 | count = 0 | ||
239 | while True: | ||
240 | count += 1 | ||
241 | |||
242 | with open('cookie') as cookies: | ||
243 | cookies = cookies.read().strip() | ||
244 | |||
245 | logger.info(getTime() + ": {} Fetching from Intel...".format(str(count))) | ||
246 | |||
247 | while True: | ||
248 | try: | ||
249 | |||
250 | intel = ingrex.Intel(cookies, field) | ||
251 | result = intel.fetch_msg(mints, maxts, reverse, tab) | ||
252 | |||
253 | if result: | ||
254 | mints = result[0][1] + 1 | ||
255 | break | ||
256 | except CookieError: | ||
257 | while True: | ||
258 | try: | ||
259 | if fetchCookie(): | ||
260 | break | ||
261 | except CookieException: | ||
262 | time.sleep(3) | ||
263 | |||
264 | for item in result[::-1]: | ||
265 | message = ingrex.Message(item) | ||
266 | if message.ptype == 'PLAYER_GENERATED': | ||
267 | logger.info(getTime() + str(item)) | ||
268 | |||
269 | msg = formatMessage(item) | ||
270 | if msg == 'Blocked': | ||
271 | logger.info(getTime() + " " + message.text) | ||
272 | else: | ||
273 | msg = message.time + " " + msg | ||
274 | logger.info(getTime() + " " + msg) | ||
275 | insertDB(message.time, msg) | ||
276 | sendMonitor(bot, msg) | ||
277 | #sendMessge(bot, msg) | ||
278 | |||
279 | time.sleep(10) | ||
280 | |||
281 | if __name__ == '__main__': | ||
282 | readConfig() | ||
283 | bot = telegram.Bot(BOT_TOKEN) | ||
284 | |||
285 | while True: | ||
286 | try: | ||
287 | main() | ||
288 | except Exception: | ||
289 | sendMonitor(bot, 'Main Error') | ||