signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def deleteThreads(self, thread_ids):
|
thread_ids = require_list(thread_ids)<EOL>data_unpin = dict()<EOL>data_delete = dict()<EOL>for i, thread_id in enumerate(thread_ids):<EOL><INDENT>data_unpin["<STR_LIT>".format(thread_id)] = "<STR_LIT:false>"<EOL>data_delete["<STR_LIT>".format(i)] = thread_id<EOL><DEDENT>r_unpin = self._post(self.req_url.PINNED_STATUS, data_unpin)<EOL>r_delete = self._post(self.req_url.DELETE_THREAD, data_delete)<EOL>return r_unpin.ok and r_delete.ok<EOL>
|
Deletes threads
:param thread_ids: Thread IDs to delete. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
|
f8726:c0:m109
|
def markAsSpam(self, thread_id=None):
|
thread_id, thread_type = self._getThread(thread_id, None)<EOL>r = self._post(self.req_url.MARK_SPAM, {"<STR_LIT:id>": thread_id})<EOL>return r.ok<EOL>
|
Mark a thread as spam and delete it
:param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads`
:return: Whether the request was successful
:raises: FBchatException if request failed
|
f8726:c0:m110
|
def deleteMessages(self, message_ids):
|
message_ids = require_list(message_ids)<EOL>data = dict()<EOL>for i, message_id in enumerate(message_ids):<EOL><INDENT>data["<STR_LIT>".format(i)] = message_id<EOL><DEDENT>r = self._post(self.req_url.DELETE_MESSAGES, data)<EOL>return r.ok<EOL>
|
Deletes specifed messages
:param message_ids: Message IDs to delete
:return: Whether the request was successful
:raises: FBchatException if request failed
|
f8726:c0:m111
|
def muteThread(self, mute_time=-<NUM_LIT:1>, thread_id=None):
|
thread_id, thread_type = self._getThread(thread_id, None)<EOL>data = {"<STR_LIT>": str(mute_time), "<STR_LIT>": thread_id}<EOL>content = self._post(self.req_url.MUTE_THREAD, data, fix_request=True)<EOL>
|
Mutes thread
:param mute_time: Mute time in seconds, leave blank to mute forever
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
|
f8726:c0:m112
|
def unmuteThread(self, thread_id=None):
|
return self.muteThread(<NUM_LIT:0>, thread_id)<EOL>
|
Unmutes thread
:param thread_id: User/Group ID to unmute. See :ref:`intro_threads`
|
f8726:c0:m113
|
def muteThreadReactions(self, mute=True, thread_id=None):
|
thread_id, thread_type = self._getThread(thread_id, None)<EOL>data = {"<STR_LIT>": int(mute), "<STR_LIT>": thread_id}<EOL>r = self._post(self.req_url.MUTE_REACTIONS, data, fix_request=True)<EOL>
|
Mutes thread reactions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
|
f8726:c0:m114
|
def unmuteThreadReactions(self, thread_id=None):
|
return self.muteThreadReactions(False, thread_id)<EOL>
|
Unmutes thread reactions
:param thread_id: User/Group ID to unmute. See :ref:`intro_threads`
|
f8726:c0:m115
|
def muteThreadMentions(self, mute=True, thread_id=None):
|
thread_id, thread_type = self._getThread(thread_id, None)<EOL>data = {"<STR_LIT>": int(mute), "<STR_LIT>": thread_id}<EOL>r = self._post(self.req_url.MUTE_MENTIONS, data, fix_request=True)<EOL>
|
Mutes thread mentions
:param mute: Boolean. True to mute, False to unmute
:param thread_id: User/Group ID to mute. See :ref:`intro_threads`
|
f8726:c0:m116
|
def unmuteThreadMentions(self, thread_id=None):
|
return self.muteThreadMentions(False, thread_id)<EOL>
|
Unmutes thread mentions
:param thread_id: User/Group ID to unmute. See :ref:`intro_threads`
|
f8726:c0:m117
|
def _pullMessage(self):
|
data = {<EOL>"<STR_LIT>": <NUM_LIT:0>,<EOL>"<STR_LIT>": self._sticky,<EOL>"<STR_LIT>": self._pool,<EOL>"<STR_LIT>": self._client_id,<EOL>"<STR_LIT:state>": "<STR_LIT>" if self._markAlive else "<STR_LIT>",<EOL>}<EOL>return self._get(self.req_url.STICKY, data, fix_request=True, as_json=True)<EOL>
|
Call pull api with seq value to get message data.
|
f8726:c0:m119
|
def _parseMessage(self, content):
|
self._seq = content.get("<STR_LIT>", "<STR_LIT:0>")<EOL>if "<STR_LIT>" in content:<EOL><INDENT>self._sticky = content["<STR_LIT>"]["<STR_LIT>"]<EOL>self._pool = content["<STR_LIT>"]["<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in content:<EOL><INDENT>for batch in content["<STR_LIT>"]:<EOL><INDENT>self._parseMessage(batch)<EOL><DEDENT><DEDENT>if "<STR_LIT>" not in content:<EOL><INDENT>return<EOL><DEDENT>for m in content["<STR_LIT>"]:<EOL><INDENT>mtype = m.get("<STR_LIT:type>")<EOL>try:<EOL><INDENT>if mtype == "<STR_LIT>":<EOL><INDENT>self._parseDelta(m)<EOL><DEDENT>elif mtype == "<STR_LIT>":<EOL><INDENT>self.onInbox(<EOL>unseen=m["<STR_LIT>"],<EOL>unread=m["<STR_LIT>"],<EOL>recent_unread=m["<STR_LIT>"],<EOL>msg=m,<EOL>)<EOL><DEDENT>elif mtype == "<STR_LIT>" or mtype == "<STR_LIT>":<EOL><INDENT>author_id = str(m.get("<STR_LIT>"))<EOL>thread_id = m.get("<STR_LIT>")<EOL>if thread_id:<EOL><INDENT>thread_type = ThreadType.GROUP<EOL>thread_id = str(thread_id)<EOL><DEDENT>else:<EOL><INDENT>thread_type = ThreadType.USER<EOL>if author_id == self._uid:<EOL><INDENT>thread_id = m.get("<STR_LIT:to>")<EOL><DEDENT>else:<EOL><INDENT>thread_id = author_id<EOL><DEDENT><DEDENT>typing_status = TypingStatus(m.get("<STR_LIT>"))<EOL>self.onTyping(<EOL>author_id=author_id,<EOL>status=typing_status,<EOL>thread_id=thread_id,<EOL>thread_type=thread_type,<EOL>msg=m,<EOL>)<EOL><DEDENT>elif mtype in ["<STR_LIT>"]:<EOL><INDENT>from_id = m["<STR_LIT>"]<EOL>self.onFriendRequest(from_id=from_id, msg=m)<EOL><DEDENT>elif mtype == "<STR_LIT>":<EOL><INDENT>self.onQprimer(ts=m.get("<STR_LIT>"), msg=m)<EOL><DEDENT>elif mtype == "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>elif mtype == "<STR_LIT>":<EOL><INDENT>statuses = dict()<EOL>for id_, data in m.get("<STR_LIT>", {}).items():<EOL><INDENT>statuses[id_] = ActiveStatus._from_chatproxy_presence(id_, data)<EOL>self._buddylist[id_] = statuses[id_]<EOL><DEDENT>self.onChatTimestamp(buddylist=statuses, msg=m)<EOL><DEDENT>elif mtype == "<STR_LIT>":<EOL><INDENT>statuses = dict()<EOL>for id_, data in m.get("<STR_LIT>", {}).items():<EOL><INDENT>old_in_game = None<EOL>if id_ in self._buddylist:<EOL><INDENT>old_in_game = self._buddylist[id_].in_game<EOL><DEDENT>statuses[id_] = ActiveStatus._from_buddylist_overlay(<EOL>data, old_in_game<EOL>)<EOL>self._buddylist[id_] = statuses[id_]<EOL><DEDENT>self.onBuddylistOverlay(statuses=statuses, msg=m)<EOL><DEDENT>else:<EOL><INDENT>self.onUnknownMesssageType(msg=m)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>self.onMessageError(exception=e, msg=m)<EOL><DEDENT><DEDENT>
|
Get message and author name from content. May contain multiple messages in the content.
|
f8726:c0:m121
|
def startListening(self):
|
self.listening = True<EOL>
|
Start listening from an external event loop
:raises: FBchatException if request failed
|
f8726:c0:m122
|
def doOneListen(self, markAlive=None):
|
if markAlive is not None:<EOL><INDENT>self._markAlive = markAlive<EOL><DEDENT>try:<EOL><INDENT>if self._markAlive:<EOL><INDENT>self._ping()<EOL><DEDENT>content = self._pullMessage()<EOL>if content:<EOL><INDENT>self._parseMessage(content)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>return False<EOL><DEDENT>except requests.Timeout:<EOL><INDENT>pass<EOL><DEDENT>except requests.ConnectionError:<EOL><INDENT>time.sleep(<NUM_LIT:30>)<EOL><DEDENT>except FBchatFacebookError as e:<EOL><INDENT>if e.request_status_code in [<NUM_LIT>, <NUM_LIT>]:<EOL><INDENT>self.req_url.change_pull_channel()<EOL>self.startListening()<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>return self.onListenError(exception=e)<EOL><DEDENT>return True<EOL>
|
Does one cycle of the listening loop.
This method is useful if you want to control fbchat from an external event loop
.. warning::
`markAlive` parameter is deprecated now, use :func:`fbchat.Client.setActiveStatus`
or `markAlive` parameter in :func:`fbchat.Client.listen` instead.
:return: Whether the loop should keep running
:rtype: bool
|
f8726:c0:m123
|
def stopListening(self):
|
self.listening = False<EOL>self._sticky, self._pool = (None, None)<EOL>
|
Cleans up the variables from startListening
|
f8726:c0:m124
|
def listen(self, markAlive=None):
|
if markAlive is not None:<EOL><INDENT>self.setActiveStatus(markAlive)<EOL><DEDENT>self.startListening()<EOL>self.onListening()<EOL>while self.listening and self.doOneListen():<EOL><INDENT>pass<EOL><DEDENT>self.stopListening()<EOL>
|
Initializes and runs the listening loop continually
:param markAlive: Whether this should ping the Facebook server each time the loop runs
:type markAlive: bool
|
f8726:c0:m125
|
def setActiveStatus(self, markAlive):
|
self._markAlive = markAlive<EOL>
|
Changes client active status while listening
:param markAlive: Whether to show if client is active
:type markAlive: bool
|
f8726:c0:m126
|
def onLoggingIn(self, email=None):
|
log.info("<STR_LIT>".format(email))<EOL>
|
Called when the client is logging in
:param email: The email of the client
|
f8726:c0:m127
|
def on2FACode(self):
|
return input("<STR_LIT>")<EOL>
|
Called when a 2FA code is needed to progress
|
f8726:c0:m128
|
def onLoggedIn(self, email=None):
|
log.info("<STR_LIT>".format(email))<EOL>
|
Called when the client is successfully logged in
:param email: The email of the client
|
f8726:c0:m129
|
def onListening(self):
|
log.info("<STR_LIT>")<EOL>
|
Called when the client is listening
|
f8726:c0:m130
|
def onListenError(self, exception=None):
|
log.exception("<STR_LIT>")<EOL>return True<EOL>
|
Called when an error was encountered while listening
:param exception: The exception that was encountered
:return: Whether the loop should keep running
|
f8726:c0:m131
|
def onMessage(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>message=None,<EOL>message_object=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info("<STR_LIT>".format(message_object, thread_id, thread_type.name))<EOL>
|
Called when the client is listening, and somebody sends a message
:param mid: The message ID
:param author_id: The ID of the author
:param message: (deprecated. Use `message_object.text` instead)
:param message_object: The message (As a `Message` object)
:param thread_id: Thread ID that the message was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the message was sent to. See :ref:`intro_threads`
:param ts: The timestamp of the message
:param metadata: Extra metadata about the message
:param msg: A full set of the data recieved
:type message_object: models.Message
:type thread_type: models.ThreadType
|
f8726:c0:m132
|
def onColorChange(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>new_color=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, thread_id, thread_type.name, new_color<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody changes a thread's color
:param mid: The action ID
:param author_id: The ID of the person who changed the color
:param new_color: The new color
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type new_color: models.ThreadColor
:type thread_type: models.ThreadType
|
f8726:c0:m133
|
def onEmojiChange(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>new_emoji=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, thread_id, thread_type.name, new_emoji<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody changes a thread's emoji
:param mid: The action ID
:param author_id: The ID of the person who changed the emoji
:param new_emoji: The new emoji
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m134
|
def onTitleChange(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>new_title=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, thread_id, thread_type.name, new_title<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody changes the title of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the title
:param new_title: The new title
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m135
|
def onImageChange(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>new_image=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.GROUP,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info("<STR_LIT>".format(author_id, thread_id))<EOL>
|
Called when the client is listening, and somebody changes the image of a thread
:param mid: The action ID
:param author_id: The ID of the person who changed the image
:param new_image: The ID of the new image
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m136
|
def onNicknameChange(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>changed_for=None,<EOL>new_nickname=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, thread_id, thread_type.name, changed_for, new_nickname<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody changes the nickname of a person
:param mid: The action ID
:param author_id: The ID of the person who changed the nickname
:param changed_for: The ID of the person whom got their nickname changed
:param new_nickname: The new nickname
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m137
|
def onAdminAdded(<EOL>self,<EOL>mid=None,<EOL>added_id=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.GROUP,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info("<STR_LIT>".format(author_id, added_id, thread_id))<EOL>
|
Called when the client is listening, and somebody adds an admin to a group thread
:param mid: The action ID
:param added_id: The ID of the admin who got added
:param author_id: The ID of the person who added the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m138
|
def onAdminRemoved(<EOL>self,<EOL>mid=None,<EOL>removed_id=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.GROUP,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info("<STR_LIT>".format(author_id, removed_id, thread_id))<EOL>
|
Called when the client is listening, and somebody removes an admin from a group thread
:param mid: The action ID
:param removed_id: The ID of the admin who got removed
:param author_id: The ID of the person who removed the admins
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m139
|
def onApprovalModeChange(<EOL>self,<EOL>mid=None,<EOL>approval_mode=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.GROUP,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
if approval_mode:<EOL><INDENT>log.info("<STR_LIT>".format(author_id, thread_id))<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>".format(author_id, thread_id))<EOL><DEDENT>
|
Called when the client is listening, and somebody changes approval mode in a group thread
:param mid: The action ID
:param approval_mode: True if approval mode is activated
:param author_id: The ID of the person who changed approval mode
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m140
|
def onMessageSeen(<EOL>self,<EOL>seen_by=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>seen_ts=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>seen_by, thread_id, thread_type.name, seen_ts / <NUM_LIT:1000><EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody marks a message as seen
:param seen_by: The ID of the person who marked the message as seen
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param seen_ts: A timestamp of when the person saw the message
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m141
|
def onMessageDelivered(<EOL>self,<EOL>msg_ids=None,<EOL>delivered_for=None,<EOL>thread_id=None,<EOL>thread_type=ThreadType.USER,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>msg_ids, delivered_for, thread_id, thread_type.name, ts / <NUM_LIT:1000><EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody marks messages as delivered
:param msg_ids: The messages that are marked as delivered
:param delivered_for: The person that marked the messages as delivered
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m142
|
def onMarkedSeen(<EOL>self, threads=None, seen_ts=None, ts=None, metadata=None, msg=None<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>[(x[<NUM_LIT:0>], x[<NUM_LIT:1>].name) for x in threads], seen_ts / <NUM_LIT:1000><EOL>)<EOL>)<EOL>
|
Called when the client is listening, and the client has successfully marked threads as seen
:param threads: The threads that were marked
:param author_id: The ID of the person who changed the emoji
:param seen_ts: A timestamp of when the threads were seen
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m143
|
def onMessageUnsent(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, repr(mid), thread_id, thread_type.name, ts / <NUM_LIT:1000><EOL>)<EOL>)<EOL>
|
Called when the client is listening, and someone unsends (deletes for everyone) a message
:param mid: ID of the unsent message
:param author_id: The ID of the person who unsent the message
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m144
|
def onPeopleAdded(<EOL>self,<EOL>mid=None,<EOL>added_ids=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(author_id, "<STR_LIT:U+002CU+0020>".join(added_ids), thread_id)<EOL>)<EOL>
|
Called when the client is listening, and somebody adds people to a group thread
:param mid: The action ID
:param added_ids: The IDs of the people who got added
:param author_id: The ID of the person who added the people
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m145
|
def onPersonRemoved(<EOL>self,<EOL>mid=None,<EOL>removed_id=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info("<STR_LIT>".format(author_id, removed_id, thread_id))<EOL>
|
Called when the client is listening, and somebody removes a person from a group thread
:param mid: The action ID
:param removed_id: The ID of the person who got removed
:param author_id: The ID of the person who removed the person
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m146
|
def onFriendRequest(self, from_id=None, msg=None):
|
log.info("<STR_LIT>".format(from_id))<EOL>
|
Called when the client is listening, and somebody sends a friend request
:param from_id: The ID of the person that sent the request
:param msg: A full set of the data recieved
|
f8726:c0:m147
|
def onInbox(self, unseen=None, unread=None, recent_unread=None, msg=None):
|
log.info("<STR_LIT>".format(unseen, unread, recent_unread))<EOL>
|
.. todo::
Documenting this
:param unseen: --
:param unread: --
:param recent_unread: --
:param msg: A full set of the data recieved
|
f8726:c0:m148
|
def onTyping(<EOL>self, author_id=None, status=None, thread_id=None, thread_type=None, msg=None<EOL>):
|
pass<EOL>
|
Called when the client is listening, and somebody starts or stops typing into a chat
:param author_id: The ID of the person who sent the action
:param status: The typing status
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param msg: A full set of the data recieved
:type typing_status: models.TypingStatus
:type thread_type: models.ThreadType
|
f8726:c0:m149
|
def onGamePlayed(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>game_id=None,<EOL>game_name=None,<EOL>score=None,<EOL>leaderboard=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>'<STR_LIT>'.format(<EOL>author_id, game_name, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody plays a game
:param mid: The action ID
:param author_id: The ID of the person who played the game
:param game_id: The ID of the game
:param game_name: Name of the game
:param score: Score obtained in the game
:param leaderboard: Actual leaderboard of the game in the thread
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m150
|
def onReactionAdded(<EOL>self,<EOL>mid=None,<EOL>reaction=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, mid, reaction.name, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that user reacted to
:param reaction: Reaction
:param add_reaction: Whether user added or removed reaction
:param author_id: The ID of the person who reacted to the message
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type reaction: models.MessageReaction
:type thread_type: models.ThreadType
|
f8726:c0:m151
|
def onReactionRemoved(<EOL>self,<EOL>mid=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, mid, thread_id, thread_type<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody removes reaction from a message
:param mid: Message ID, that user reacted to
:param author_id: The ID of the person who removed reaction
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m152
|
def onBlock(<EOL>self, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(author_id, thread_id, thread_type.name)<EOL>)<EOL>
|
Called when the client is listening, and somebody blocks client
:param author_id: The ID of the person who blocked
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m153
|
def onUnblock(<EOL>self, author_id=None, thread_id=None, thread_type=None, ts=None, msg=None<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(author_id, thread_id, thread_type.name)<EOL>)<EOL>
|
Called when the client is listening, and somebody blocks client
:param author_id: The ID of the person who unblocked
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m154
|
def onLiveLocation(<EOL>self,<EOL>mid=None,<EOL>location=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, thread_id, thread_type, location.latitude, location.longitude<EOL>)<EOL>)<EOL>
|
Called when the client is listening and somebody sends live location info
:param mid: The action ID
:param location: Sent location info
:param author_id: The ID of the person who sent location info
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
:type location: models.LiveLocationAttachment
:type thread_type: models.ThreadType
|
f8726:c0:m155
|
def onCallStarted(<EOL>self,<EOL>mid=None,<EOL>caller_id=None,<EOL>is_video_call=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(caller_id, thread_id, thread_type.name)<EOL>)<EOL>
|
.. todo::
Make this work with private calls
Called when the client is listening, and somebody starts a call in a group
:param mid: The action ID
:param caller_id: The ID of the person who started the call
:param is_video_call: True if it's video call
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m156
|
def onCallEnded(<EOL>self,<EOL>mid=None,<EOL>caller_id=None,<EOL>is_video_call=None,<EOL>call_duration=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(caller_id, thread_id, thread_type.name)<EOL>)<EOL>
|
.. todo::
Make this work with private calls
Called when the client is listening, and somebody ends a call in a group
:param mid: The action ID
:param caller_id: The ID of the person who ended the call
:param is_video_call: True if it was video call
:param call_duration: Call duration in seconds
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m157
|
def onUserJoinedCall(<EOL>self,<EOL>mid=None,<EOL>joined_id=None,<EOL>is_video_call=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(joined_id, thread_id, thread_type.name)<EOL>)<EOL>
|
Called when the client is listening, and somebody joins a group call
:param mid: The action ID
:param joined_id: The ID of the person who joined the call
:param is_video_call: True if it's video call
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type thread_type: models.ThreadType
|
f8726:c0:m158
|
def onPollCreated(<EOL>self,<EOL>mid=None,<EOL>poll=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, poll, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody creates a group poll
:param mid: The action ID
:param poll: Created poll
:param author_id: The ID of the person who created the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
|
f8726:c0:m159
|
def onPollVoted(<EOL>self,<EOL>mid=None,<EOL>poll=None,<EOL>added_options=None,<EOL>removed_options=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, poll, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody votes in a group poll
:param mid: The action ID
:param poll: Poll, that user voted in
:param author_id: The ID of the person who voted in the poll
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type poll: models.Poll
:type thread_type: models.ThreadType
|
f8726:c0:m160
|
def onPlanCreated(<EOL>self,<EOL>mid=None,<EOL>plan=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, plan, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody creates a plan
:param mid: The action ID
:param plan: Created plan
:param author_id: The ID of the person who created the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
|
f8726:c0:m161
|
def onPlanEnded(<EOL>self,<EOL>mid=None,<EOL>plan=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(plan, thread_id, thread_type.name)<EOL>)<EOL>
|
Called when the client is listening, and a plan ends
:param mid: The action ID
:param plan: Ended plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
|
f8726:c0:m162
|
def onPlanEdited(<EOL>self,<EOL>mid=None,<EOL>plan=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, plan, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody edits a plan
:param mid: The action ID
:param plan: Edited plan
:param author_id: The ID of the person who edited the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
|
f8726:c0:m163
|
def onPlanDeleted(<EOL>self,<EOL>mid=None,<EOL>plan=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, plan, thread_id, thread_type.name<EOL>)<EOL>)<EOL>
|
Called when the client is listening, and somebody deletes a plan
:param mid: The action ID
:param plan: Deleted plan
:param author_id: The ID of the person who deleted the plan
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type thread_type: models.ThreadType
|
f8726:c0:m164
|
def onPlanParticipation(<EOL>self,<EOL>mid=None,<EOL>plan=None,<EOL>take_part=None,<EOL>author_id=None,<EOL>thread_id=None,<EOL>thread_type=None,<EOL>ts=None,<EOL>metadata=None,<EOL>msg=None,<EOL>):
|
if take_part:<EOL><INDENT>log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, plan, thread_id, thread_type.name<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>log.info(<EOL>"<STR_LIT>".format(<EOL>author_id, plan, thread_id, thread_type.name<EOL>)<EOL>)<EOL><DEDENT>
|
Called when the client is listening, and somebody takes part in a plan or not
:param mid: The action ID
:param plan: Plan
:param take_part: Whether the person takes part in the plan or not
:param author_id: The ID of the person who will participate in the plan or not
:param thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
:param thread_type: Type of thread that the action was sent to. See :ref:`intro_threads`
:param ts: A timestamp of the action
:param metadata: Extra metadata about the action
:param msg: A full set of the data recieved
:type plan: models.Plan
:type take_part: bool
:type thread_type: models.ThreadType
|
f8726:c0:m165
|
def onQprimer(self, ts=None, msg=None):
|
pass<EOL>
|
Called when the client just started listening
:param ts: A timestamp of the action
:param msg: A full set of the data recieved
|
f8726:c0:m166
|
def onChatTimestamp(self, buddylist=None, msg=None):
|
log.debug("<STR_LIT>".format(buddylist))<EOL>
|
Called when the client receives chat online presence update
:param buddylist: A list of dicts with friend id and last seen timestamp
:param msg: A full set of the data recieved
|
f8726:c0:m167
|
def onBuddylistOverlay(self, statuses=None, msg=None):
|
log.debug("<STR_LIT>".format(statuses))<EOL>
|
Called when the client is listening and client receives information about friend active status
:param statuses: Dictionary with user IDs as keys and :class:`models.ActiveStatus` as values
:param msg: A full set of the data recieved
:type statuses: dict
|
f8726:c0:m168
|
def onUnknownMesssageType(self, msg=None):
|
log.debug("<STR_LIT>".format(msg))<EOL>
|
Called when the client is listening, and some unknown data was recieved
:param msg: A full set of the data recieved
|
f8726:c0:m169
|
def onMessageError(self, exception=None, msg=None):
|
log.exception("<STR_LIT>".format(msg))<EOL>
|
Called when an error was encountered while parsing recieved data
:param exception: The exception that was encountered
:param msg: A full set of the data recieved
|
f8726:c0:m170
|
def graphql_queries_to_json(*queries):
|
rtn = {}<EOL>for i, query in enumerate(queries):<EOL><INDENT>rtn["<STR_LIT>".format(i)] = query.value<EOL><DEDENT>return json.dumps(rtn)<EOL>
|
Queries should be a list of GraphQL objects
|
f8727:m0
|
@bus.on(event=EVENT_NAME)<EOL>def subscription():
|
print("<STR_LIT>")<EOL>
|
Subscribed event to run after event `hello_world`
|
f8737:m0
|
@bus.on(event=EVENT_NAME)<EOL>def event_one():
|
pass<EOL>
|
Mock event.
|
f8738:m0
|
@bus.on(event=EVENT_NAME)<EOL>def on_complete():
|
global GLOBAL_VAR<EOL>GLOBAL_VAR = '<STR_LIT>'<EOL>
|
Subscribed function to EVENT_NAME
|
f8741:m0
|
@bus.emit_after(event=EVENT_NAME)<EOL>def code():
|
print("<STR_LIT>")<EOL>
|
A function that emits an event after completion.
|
f8741:m1
|
@bus.on(event=EVENT_NAME)<EOL>def on_completed():
|
return "<STR_LIT>"<EOL>
|
Subscribed event to run after event `completed`
|
f8742:m0
|
@bus.on(event=EVENT_NAME)<EOL>def on_complete():
|
print("<STR_LIT>")<EOL>
|
Subscribed event to run after event `completed`
|
f8744:m0
|
@bus.on(event=EVENT_NAME)<EOL>def subscription():
|
global GLOBAL_VAR<EOL>GLOBAL_VAR = '<STR_LIT>'<EOL>
|
Subscribed event to run after event `completed`
|
f8745:m0
|
def __init__(self) -> None:
|
self._events = defaultdict(set)<EOL>
|
Creates new EventBus object.
|
f8746:c0:m0
|
def __repr__(self) -> str:
|
return "<STR_LIT>".format(<EOL>self.cls_name,<EOL>self.event_count<EOL>)<EOL>
|
Returns EventBus string representation.
:return: Instance with how many subscribed events.
|
f8746:c0:m1
|
def __str__(self) -> str:
|
return "<STR_LIT:{}>".format(self.cls_name)<EOL>
|
Returns EventBus string representation.
:return: Instance with how many subscribed events.
|
f8746:c0:m2
|
@property<EOL><INDENT>def event_count(self) -> int:<DEDENT>
|
return self._subscribed_event_count()<EOL>
|
Sugar for returning total subscribed events.
:return: Total amount of subscribed events.
:rtype: int
|
f8746:c0:m3
|
@property<EOL><INDENT>def cls_name(self) -> str:<DEDENT>
|
return self.__class__.__name__<EOL>
|
Convenience method to reduce verbosity.
:return: Name of class
:rtype: str
|
f8746:c0:m4
|
def on(self, event: str) -> Callable:
|
def outer(func):<EOL><INDENT>self.add_event(func, event)<EOL>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return outer<EOL>
|
Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
|
f8746:c0:m5
|
def add_event(self, func: Callable, event: str) -> None:
|
self._events[event].add(func)<EOL>
|
Adds a function to a event.
:param func: The function to call when event is emitted
:type func: Callable
:param event: Name of the event.
:type event: str
|
f8746:c0:m6
|
def emit(self, event: str, *args, **kwargs) -> None:
|
threads = kwargs.pop('<STR_LIT>', None)<EOL>if threads:<EOL><INDENT>events = [<EOL>Thread(target=f, args=args, kwargs=kwargs) for f in<EOL>self._event_funcs(event)<EOL>]<EOL>for event in events:<EOL><INDENT>event.start()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for func in self._event_funcs(event):<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT><DEDENT>
|
Emit an event and run the subscribed functions.
:param event: Name of the event.
:type event: str
.. notes:
Passing in threads=True as a kwarg allows to run emitted events
as separate threads. This can significantly speed up code execution
depending on the code being executed.
|
f8746:c0:m7
|
def emit_only(self, event: str, func_names: Union[str, List[str]], *args,<EOL>**kwargs) -> None:
|
if isinstance(func_names, str):<EOL><INDENT>func_names = [func_names]<EOL><DEDENT>for func in self._event_funcs(event):<EOL><INDENT>if func.__name__ in func_names:<EOL><INDENT>func(*args, **kwargs)<EOL><DEDENT><DEDENT>
|
Specifically only emits certain subscribed events.
:param event: Name of the event.
:type event: str
:param func_names: Function(s) to emit.
:type func_names: Union[ str | List[str] ]
|
f8746:c0:m8
|
def emit_after(self, event: str) -> Callable:
|
def outer(func):<EOL><INDENT>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>returned = func(*args, **kwargs)<EOL>self.emit(event)<EOL>return returned<EOL><DEDENT>return wrapper<EOL><DEDENT>return outer<EOL>
|
Decorator that emits events after the function is completed.
:param event: Name of the event.
:type event: str
:return: Callable
.. note:
This plainly just calls functions without passing params into the
subscribed callables. This is great if you want to do some kind
of post processing without the callable requiring information
before doing so.
|
f8746:c0:m9
|
def remove_event(self, func_name: str, event: str) -> None:
|
event_funcs_copy = self._events[event].copy()<EOL>for func in self._event_funcs(event):<EOL><INDENT>if func.__name__ == func_name:<EOL><INDENT>event_funcs_copy.remove(func)<EOL><DEDENT><DEDENT>if self._events[event] == event_funcs_copy:<EOL><INDENT>err_msg = "<STR_LIT>".format(event)<EOL>raise EventDoesntExist(err_msg)<EOL><DEDENT>else:<EOL><INDENT>self._events[event] = event_funcs_copy<EOL><DEDENT>
|
Removes a subscribed function from a specific event.
:param func_name: The name of the function to be removed.
:type func_name: str
:param event: The name of the event.
:type event: str
:raise EventDoesntExist if there func_name doesn't exist in event.
|
f8746:c0:m10
|
def _event_funcs(self, event: str) -> Iterable[Callable]:
|
for func in self._events[event]:<EOL><INDENT>yield func<EOL><DEDENT>
|
Returns an Iterable of the functions subscribed to a event.
:param event: Name of the event.
:type event: str
:return: A iterable to do things with.
:rtype: Iterable
|
f8746:c0:m11
|
def _event_func_names(self, event: str) -> List[str]:
|
return [func.__name__ for func in self._events[event]]<EOL>
|
Returns string name of each function subscribed to an event.
:param event: Name of the event.
:type event: str
:return: Names of functions subscribed to a specific event.
:rtype: list
|
f8746:c0:m12
|
def _subscribed_event_count(self) -> int:
|
event_counter = Counter() <EOL>for key, values in self._events.items():<EOL><INDENT>event_counter[key] = len(values)<EOL><DEDENT>return sum(event_counter.values())<EOL>
|
Returns the total amount of subscribed events.
:return: Integer amount events.
:rtype: int
|
f8746:c0:m13
|
def remove_symbol_from_dist(dist, index):
|
if type(dist) is not Distribution:<EOL><INDENT>raise TypeError("<STR_LIT>".format(type(dist)))<EOL><DEDENT>new_prob = dist.prob.copy()<EOL>new_prob[index]=<NUM_LIT:0><EOL>new_prob /= sum(new_prob)<EOL>return Distribution(new_prob)<EOL>
|
prob is a ndarray representing a probability distribution.
index is a number between 0 and and the number of symbols ( len(prob)-1 )
return the probability distribution if the element at 'index' was no longer available
|
f8752:m0
|
def change_response(x, prob, index):
|
<EOL>N = (x==index).sum()<EOL>x[x==index] = dist.sample(N)<EOL>
|
change every response in x that matches 'index' by randomly sampling from prob
|
f8752:m1
|
def toy_example():
|
<EOL>N=<NUM_LIT:4><EOL>m = <NUM_LIT:100><EOL>x = np.zeros(m*(<NUM_LIT:2>**N))<EOL>y = np.zeros(m*(<NUM_LIT:2>**N))<EOL>for i in range(<NUM_LIT:1>, <NUM_LIT:2>**N):<EOL><INDENT>x[i*m:(i+<NUM_LIT:1>)*m] = i<EOL>y[i*m:(i+<NUM_LIT:1>)*m] = i + np.random.randint(<NUM_LIT:0>, <NUM_LIT:2>*i, m)<EOL><DEDENT>diff = differentiate_mi(x,y)<EOL>return x, y, diff<EOL>
|
Make a toy example where x is uniformly distributed with N bits and y
follows x but with symbol dependent noise.
x=0 -> y=0
x=1 -> y=1 + e
x=2 -> y=2 + 2*e
...
x=n -> y=n + n*e
where by n*e I am saying that the noise grows
|
f8752:m2
|
def differentiate_mi(x, y):
|
<EOL>dist = Distribution(discrete.symbols_to_prob(x))<EOL>diff = np.zeros(len(dist.prob))<EOL>for i in range(len(dist.prob)):<EOL><INDENT>i = int(i)<EOL>dist = Distribution(remove_symbol_from_dist(dist, i).prob)<EOL>new_x = change_response(x, dist, i)<EOL>diff[i] = discrete.mi(x,y)<EOL><DEDENT>return diff<EOL>
|
for each symbol in x, change x such that there are no more of such symbols
(replacing by a random distribution with the same proba of all other symbols)
and compute mi(new_x, y)
|
f8752:m3
|
def sample(self, *args):
|
return self.cumsum.searchsorted(np.random.rand(*args))<EOL>
|
generate a random number in [0,1) and return the index into self.prob
such that self.prob[index] <= random_number but self.prob[index+1] > random_number
implementation note: the problem is identical to finding the index into self.cumsum
where the random number should be inserted to keep the array sorted. This is exactly
what searchsorted does.
usage:
myDist = Distribution(array(0.5, .25, .25))
x = myDist.sample() # generates 1 sample
x = myDist.sample(100) # generates 100 samples
x = myDist.sample(10,10) # generates a 10x10 ndarray
|
f8752:c0:m1
|
def entropy(data=None, prob=None, method='<STR_LIT>', bins=None, errorVal=<NUM_LIT>, units='<STR_LIT>'):
|
if prob is None and data is None:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and data is not None:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and not isinstance(prob, np.ndarray):<EOL><INDENT>raise TypeError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and abs(prob.sum()-<NUM_LIT:1>) > errorVal:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if data is not None:<EOL><INDENT>num_samples = data.shape[<NUM_LIT:0>]<EOL>if len(data.shape) == <NUM_LIT:1>:<EOL><INDENT>num_dimensions = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>num_dimensions = data.shape[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>from sklearn.neighbors import NearestNeighbors<EOL>from scipy.special import gamma<EOL>if data is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(data.shape) > <NUM_LIT:1>:<EOL><INDENT>k = num_dimensions<EOL><DEDENT>else:<EOL><INDENT>k = <NUM_LIT:1><EOL><DEDENT>nbrs = NearestNeighbors(n_neighbors=<NUM_LIT:2>, algorithm='<STR_LIT>').fit(data)<EOL>distances, indices = nbrs.kneighbors(data)<EOL>rho = distances[:,<NUM_LIT:1>] <EOL>Ak = (k*np.pi**(float(k)/float(<NUM_LIT:2>)))/gamma(float(k)/float(<NUM_LIT:2>)+<NUM_LIT:1>)<EOL>if units is '<STR_LIT>':<EOL><INDENT>return k*np.mean(np.log2(rho)) + np.log2(num_samples*Ak/k) + np.log2(np.exp(<NUM_LIT:1>))*np.euler_gamma<EOL><DEDENT>elif units is '<STR_LIT>':<EOL><INDENT>return k*np.mean(np.log(rho)) + np.log(num_samples*Ak/k) + np.log(np.exp(<NUM_LIT:1>))*np.euler_gamma<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(units))<EOL><DEDENT><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>from numpy.linalg import det<EOL>if data is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>detCov = det(np.dot(data.transpose(), data)/num_samples)<EOL>normalization = (<NUM_LIT:2>*np.pi*np.exp(<NUM_LIT:1>))**num_dimensions<EOL>if detCov == <NUM_LIT:0>:<EOL><INDENT>return -np.inf<EOL><DEDENT>else:<EOL><INDENT>if units is '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:0.5>*np.log2(normalization*detCov)<EOL><DEDENT>elif units is '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:0.5>*np.log(normalization*detCov)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(units))<EOL><DEDENT><DEDENT><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>if prob is None and bins is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if data is not None:<EOL><INDENT>prob = symbols_to_prob(data, bins=bins)<EOL><DEDENT>if units is '<STR_LIT>':<EOL><INDENT>logProb = np.log2(prob)<EOL>logProb[logProb == -np.inf] = <NUM_LIT:0><EOL><DEDENT>elif units is '<STR_LIT>':<EOL><INDENT>logProb = np.log(prob)<EOL>logProb[logProb == -np.inf] = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(units))<EOL><DEDENT>return -float(np.sum(prob * logProb))<EOL><DEDENT>
|
given a probability distribution (prob) or an interable of symbols (data) compute and
return its continuous entropy.
inputs:
------
data: samples by dimensions ndarray
prob: iterable with probabilities
method: 'nearest-neighbors', 'gaussian', or 'bin'
bins: either a list of num_bins, or a list of lists containing
the bin edges
errorVal: if prob is given, 'entropy' checks that the sum is about 1.
It raises an error if abs(sum(prob)-1) >= errorVal
units: either 'bits' or 'nats'
Different Methods:
'nearest-neighbors' computes the binless entropy (bits) of a random vector
using average nearest neighbors distance (Kozachenko and Leonenko, 1987).
For a review see Beirlant et al., 2001 or Chandler & Field, 2007.
'gaussian' computes the binless entropy based on estimating the covariance
matrix and assuming the data is normally distributed.
'bin' discretizes the data and computes the discrete entropy.
|
f8753:m0
|
def symbols_to_prob(data, bins=None, tol=<NUM_LIT>):
|
dimensionality = data.shape[<NUM_LIT:1>]<EOL>if isinstance(bins, int):<EOL><INDENT>bins = dimensionality * [bins]<EOL><DEDENT>if len(bins) != dimensionality:<EOL><INDENT>raise ValueError("<STR_LIT>"%(dimensionality, len(bins)))<EOL><DEDENT>prob = np.histogramdd(data, bins, normed=True)<EOL>if abs(sum(prob) - <NUM_LIT:1>) > tol:<EOL><INDENT>raise ValueError("<STR_LIT>"%(sum(prob)))<EOL><DEDENT>return prob<EOL>
|
Return the probability distribution of symbols. Only probabilities are returned and in random order,
you don't know what the probability of a given label is but this can be used to compute entropy
input:
data: ndarray of shape (samples, dimensions)
bins: either int, list of num_bins, or list of list of bin edges
tol: tolerance for determining if probabilities sum to 1
returns:
prob: returns list of 1-d np arrays each containing probability of discretized symbols
|
f8753:m1
|
def mi(x, y, bins_x=None, bins_y=None, bins_xy=None, method='<STR_LIT>', units='<STR_LIT>'):
|
<EOL>try:<EOL><INDENT>if isinstance(x, zip):<EOL><INDENT>x = list(x)<EOL><DEDENT>if isinstance(y, zip):<EOL><INDENT>y = list(y)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if len(x.shape) == <NUM_LIT:1>:<EOL><INDENT>x = np.expand_dims(x, <NUM_LIT:1>)<EOL><DEDENT>if len(y.shape) == <NUM_LIT:1>:<EOL><INDENT>y = np.expand_dims(y, <NUM_LIT:1>)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>HX = entropy(data=x, bins=bins_x, method=method, units=units)<EOL>HY = entropy(data=y, bins=bins_y, method=method, units=units)<EOL>HXY = entropy(data=np.concatenate([x, y], axis=<NUM_LIT:1>), bins=bins_xy, method=method, units=units)<EOL>return HX + HY - HXY<EOL>
|
compute and return the mutual information between x and y
inputs:
-------
x, y: numpy arrays of shape samples x dimension
method: 'nearest-neighbors', 'gaussian', or 'bin'
units: 'bits' or 'nats'
output:
-------
mi: float
Notes:
------
if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try
info[p] = _info.mi(x, info.combine_symbols(y0, y1, ...) )
|
f8753:m2
|
def cond_entropy(x, y, bins_y=None, bins_xy=None, method='<STR_LIT>', units='<STR_LIT>'):
|
HXY = entropy(data=np.concatenate([x, y], axis=<NUM_LIT:1>), bins=bins_xy, method=method, units=units)<EOL>HY = entropy(data=y, bins=bins_y, method=method, units=units)<EOL>return HXY - HY<EOL>
|
compute the conditional entropy H(X|Y).
method: 'nearest-neighbors', 'gaussian', or 'bin'
if 'bin' need to provide bins_y, and bins_xy
units: 'bits' or 'nats'
|
f8753:m3
|
def entropy(data=None, prob=None, tol=<NUM_LIT>):
|
if prob is None and data is None:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and data is not None:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and not isinstance(prob, np.ndarray):<EOL><INDENT>raise TypeError("<STR_LIT>" % __name__)<EOL><DEDENT>if prob is not None and abs(prob.sum()-<NUM_LIT:1>) > tol:<EOL><INDENT>raise ValueError("<STR_LIT>" % __name__)<EOL><DEDENT>if data is not None:<EOL><INDENT>prob = symbols_to_prob(data).prob()<EOL><DEDENT>logProb = np.log2(prob)<EOL>logProb[logProb == -np.inf] = <NUM_LIT:0><EOL>return -float(np.dot(prob, logProb))<EOL>
|
given a probability distribution (prob) or an interable of symbols (data) compute and
return its entropy
inputs:
------
data: iterable of symbols
prob: iterable with probabilities
tol: if prob is given, 'entropy' checks that the sum is about 1.
It raises an error if abs(sum(prob)-1) >= tol
|
f8755:m0
|
def symbols_to_prob(symbols):
|
myCounter = Counter(symbols)<EOL>N = float(len(list(symbols))) <EOL>for k in myCounter:<EOL><INDENT>myCounter[k] /= N<EOL><DEDENT>return myCounter<EOL>
|
Return a dict mapping symbols to probability.
input:
-----
symbols: iterable of hashable items
works well if symbols is a zip of iterables
|
f8755:m1
|
def combine_symbols(*args):
|
for arg in args:<EOL><INDENT>if len(arg)!=len(args[<NUM_LIT:0>]):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return tuple(zip(*args))<EOL>
|
Combine different symbols into a 'super'-symbol
args can be an iterable of iterables that support hashing
see example for 2D ndarray input
usage:
1) combine two symbols, each a number into just one symbol
x = numpy.random.randint(0,4,1000)
y = numpy.random.randint(0,2,1000)
z = combine_symbols(x,y)
2) combine a letter and a number
s = 'abcd'
x = numpy.random.randint(0,4,1000)
y = [s[randint(4)] for i in range(1000)]
z = combine_symbols(x,y)
3) suppose you are running an experiment and for each sample, you measure 3 different
properties and you put the data into a 2d ndarray such that:
samples_N, properties_N = data.shape
and you want to combine all 3 different properties into just 1 symbol
In this case you have to find a way to impute each property as an independent array
combined_symbol = combine_symbols(*data.T)
4) if data from 3) is such that:
properties_N, samples_N = data.shape
then run:
combined_symbol = combine_symbols(*data)
|
f8755:m2
|
def mi(x, y):
|
<EOL>try:<EOL><INDENT>if isinstance(x, zip):<EOL><INDENT>x = list(x)<EOL><DEDENT>if isinstance(y, zip):<EOL><INDENT>y = list(y)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>probX = symbols_to_prob(x).prob()<EOL>probY = symbols_to_prob(y).prob()<EOL>probXY = symbols_to_prob(combine_symbols(x, y)).prob()<EOL>return entropy(prob=probX) + entropy(prob=probY) - entropy(prob=probXY)<EOL>
|
compute and return the mutual information between x and y
inputs:
-------
x, y: iterables of hashable items
output:
-------
mi: float
Notes:
------
if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try
info[p] = _info.mi(x, info.combine_symbols(y0, y1, ...) )
|
f8755:m3
|
def cond_mi(x, y, z):
|
<EOL>probXZ = symbols_to_prob(combine_symbols(x, z)).prob()<EOL>probYZ = symbols_to_prob(combine_symbols(y, z)).prob()<EOL>probXYZ =symbols_to_prob(combine_symbols(x, y, z)).prob()<EOL>probZ = symbols_to_prob(z).prob()<EOL>return entropy(prob=probXZ) + entropy(prob=probYZ) - entropy(prob=probXYZ) - entropy(prob=probZ)<EOL>
|
compute and return the mutual information between x and y given z, I(x, y | z)
inputs:
-------
x, y, z: iterables with discrete symbols
output:
-------
mi: float
implementation notes:
---------------------
I(x, y | z) = H(x | z) - H(x | y, z)
= H(x, z) - H(z) - ( H(x, y, z) - H(y,z) )
= H(x, z) + H(y, z) - H(z) - H(x, y, z)
|
f8755:m4
|
def mi_chain_rule(X, y):
|
<EOL>chain = np.zeros(len(X))<EOL>chain[<NUM_LIT:0>] = mi(X[<NUM_LIT:0>], y)<EOL>for i in range(<NUM_LIT:1>, len(X)):<EOL><INDENT>chain[i] = cond_mi(X[i], y, X[:i])<EOL><DEDENT>return chain<EOL>
|
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
output:
-------
ndarray: terms of chaing rule
Implemenation notes:
I(X; y) = I(x0, x1, ..., xn; y)
= I(x0; y) + I(x1;y | x0) + I(x2; y | x0, x1) + ... + I(xn; y | x0, x1, ..., xn-1)
|
f8755:m5
|
def KL_divergence(P,Q):
|
assert(P.keys()==Q.keys())<EOL>distance = <NUM_LIT:0><EOL>for k in P.keys():<EOL><INDENT>distance += P[k] * log(P[k]/Q[k])<EOL><DEDENT>return distance<EOL>
|
Compute the KL divergence between distributions P and Q
P and Q should be dictionaries linking symbols to probabilities.
the keys to P and Q should be the same.
|
f8755:m6
|
def bin(x, bins, maxX=None, minX=None):
|
if maxX is None:<EOL><INDENT>maxX = x.max()<EOL><DEDENT>if minX is None:<EOL><INDENT>minX = x.min()<EOL><DEDENT>if not np.iterable(bins):<EOL><INDENT>bins = np.linspace(minX, maxX+<NUM_LIT>, bins+<NUM_LIT:1>)<EOL><DEDENT>return np.digitize(x.ravel(), bins).reshape(x.shape), bins<EOL>
|
bin signal x using 'binsN' bin. If minX, maxX are None, they default to the full
range of the signal. If they are not None, everything above maxX gets assigned to
binsN-1 and everything below minX gets assigned to 0, this is effectively the same
as clipping x before passing it to 'bin'
input:
-----
x: signal to be binned, some sort of iterable
bins: int, number of bins
iterable, bin edges
maxX: clips data above maxX
minX: clips data below maxX
output:
------
binnedX: x after being binned
bins: bins used for binning.
if input 'bins' is already an iterable it just returns the
same iterable
example:
# make 10 bins of equal length spanning from x.min() to x.max()
bin(x, 10)
# use predefined bins such that each bin has the same number of points (maximize
entropy)
binsN = 10
percentiles = list(np.arange(0, 100.1, 100/binsN))
bins = np.percentile(x, percentiles)
bin(x, bins)
|
f8755:m7
|
def _doc_object(obj, obj_type, nest=None, config=default_config):
|
doc = inspect.getdoc(obj)<EOL>if not doc and not nest:<EOL><INDENT>return None<EOL><DEDENT>result = {<EOL>'<STR_LIT:type>': obj_type,<EOL>'<STR_LIT:name>': obj.__name__,<EOL>'<STR_LIT>': doc<EOL>}<EOL>if nest:<EOL><INDENT>result['<STR_LIT>'] = nest<EOL><DEDENT>return result<EOL>
|
Return a dict with type, name, doc and nested doc (if any).
|
f8758:m0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.