Guest User

Untitled

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