Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.08 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. line.client
  4. ~~~~~~~~~~~
  5.  
  6. LineClient for sending and receiving message from LINE server.
  7.  
  8. :copyright: (c) 2014 by Taehoon Kim.
  9. :license: BSD, see LICENSE for more details.
  10. """
  11.  
  12. import re
  13. import requests
  14. import sys
  15. import subprocess
  16.  
  17.  
  18. from api import LineAPI
  19. from models import LineGroup, LineContact, LineRoom, LineMessage
  20. from curve.ttypes import TalkException, ToType, OperationType, Provider
  21.  
  22. reload(sys)
  23. sys.setdefaultencoding("utf-8")
  24.  
  25. EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
  26.  
  27. botlist = ['ud9f316566d773ba7fcdfb1b85ee40178','u9eed12fd9f5fa312a49e1360d08c9026','ud33da8414f156e935ee0a99b83b4eae9','u93af4f2035a5c8e6174da337144c8641','uf1c773a67d02c8b4ac5adbb7f0942abd','u7d60e3749adf8e209936887cf43555a7','u6d1da35f0c81283466843b7c4efcecc0']
  28. kik = []
  29. myBot = ['ubfe819b3ed180757b9dba0a03fbf5581','u205e00175e0be96d571a70021cb0492a','u1bb4d4e9115180999e74726a4b9fe392''uf418cf9fa2e83a1bd19b8c375dd876b1','u236b88bf1eac2b90e848a6198152e647','u2fa53083615576ab118eb021741c6bfa']
  30. admin = ['u205e00175e0be96d571a70021cb0492a','u1bb4d4e9115180999e74726a4b9fe392']
  31. def check_auth(func):
  32. def wrapper_check_auth(*args, **kwargs):
  33. if args[0]._check_auth():
  34. return func(*args, **kwargs)
  35. return wrapper_check_auth
  36.  
  37. class LineClient(LineAPI):
  38. profile = None
  39. contacts = []
  40. rooms = []
  41. groups = []
  42.  
  43. def __init__(self, id=None, password=None, authToken=None, is_mac=True, com_name="carpedm20"):
  44. """Provide a way to communicate with LINE server.
  45.  
  46. :param id: `NAVER id` or `LINE email`
  47. :param password: LINE account password
  48. :param authToken: LINE session key
  49. :param is_mac: (optional) os setting
  50. :param com_name: (optional) name of your system
  51.  
  52. >>> client = LineClient("carpedm20", "xxxxxxxxxx")
  53. Enter PinCode '9779' to your mobile phone in 2 minutes
  54. >>> client = LineClient("carpedm20@gmail.com", "xxxxxxxxxx")
  55. Enter PinCode '7390' to your mobile phone in 2 minutes
  56. >>> client = LineClient(authToken="xxx ... xxx")
  57. True
  58. """
  59. LineAPI.__init__(self)
  60.  
  61. if not (authToken or id and password):
  62. msg = "id and password or authToken is needed"
  63. self.raise_error(msg)
  64.  
  65. if is_mac:
  66. os_version = "10.9.4-MAVERICKS-x64"
  67. user_agent = "DESKTOP:MAC:%s(%s)" % (os_version, self.version)
  68. app = "DESKTOPMAC\t%s\tMAC\t%s" % (self.version, os_version)
  69. else:
  70. os_version = "5.1.2600-XP-x64"
  71. user_agent = "DESKTOP:WIN:%s(%s)" % (os_version, self.version)
  72. app = "DESKTOPWIN\t%s\tWINDOWS\t%s" % (self.version, os_version)
  73.  
  74. if com_name:
  75. self.com_name = com_name
  76.  
  77. self._headers['User-Agent'] = user_agent
  78. # self._headers['X-Line-Application'] = app
  79.  
  80. if authToken:
  81. self.authToken = self._headers['X-Line-Access'] = authToken
  82.  
  83. self.tokenLogin()
  84. #self.ready()
  85. else:
  86. if EMAIL_REGEX.match(id):
  87. self.provider = Provider.LINE # LINE
  88. else:
  89. self.provider = Provider.NAVER_KR # NAVER
  90.  
  91. self.id = id
  92. self.password = password
  93. self.is_mac = is_mac
  94.  
  95. self.login()
  96. self.ready()
  97.  
  98. self.revision = self._getLastOpRevision()
  99. self.getProfile()
  100.  
  101. try:
  102. self.refreshGroups()
  103. except: pass
  104.  
  105. try:
  106. self.refreshContacts()
  107. except: pass
  108.  
  109. try:
  110. self.refreshActiveRooms()
  111. except: pass
  112.  
  113. @check_auth
  114. def getProfile(self):
  115. """Get `profile` of LINE account"""
  116. self.profile = LineContact(self, self._getProfile())
  117.  
  118. return self.profile
  119.  
  120. def getContactByName(self, name):
  121. """Get a `contact` by name
  122.  
  123. :param name: name of a `contact`
  124. """
  125. for contact in self.contacts:
  126. if name == contact.name:
  127. return contact
  128.  
  129. return None
  130.  
  131. def getContactById(self, id):
  132. """Get a `contact` by id
  133.  
  134. :param id: id of a `contact`
  135. """
  136. for contact in self.contacts:
  137. if contact.id == id:
  138. return contact
  139. if self.profile:
  140. if self.profile.id == id:
  141. return self.profile
  142.  
  143. return None
  144.  
  145. def getContactOrRoomOrGroupById(self, id):
  146. """Get a `contact` or `room` or `group` by its id
  147.  
  148. :param id: id of a instance
  149. """
  150. return self.getContactById(id)\
  151. or self.getRoomById(id)\
  152. or self.getGroupById(id)
  153.  
  154. @check_auth
  155. def refreshGroups(self):
  156. """Refresh groups of LineClient"""
  157. self.groups = []
  158.  
  159. self.addGroupsWithIds(self._getGroupIdsJoined())
  160. self.addGroupsWithIds(self._getGroupIdsInvited(), False)
  161.  
  162. @check_auth
  163. def addGroupsWithIds(self, group_ids, is_joined=True):
  164. """Refresh groups of LineClient"""
  165. new_groups = self._getGroups(group_ids)
  166.  
  167. self.groups += [LineGroup(self, group, is_joined) for group in new_groups]
  168.  
  169. self.groups.sort()
  170.  
  171. @check_auth
  172. def refreshContacts(self):
  173. """Refresh contacts of LineClient """
  174. contact_ids = self._getAllContactIds()
  175. contacts = self._getContacts(contact_ids)
  176.  
  177. self.contacts = [LineContact(self, contact) for contact in contacts]
  178.  
  179. self.contacts.sort()
  180.  
  181. @check_auth
  182. def findAndAddContactByUserid(self, userid):
  183. """Find and add a `contact` by userid
  184.  
  185. :param userid: user id
  186. """
  187. try:
  188. contact = self._findAndAddContactsByUserid(userid)
  189. except TalkException as e:
  190. self.raise_error(e.reason)
  191.  
  192. contact = contact.values()[0]
  193.  
  194. for c in self.contacts:
  195. if c.id == contact.mid:
  196. self.raise_error("%s already exists" % contact.displayName)
  197. return
  198.  
  199. c = LineContact(self, contact)
  200. self.contacts.append(c)
  201.  
  202. self.contacts.sort()
  203. return c
  204.  
  205. @check_auth
  206. def _findAndAddContactByPhone(self, phone):
  207. """Find and add a `contact` by phone number
  208.  
  209. :param phone: phone number (unknown format)
  210. """
  211. try:
  212. contact = self._findAndAddContactsByPhone(phone)
  213. except TalkException as e:
  214. self.raise_error(e.reason)
  215.  
  216. contact = contact.values()[0]
  217.  
  218. for c in self.contacts:
  219. if c.id == contact.mid:
  220. self.raise_error("%s already exists" % contact.displayName)
  221. return
  222.  
  223. c = LineContact(self, contact)
  224. self.contacts.append(c)
  225.  
  226. self.contacts.sort()
  227. return c
  228.  
  229. @check_auth
  230. def _findAndAddContactByEmail(self, email):
  231. """Find and add a `contact` by email
  232.  
  233. :param email: email
  234. """
  235. try:
  236. contact = self._findAndAddContactsByEmail(email)
  237. except TalkException as e:
  238. self.raise_error(e.reason)
  239.  
  240. contact = contact.values()[0]
  241.  
  242. for c in self.contacts:
  243. if c.id == contact.mid:
  244. self.raise_error("%s already exists" % contact.displayName)
  245. return
  246.  
  247. c = LineContact(self, contact)
  248. self.contacts.append(c)
  249.  
  250. self.contacts.sort()
  251. return c
  252.  
  253. @check_auth
  254. def _findContactByUserid(self, userid):
  255. """Find a `contact` by userid
  256.  
  257. :param userid: user id
  258. """
  259. try:
  260. contact = self._findContactByUserid(userid)
  261. except TalkException as e:
  262. self.raise_error(e.reason)
  263.  
  264. return LineContact(self, contact)
  265.  
  266. @check_auth
  267. def refreshActiveRooms(self):
  268. """Refresh active chat rooms"""
  269. start = 1
  270. count = 50
  271.  
  272. self.rooms = []
  273.  
  274. while True:
  275. channel = self._getMessageBoxCompactWrapUpList(start, count)
  276.  
  277. for box in channel.messageBoxWrapUpList:
  278. if box.messageBox.midType == ToType.ROOM:
  279. room = LineRoom(self, self._getRoom(box.messageBox.id))
  280. self.rooms.append(room)
  281.  
  282. if len(channel.messageBoxWrapUpList) == count:
  283. start += count
  284. else:
  285. break
  286.  
  287. @check_auth
  288. def createGroupWithIds(self, name, ids=[]):
  289. """Create a group with contact ids
  290.  
  291. :param name: name of group
  292. :param ids: list of contact ids
  293. """
  294. try:
  295. group = LineGroup(self, self._createGroup(name, ids))
  296. self.groups.append(group)
  297.  
  298. return group
  299. except Exception as e:
  300. self.raise_error(e)
  301.  
  302. return None
  303.  
  304. @check_auth
  305. def createGroupWithContacts(self, name, contacts=[]):
  306. """Create a group with contacts
  307.  
  308. :param name: name of group
  309. :param contacts: list of contacts
  310. """
  311. try:
  312. contact_ids = []
  313. for contact in contacts:
  314. contact_ids.append(contact.id)
  315.  
  316. group = LineGroup(self, self._createGroup(name, contact_ids))
  317. self.groups.append(group)
  318.  
  319. return group
  320. except Exception as e:
  321. self.raise_error(e)
  322.  
  323. return None
  324.  
  325. def getGroupByName(self, name):
  326. """Get a group by name
  327.  
  328. :param name: name of a group
  329. """
  330. for group in self.groups:
  331. if name == group.name:
  332. return group
  333.  
  334. return None
  335.  
  336. def getGroupById(self, id):
  337. """Get a group by id
  338.  
  339. :param id: id of a group
  340. """
  341. for group in self.groups:
  342. if group.id == id:
  343. return group
  344.  
  345. return None
  346.  
  347. @check_auth
  348. def inviteIntoGroup(self, group, contacts=[]):
  349. """Invite contacts into group
  350.  
  351. :param group: LineGroup instance
  352. :param contacts: LineContact instances to invite
  353. """
  354. contact_ids = [contact.id for contact in contacts]
  355. self._inviteIntoGroup(group.id, contact_ids)
  356.  
  357. def acceptGroupInvitation(self, group):
  358. """Accept a group invitation
  359.  
  360. :param group: LineGroup instance
  361. """
  362. if self._check_auth():
  363. try:
  364. self._acceptGroupInvitation(group.id)
  365. return True
  366. except Exception as e:
  367. self.raise_error(e)
  368. return False
  369.  
  370. @check_auth
  371. def leaveGroup(self, group):
  372. """Leave a group
  373.  
  374. :param group: LineGroup instance to leave
  375. """
  376. try:
  377. self._leaveGroup(group.id)
  378. self.groups.remove(group)
  379.  
  380. return True
  381. except Exception as e:
  382. self.raise_error(e)
  383.  
  384. return False
  385.  
  386. @check_auth
  387. def createRoomWithIds(self, ids=[]):
  388. """Create a chat room with contact ids"""
  389. try:
  390. room = LineRoom(self, self._createRoom(ids))
  391. self.rooms.append(room)
  392.  
  393. return room
  394. except Exception as e:
  395. self.raise_error(e)
  396.  
  397. return None
  398.  
  399. @check_auth
  400. def createRoomWithContacts(self, contacts=[]):
  401. """Create a chat room with contacts"""
  402. try:
  403. contact_ids = []
  404. for contact in contacts:
  405. contact_ids.append(contact.id)
  406.  
  407. room = LineRoom(self, self._createRoom(contact_ids))
  408. self.rooms.append(room)
  409.  
  410. return room
  411. except Exception as e:
  412. self.raise_error(e)
  413.  
  414. return None
  415.  
  416. def getRoomById(self, id):
  417. """Get a room by id
  418.  
  419. :param id: id of a room
  420. """
  421. for room in self.rooms:
  422. if room.id == id:
  423. return room
  424.  
  425. return None
  426.  
  427. @check_auth
  428. def inviteIntoRoom(self, room, contacts=[]):
  429. """Invite contacts into room
  430.  
  431. :param room: LineRoom instance
  432. :param contacts: LineContact instances to invite
  433. """
  434. contact_ids = [contact.id for contact in contacts]
  435. self._inviteIntoRoom(room.id, contact_ids)
  436.  
  437. @check_auth
  438. def leaveRoom(self, room):
  439. """Leave a room
  440.  
  441. :param room: LineRoom instance to leave
  442. """
  443. try:
  444. self._leaveRoom(room.id)
  445. self.rooms.remove(room)
  446.  
  447. return True
  448. except Exception as e:
  449. self.raise_error(e)
  450.  
  451. return False
  452.  
  453. @check_auth
  454. def sendMessage(self, message, seq=0):
  455. """Send a message
  456.  
  457. :param message: LineMessage instance to send
  458. """
  459. try:
  460. return self._sendMessage(message, seq)
  461. except TalkException as e:
  462. self.updateAuthToken()
  463. try:
  464. return self._sendMessage(message, seq)
  465. except Exception as e:
  466. self.raise_error(e)
  467.  
  468. return False
  469.  
  470. @check_auth
  471. def getMessageBox(self, id):
  472. """Get MessageBox by id
  473.  
  474. :param id: `contact` id or `group` id or `room` id
  475. """
  476. try:
  477. messageBoxWrapUp = self._getMessageBoxCompactWrapUp(id)
  478.  
  479. return messageBoxWrapUp.messageBox
  480. except:
  481. return None
  482.  
  483. @check_auth
  484. def getRecentMessages(self, messageBox, count):
  485. """Get recent message from MessageBox
  486.  
  487. :param messageBox: MessageBox object
  488. """
  489. id = messageBox.id
  490. messages = self._getRecentMessages(id, count)
  491.  
  492. return self.getLineMessageFromMessage(messages)
  493.  
  494. @check_auth
  495. def longPoll(self, count=50, debug=False):
  496. """Receive a list of operations that have to be processed by original
  497. Line cleint.
  498.  
  499. :param count: number of operations to get from
  500. :returns: a generator which returns operations
  501.  
  502. >>> for op in client.longPoll():
  503. sender = op[0]
  504. receiver = op[1]
  505. message = op[2]
  506. print "%s->%s : %s" % (sender, receiver, message)
  507. """
  508. """Check is there any operations from LINE server"""
  509. OT = OperationType
  510.  
  511. try:
  512. operations = self._fetchOperations(self.revision, count)
  513. except EOFError:
  514. return
  515. except TalkException as e:
  516. if e.code == 9:
  517. self.raise_error("user logged in to another machine")
  518. else:
  519. return
  520.  
  521. for operation in operations:
  522. if debug:
  523. print operation
  524. if operation.type == OT.END_OF_OPERATION:
  525. pass
  526. elif operation.type == OT.SEND_MESSAGE:
  527. pass
  528. elif operation.type == OT.NOTIFIED_INVITE_INTO_GROUP:
  529.  
  530. try:
  531. NameData = self._getContacts([operation.param3])
  532. lowerName = NameData[0].displayName.lower()
  533. requestID = operation.param2
  534.  
  535. if requestID is operation.param2:
  536. self._acceptGroupInvitation(operation.param1)
  537. else:
  538. self._cancelGroupInvitation(operation.param1,operation.param3)
  539. except:
  540. print "cannot!"
  541. elif operation.type == OT.RECEIVE_MESSAGE:
  542. message = LineMessage(self, operation.message)
  543.  
  544. raw_sender = operation.message._from
  545. raw_receiver = operation.message.to
  546.  
  547. sender = self.getContactOrRoomOrGroupById(raw_sender)
  548. receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  549.  
  550. # If sender is not found, check member list of group chat sent to
  551. if sender is None:
  552. try:
  553. for m in receiver.members:
  554. if m.id == raw_sender:
  555. sender = m
  556. break
  557. except (AttributeError, TypeError):
  558. pass
  559.  
  560. # If sender is not found, check member list of room chat sent to
  561. if sender is None:
  562. try:
  563. for m in receiver.contacts:
  564. if m.id == raw_sender:
  565. sender = m
  566. break
  567. except (AttributeError, TypeError):
  568. pass
  569.  
  570. if sender is None or receiver is None:
  571. self.refreshGroups()
  572. self.refreshContacts()
  573. self.refreshActiveRooms()
  574.  
  575. sender = self.getContactOrRoomOrGroupById(raw_sender)
  576. receiver = self.getContactOrRoomOrGroupById(raw_receiver)
  577.  
  578. if sender is None or receiver is None:
  579. contacts = self._getContacts([raw_sender, raw_receiver])
  580. if contacts:
  581. if len(contacts) == 2:
  582. sender = LineContact(self, contacts[0])
  583. receiver = LineContact(self, contacts[1])
  584.  
  585. yield (sender, receiver, message)
  586. elif operation.type in [ 60, 61 ]:
  587. pass
  588. else:
  589. if OT._VALUES_TO_NAMES[operation.type] == 'NOTIFIED_READ_MESSAGE':
  590. proc=subprocess.Popen('echo "'+ operation.param2+'|'+operation.param1+'|'+str(operation.createdTime)+'" >> Output.txt', shell=True, stdout=subprocess.PIPE, )
  591. if OT._VALUES_TO_NAMES[operation.type] == 'NOTIFIED_KICKOUT_FROM_GROUP':
  592. if operation.param1 and operation.param2 in admin:
  593. print 'Allowed'
  594. else:
  595. if operation.param3 in myBot:
  596. try:
  597. thisgroup = self.getGroupById(operation.param1)
  598. self.refreshGroups();
  599. if thisgroup is not None:
  600. self._kickoutFromGroup(operation.param1,[operation.param2])
  601. self._inviteIntoGroup(operation.param1,[operation.param3])
  602. except Exception, e:
  603. print 'failed'
  604. proc=subprocess.Popen('echo "'+ operation.param2+'" >> kickersz.txt;cat kickersz.txt', shell=True, stdout=subprocess.PIPE, )
  605. output=proc.communicate()[0]
  606. spl = output.split('\n')
  607. print len(spl)
  608. if len(spl) > 1 :
  609. totals = spl.count(operation.param2)
  610. if totals > 0 :
  611. try:
  612. self._kickoutFromGroup(operation.param1,[operation.param2])
  613. proc=subprocess.Popen('echo "" > kickersz.txt', shell=True, stdout=subprocess.PIPE, )
  614. except Exception, e:
  615. print 'yor not related'
  616.  
  617. print "[*] %s" % OT._VALUES_TO_NAMES[operation.type]
  618. print operation
  619.  
  620. self.revision = max(operation.revision, self.revision)
  621.  
  622. def createContactOrRoomOrGroupByMessage(self, message):
  623. if message.toType == ToType.USER:
  624. pass
  625. elif message.toType == ToType.ROOM:
  626. pass
  627. elif message.toType == ToType.GROUP:
  628. pass
  629.  
  630. def getLineMessageFromMessage(self, messages=[]):
  631. """Change Message objects to LineMessage objects
  632.  
  633. :param messges: list of Message object
  634. """
  635. return [LineMessage(self, message) for message in messages]
  636.  
  637. def _check_auth(self):
  638. """Check if client is logged in or not"""
  639. if self.authToken:
  640. return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement