INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Setup logging
def setup_logging(args, conf): """Setup logging""" logging_format = "%(asctime)s [%(levelname)s]: %(name)s (%(module)s.%(funcName)s; " \ "%(filename)s:%(lineno)d)\n %(message)s" if getattr(args, "verbose", None): debug_logger = logging.StreamHandler(sys.stdout) debug...
Setup telemetry
def setup_telemetry(key: str): """ Setup telemetry EH Forwarder Bot Framework includes NO code that uploads your log or any other data to anywhere. To enable telemetry functionality, additional modules need to be installed manually. See :doc:`telemetry` for details. """ if not isinsta...
Connects to the db using pymapd https:// pymapd. readthedocs. io/ en/ latest/ usage. html#connecting
def get_connection(**kwargs): """ Connects to the db using pymapd https://pymapd.readthedocs.io/en/latest/usage.html#connecting Kwargs: db_user(str): DB username db_passwd(str): DB password db_server(str): DB host db_port(int): DB port db_name(str): DB name...
Executes a query against the connected db using pymapd https:// pymapd. readthedocs. io/ en/ latest/ usage. html#querying
def execute_query(**kwargs): """ Executes a query against the connected db using pymapd https://pymapd.readthedocs.io/en/latest/usage.html#querying Kwargs: query_name(str): Name of query query_mapdql(str): Query to run iteration(int): Iteration number Returns: ...
Calculates aggregate query times from all iteration times
def calculate_query_times(**kwargs): """ Calculates aggregate query times from all iteration times Kwargs: total_times(list): List of total time calculations execution_times(list): List of execution_time calculations results_iter_times(list): List of results_iter_time calculatio...
Calculates memory statistics from mapd_server _client. get_memory call
def get_mem_usage(**kwargs): """ Calculates memory statistics from mapd_server _client.get_memory call Kwargs: con(class 'pymapd.connection.Connection'): Mapd connection mem_type(str): [gpu, cpu] Type of memory to gather metrics for Returns: ramusage(dict)::: us...
Adjusts the directory until a compilation database is found.
def find_compilation_database(path): """Adjusts the directory until a compilation database is found.""" result = './' while not os.path.isfile(os.path.join(result, path)): if os.path.realpath(result) == '/': print('Error: could not find compilation database.') sys.exit(1) result += '../' ret...
Gets a command line for clang - tidy.
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet, config): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] if header_filter is not None: start.append('-header-filter...
Merge all replacement files in a directory into a single file
def merge_replacement_files(tmpdir, mergefile): """Merge all replacement files in a directory into a single file""" # The fixes suggested by clang-tidy >= 4.0.0 are given under # the top level key 'Diagnostics' in the output yaml files mergekey="Diagnostics" merged=[] for replacefile in glob.iglob(os.path.j...
Checks if invoking supplied clang - apply - replacements binary works.
def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, '--version']) except: print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary c...
Calls clang - apply - fixes on a given directory.
def apply_fixes(args, tmpdir): """Calls clang-apply-fixes on a given directory.""" invocation = [args.clang_apply_replacements_binary] if args.format: invocation.append('-format') if args.style: invocation.append('-style=' + args.style) invocation.append(tmpdir) subprocess.call(invocation)
Takes filenames out of queue and runs clang - tidy on them.
def run_tidy(args, tmpdir, build_path, queue, lock, failed_files): """Takes filenames out of queue and runs clang-tidy on them.""" while True: name = queue.get() invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks, tmpdir, build_path, args.header_f...
Rewrite Thrift - generated Python clients to handle recursive structs. For more details see: https:// issues. apache. org/ jira/ browse/ THRIFT - 2642.
def main(): """Rewrite Thrift-generated Python clients to handle recursive structs. For more details see: https://issues.apache.org/jira/browse/THRIFT-2642. Requires package `RedBaron`, available via pip: $ pip install redbaron To use: $ thrift -gen py mapd.thrift $ mv gen-py/mapd/ttypes....
A decorator to store and link a callback to an event.
def run_on(*, event: str): """A decorator to store and link a callback to an event.""" def decorator(callback): @functools.wraps(callback) def decorator_wrapper(): RTMClient.on(event=event, callback=callback) return decorator_wrapper() retur...
Stores and links the callback ( s ) to the event.
def on(cls, *, event: str, callback: Callable): """Stores and links the callback(s) to the event. Args: event (str): A string that specifies a Slack or websocket event. e.g. 'channel_joined' or 'open' callback (Callable): Any object or a list of objects that can ...
Starts an RTM Session with Slack.
def start(self) -> asyncio.Future: """Starts an RTM Session with Slack. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL and then connects to the message server. As events stream-in we run any associated callbacks stored on the client. If 'auto...
Closes the websocket connection and ensures it won t reconnect.
def stop(self): """Closes the websocket connection and ensures it won't reconnect.""" self._logger.debug("The Slack RTMClient is shutting down.") self._stopped = True self._close_websocket()
Sends a message to Slack over the WebSocket connection.
def send_over_websocket(self, *, payload: dict): """Sends a message to Slack over the WebSocket connection. Note: The RTM API only supports posting simple messages formatted using our default message formatting mode. It does not support attachments or other message f...
Sends a typing indicator to the specified channel.
def typing(self, *, channel: str): """Sends a typing indicator to the specified channel. This indicates that this app is currently writing a message to send to a channel. Args: channel (str): The channel id. e.g. 'C024BE91L' Raises: SlackClientNotConnec...
Checks if the specified callback is callable and accepts a kwargs param.
def _validate_callback(callback): """Checks if the specified callback is callable and accepts a kwargs param. Args: callback (obj): Any object or a list of objects that can be called. e.g. <function say_hello at 0x101234567> Raises: SlackClientError: The...
Retreives and connects to Slack s RTM API.
async def _connect_and_read(self): """Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' is specified we ...
Process messages received on the WebSocket connection.
async def _read_messages(self): """Process messages received on the WebSocket connection. Iteration terminates when the client is stopped or it disconnects. """ while not self._stopped and self._websocket is not None: async for message in self._websocket: if ...
Dispatches the event and executes any associated callbacks.
def _dispatch_event(self, event, data=None): """Dispatches the event and executes any associated callbacks. Note: To prevent the app from crashing due to callback errors. We catch all exceptions and send all data to the logger. Args: event (str): The type of event. e.g. 'bo...
Execute the callback asynchronously.
def _execute_callback_async(self, callback, data): """Execute the callback asynchronously. If the callback is not a coroutine, convert it. Note: The WebClient passed into the callback is running in "async" mode. This means all responses will be futures. """ if asyncio.i...
Execute the callback in another thread. Wait for and return the results.
def _execute_callback(self, callback, data): """Execute the callback in another thread. Wait for and return the results.""" web_client = WebClient( token=self.token, base_url=self.base_url, ssl=self.ssl, proxy=self.proxy ) with concurrent.futures.ThreadPoolExecutor(max_worker...
Retreives the WebSocket info from Slack.
async def _retreive_websocket_info(self): """Retreives the WebSocket info from Slack. Returns: A tuple of websocket information. e.g. ( "wss://...", { "self": {"id": "U01234ABC","name": "robotoverlord"}, ...
Wait exponentially longer for each connection attempt.
async def _wait_exponentially(self, exception, max_wait_time=300): """Wait exponentially longer for each connection attempt. Calculate the number of seconds to wait and then add a random number of milliseconds to avoid coincendental synchronized client retries. Wait up to the maximium a...
Closes the websocket connection.
def _close_websocket(self): """Closes the websocket connection.""" close_method = getattr(self._websocket, "close", None) if callable(close_method): asyncio.ensure_future(close_method(), loop=self._event_loop) self._websocket = None self._dispatch_event(event="close")
Update the onboarding welcome message after recieving a reaction_added event from Slack. Update timestamp for welcome message as well.
async def update_emoji(**payload): """Update the onboarding welcome message after recieving a "reaction_added" event from Slack. Update timestamp for welcome message as well. """ data = payload["data"] web_client = payload["web_client"] channel_id = data["item"]["channel"] user_id = data["us...
Update the onboarding welcome message after recieving a pin_added event from Slack. Update timestamp for welcome message as well.
async def update_pin(**payload): """Update the onboarding welcome message after recieving a "pin_added" event from Slack. Update timestamp for welcome message as well. """ data = payload["data"] web_client = payload["web_client"] channel_id = data["channel_id"] user_id = data["user"] # ...
Display the onboarding welcome message after receiving a message that contains start.
async def message(**payload): """Display the onboarding welcome message after receiving a message that contains "start". """ data = payload["data"] web_client = payload["web_client"] channel_id = data.get("channel") user_id = data.get("user") text = data.get("text") if text and text...
Renames a channel.
def channels_rename(self, *, channel: str, name: str, **kwargs) -> SlackResponse: """Renames a channel. Args: channel (str): The channel id. e.g. 'C1234567890' name (str): The new channel name. e.g. 'newchannel' """ self._validate_xoxp_token() kwargs.upda...
Retrieve a thread of messages posted to a channel
def channels_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse: """Retrieve a thread of messages posted to a channel Args: channel (str): The channel id. e.g. 'C1234567890' thread_ts (str): The timestamp of an existing message with 0 or more replies. ...
Unarchives a channel.
def channels_unarchive(self, *, channel: str, **kwargs) -> SlackResponse: """Unarchives a channel. Args: channel (str): The channel id. e.g. 'C1234567890' """ self._validate_xoxp_token() kwargs.update({"channel": channel}) return self.api_call("channels.unarc...
Deletes a message.
def chat_delete(self, *, channel: str, ts: str, **kwargs) -> SlackResponse: """Deletes a message. Args: channel (str): Channel containing the message to be deleted. e.g. 'C1234567890' ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456' """ ...
Retrieve a permalink URL for a specific extant message
def chat_getPermalink( self, *, channel: str, message_ts: str, **kwargs ) -> SlackResponse: """Retrieve a permalink URL for a specific extant message Args: channel (str): The channel id. e.g. 'C1234567890' message_ts (str): The timestamp. e.g. '1234567890.123456' ...
Share a me message into a channel.
def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse: """Share a me message into a channel. Args: channel (str): The channel id. e.g. 'C1234567890' text (str): The message you'd like to share. e.g. 'Hello world' """ kwargs.update({"chan...
Sends an ephemeral message to a user in a channel.
def chat_postEphemeral(self, *, channel: str, user: str, **kwargs) -> SlackResponse: """Sends an ephemeral message to a user in a channel. Args: channel (str): The channel id. e.g. 'C1234567890' user (str): The id of user who should see the message. e.g. 'U0BPQUNTA' ...
Provide custom unfurl behavior for user - posted URLs.
def chat_unfurl( self, *, channel: str, ts: str, unfurls: dict, **kwargs ) -> SlackResponse: """Provide custom unfurl behavior for user-posted URLs. Args: channel (str): The Channel ID of the message. e.g. 'C1234567890' ts (str): Timestamp of the message to add unfur...
Invites users to a channel.
def conversations_invite( self, *, channel: str, users: List[str], **kwargs ) -> SlackResponse: """Invites users to a channel. Args: channel (str): The channel id. e.g. 'C1234567890' users (list): An list of user id's to invite. e.g. ['U2345678901', 'U3456789012'] ...
Retrieve a thread of messages posted to a conversation
def conversations_replies(self, *, channel: str, ts: str, **kwargs) -> SlackResponse: """Retrieve a thread of messages posted to a conversation Args: channel (str): Conversation ID to fetch thread from. e.g. 'C1234567890' ts (str): Unique identifier of a thread's parent message....
Sets the topic for a conversation.
def conversations_setTopic( self, *, channel: str, topic: str, **kwargs ) -> SlackResponse: """Sets the topic for a conversation. Args: channel (str): The channel id. e.g. 'C1234567890' topic (str): The new topic for the channel. e.g. 'My Topic' """ k...
Open a dialog with a user.
def dialog_open(self, *, dialog: dict, trigger_id: str, **kwargs) -> SlackResponse: """Open a dialog with a user. Args: dialog (dict): A dictionary of dialog arguments. { "callback_id": "46eh782b0", "title": "Request something", ...
Ends the current user s Do Not Disturb session immediately.
def dnd_endDnd(self, **kwargs) -> SlackResponse: """Ends the current user's Do Not Disturb session immediately.""" self._validate_xoxp_token() return self.api_call("dnd.endDnd", json=kwargs)
Ends the current user s snooze mode immediately.
def dnd_endSnooze(self, **kwargs) -> SlackResponse: """Ends the current user's snooze mode immediately.""" self._validate_xoxp_token() return self.api_call("dnd.endSnooze", json=kwargs)
Turns on Do Not Disturb mode for the current user or changes its duration.
def dnd_setSnooze(self, *, num_minutes: int, **kwargs) -> SlackResponse: """Turns on Do Not Disturb mode for the current user, or changes its duration. Args: num_minutes (int): The snooze duration. e.g. 60 """ self._validate_xoxp_token() kwargs.update({"num_minutes":...
Add a comment to an existing file.
def files_comments_add(self, *, comment: str, file: str, **kwargs) -> SlackResponse: """Add a comment to an existing file. Args: comment (str): The body of the comment. e.g. 'Everyone should take a moment to read this file.' file (str): The file id. e.g. 'F123446...
Deletes an existing comment on a file.
def files_comments_delete(self, *, file: str, id: str, **kwargs) -> SlackResponse: """Deletes an existing comment on a file. Args: file (str): The file id. e.g. 'F1234467890' id (str): The file comment id. e.g. 'Fc1234567890' """ kwargs.update({"file": file, "id"...
Edit an existing file comment.
def files_comments_edit( self, *, comment: str, file: str, id: str, **kwargs ) -> SlackResponse: """Edit an existing file comment. Args: comment (str): The body of the comment. e.g. 'Everyone should take a moment to read this file.' file (str): The fi...
Deletes a file.
def files_delete(self, *, id: str, **kwargs) -> SlackResponse: """Deletes a file. Args: id (str): The file id. e.g. 'F1234467890' """ kwargs.update({"id": id}) return self.api_call("files.delete", json=kwargs)
Gets information about a team file.
def files_info(self, *, id: str, **kwargs) -> SlackResponse: """Gets information about a team file. Args: id (str): The file id. e.g. 'F1234467890' """ kwargs.update({"id": id}) return self.api_call("files.info", http_verb="GET", params=kwargs)
Lists & filters team files.
def files_list(self, **kwargs) -> SlackResponse: """Lists & filters team files.""" self._validate_xoxp_token() return self.api_call("files.list", http_verb="GET", params=kwargs)
Enables a file for public/ external sharing.
def files_sharedPublicURL(self, *, id: str, **kwargs) -> SlackResponse: """Enables a file for public/external sharing. Args: id (str): The file id. e.g. 'F1234467890' """ self._validate_xoxp_token() kwargs.update({"id": id}) return self.api_call("files.shared...
Uploads or creates a file.
def files_upload( self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs ) -> SlackResponse: """Uploads or creates a file. Args: file (str): Supply a file path. when you'd like to upload a specific file. e.g. 'dramacat.gif' content (s...
Clones and archives a private channel.
def groups_createChild(self, *, channel: str, **kwargs) -> SlackResponse: """Clones and archives a private channel. Args: channel (str): The group id. e.g. 'G1234567890' """ self._validate_xoxp_token() kwargs.update({"channel": channel}) return self.api_call(...
Invites a user to a private channel.
def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse: """Invites a user to a private channel. Args: channel (str): The group id. e.g. 'G1234567890' user (str): The user id. e.g. 'U1234567890' """ self._validate_xoxp_token() kwarg...
Retrieve a thread of messages posted to a private channel
def groups_replies(self, *, channel: str, thread_ts: str, **kwargs) -> SlackResponse: """Retrieve a thread of messages posted to a private channel Args: channel (str): The channel id. e.g. 'C1234567890' thread_ts (str): The timestamp of an existing message with 0 or more replies...
Sets the purpose for a private channel.
def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse: """Sets the purpose for a private channel. Args: channel (str): The channel id. e.g. 'G1234567890' purpose (str): The new purpose for the channel. e.g. 'My Purpose' """ kwargs....
Opens a direct message channel.
def im_open(self, *, user: str, **kwargs) -> SlackResponse: """Opens a direct message channel. Args: user (str): The user id to open a DM with. e.g. 'W1234567890' """ kwargs.update({"user": user}) return self.api_call("im.open", json=kwargs)
For Enterprise Grid workspaces map local user IDs to global user IDs
def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse: """For Enterprise Grid workspaces, map local user IDs to global user IDs Args: users (list): A list of user ids, up to 400 per request. e.g. ['W1234567890', 'U2345678901', 'U3456789012'] ""...
Closes a multiparty direct message channel.
def mpim_close(self, *, channel: str, **kwargs) -> SlackResponse: """Closes a multiparty direct message channel. Args: channel (str): Multiparty Direct message channel to close. e.g. 'G1234567890' """ kwargs.update({"channel": channel}) return self.api_call("mpim.clo...
Fetches history of messages and events from a multiparty direct message.
def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse: """Fetches history of messages and events from a multiparty direct message. Args: channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890' """ kwargs.update({"channel": channel}) ...
This method opens a multiparty direct message.
def mpim_open(self, *, users: List[str], **kwargs) -> SlackResponse: """This method opens a multiparty direct message. Args: users (list): A lists of user ids. The ordering of the users is preserved whenever a MPIM group is returned. e.g. ['W1234567890', 'U23...
Exchanges a temporary OAuth verifier code for an access token.
def oauth_access( self, *, client_id: str, client_secret: str, code: str, **kwargs ) -> SlackResponse: """Exchanges a temporary OAuth verifier code for an access token. Args: client_id (str): Issued when you created your application. e.g. '4b39e9-752c4' client_secret...
Adds a reaction to an item.
def reactions_add(self, *, name: str, **kwargs) -> SlackResponse: """Adds a reaction to an item. Args: name (str): Reaction (emoji) name. e.g. 'thumbsup' channel (str): Channel where the message to add reaction to was posted. e.g. 'C1234567890' timest...
Creates a reminder.
def reminders_add(self, *, text: str, time: str, **kwargs) -> SlackResponse: """Creates a reminder. Args: text (str): The content of the reminder. e.g. 'eat a banana' time (str): When this reminder should happen: the Unix timestamp (up to five years from now e.g....
Marks a reminder as complete.
def reminders_complete(self, *, reminder: str, **kwargs) -> SlackResponse: """Marks a reminder as complete. Args: reminder (str): The ID of the reminder to be marked as complete. e.g. 'Rm12345678' """ self._validate_xoxp_token() kwargs.update({"remind...
Gets information about a reminder.
def reminders_info(self, *, reminder: str, **kwargs) -> SlackResponse: """Gets information about a reminder. Args: reminder (str): The ID of the reminder. e.g. 'Rm12345678' """ self._validate_xoxp_token() kwargs.update({"reminder": reminder}) return self.api_...
Lists all reminders created by or for a given user.
def reminders_list(self, **kwargs) -> SlackResponse: """Lists all reminders created by or for a given user.""" self._validate_xoxp_token() return self.api_call("reminders.list", http_verb="GET", params=kwargs)
Searches for messages matching a query.
def search_messages(self, *, query: str, **kwargs) -> SlackResponse: """Searches for messages matching a query. Args: query (str): Search query. May contains booleans, etc. e.g. 'pickleface' """ self._validate_xoxp_token() kwargs.update({"query": quer...
Lists stars for a user.
def stars_list(self, **kwargs) -> SlackResponse: """Lists stars for a user.""" self._validate_xoxp_token() return self.api_call("stars.list", http_verb="GET", params=kwargs)
Gets the access logs for the current team.
def team_accessLogs(self, **kwargs) -> SlackResponse: """Gets the access logs for the current team.""" self._validate_xoxp_token() return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
Gets billable users information for the current team.
def team_billableInfo(self, **kwargs) -> SlackResponse: """Gets billable users information for the current team.""" self._validate_xoxp_token() return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
Gets the integration logs for the current team.
def team_integrationLogs(self, **kwargs) -> SlackResponse: """Gets the integration logs for the current team.""" self._validate_xoxp_token() return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
Retrieve a team s profile.
def team_profile_get(self, **kwargs) -> SlackResponse: """Retrieve a team's profile.""" self._validate_xoxp_token() return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
Create a User Group
def usergroups_create(self, *, name: str, **kwargs) -> SlackResponse: """Create a User Group Args: name (str): A name for the User Group. Must be unique among User Groups. e.g. 'My Test Team' """ self._validate_xoxp_token() kwargs.update({"name": name...
Disable an existing User Group
def usergroups_disable(self, *, usergroup: str, **kwargs) -> SlackResponse: """Disable an existing User Group Args: usergroup (str): The encoded ID of the User Group to disable. e.g. 'S0604QSJC' """ self._validate_xoxp_token() kwargs.update({"usergrou...
List all User Groups for a team
def usergroups_list(self, **kwargs) -> SlackResponse: """List all User Groups for a team""" self._validate_xoxp_token() return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
List all users in a User Group
def usergroups_users_list(self, *, usergroup: str, **kwargs) -> SlackResponse: """List all users in a User Group Args: usergroup (str): The encoded ID of the User Group to update. e.g. 'S0604QSJC' """ self._validate_xoxp_token() kwargs.update({"usergr...
Update the list of users for a User Group
def usergroups_users_update( self, *, usergroup: str, users: List[str], **kwargs ) -> SlackResponse: """Update the list of users for a User Group Args: usergroup (str): The encoded ID of the User Group to update. e.g. 'S0604QSJC' users (list): A list ...
Delete the user profile photo
def users_deletePhoto(self, **kwargs) -> SlackResponse: """Delete the user profile photo""" self._validate_xoxp_token() return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
Gets user presence information.
def users_getPresence(self, *, user: str, **kwargs) -> SlackResponse: """Gets user presence information. Args: user (str): User to get presence info on. Defaults to the authed user. e.g. 'W1234567890' """ kwargs.update({"user": user}) return self.api_...
Get a user s identity.
def users_identity(self, **kwargs) -> SlackResponse: """Get a user's identity.""" self._validate_xoxp_token() return self.api_call("users.identity", http_verb="GET", params=kwargs)
Find a user with an email address.
def users_lookupByEmail(self, *, email: str, **kwargs) -> SlackResponse: """Find a user with an email address. Args: email (str): An email address belonging to a user in the workspace. e.g. 'spengler@ghostbusters.example.com' """ kwargs.update({"email": email...
Set the user profile photo
def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse: """Set the user profile photo Args: image (str): Supply the path of the image you'd like to upload. e.g. 'myimage.png' """ self._validate_xoxp_token() return self.api_c...
Manually sets user presence.
def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse: """Manually sets user presence. Args: presence (str): Either 'auto' or 'away'. """ kwargs.update({"presence": presence}) return self.api_call("users.setPresence", json=kwargs)
Retrieves a user s profile information.
def users_profile_get(self, **kwargs) -> SlackResponse: """Retrieves a user's profile information.""" self._validate_xoxp_token() return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
Set the profile information for a user.
def users_profile_set(self, **kwargs) -> SlackResponse: """Set the profile information for a user.""" self._validate_xoxp_token() return self.api_call("users.profile.set", json=kwargs)
Create a request and execute the API call to Slack.
def api_call( self, api_method: str, *, http_verb: str = "POST", files: dict = None, data: dict = None, params: dict = None, json: dict = None, ): """Create a request and execute the API call to Slack. Args: api_method (str...
Ensures that an xoxp token is used when the specified method is called.
def _validate_xoxp_token(self): """Ensures that an xoxp token is used when the specified method is called. Raises: BotUserAccessError: If the API method is called with a Bot User OAuth Access Token. """ if self.token.startswith("xoxb"): method_name = inspect.sta...
Sends the request out for transmission.
async def _send(self, http_verb, api_url, req_args): """Sends the request out for transmission. Args: http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'. api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage' req_args (dict): The request ar...
Submit the HTTP request with the running session or a new session. Returns: A dictionary of the response data.
async def _request(self, *, http_verb, api_url, req_args): """Submit the HTTP request with the running session or a new session. Returns: A dictionary of the response data. """ if self.session and not self.session.closed: async with self.session.request(http_verb,...
Construct the user - agent header with the package info Python version and OS version.
def _get_user_agent(): """Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0' """ # __name__ returns all classes, we only want the client ...
Check if the response from Slack was successful.
def validate(self): """Check if the response from Slack was successful. Returns: (SlackResponse) This method returns it's own object. e.g. 'self' Raises: SlackApiError: The request to the Slack API failed. """ if self.status_code == 200 a...
Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future.
def onboarding_message(**payload): """Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future. """ # Get WebClient so you can communicate back to Slack. web_client = payload["web_client"] # Get the id of the Sla...
Log the time it takes to run a function. It s sort of like timeit but prettier.
def log_time(func: Callable[..., Any]) -> Callable[..., Any]: """Log the time it takes to run a function. It's sort of like timeit, but prettier. """ def wrapper(*args, **kwargs): start_time = time.time() log.info("%s starting...", func.__name__.title()) ret = func(*args, **kwar...
We double - fork here to detach the daemon process from the parent. If we were to just fork the child as a daemon we d have to worry about the parent process exiting zombifying the daemon.
def daemonize(self) -> None: """We double-fork here to detach the daemon process from the parent. If we were to just fork the child as a daemon, we'd have to worry about the parent process exiting zombifying the daemon.""" if os.fork() == 0: pid = os.fork() ...
Populates this graph from the given one based on affected_files
def populate_from_trace_graph(self, graph: TraceGraph) -> None: """Populates this graph from the given one based on affected_files """ # Track which trace frames have been visited as we populate the full # traces of the graph. self._visited_trace_frame_ids: Set[int] = set() ...
Populates the trimmed graph with issues whose locations are in affected_files based on data in the input graph. Since these issues exist in the affected files all traces are copied as well.
def _populate_affected_issues(self, graph: TraceGraph) -> None: """Populates the trimmed graph with issues whose locations are in affected_files based on data in the input graph. Since these issues exist in the affected files, all traces are copied as well. """ affected_instance_...
TraceFrames found in affected_files should be reachable via some issue instance. Follow traces of graph to find them and populate this TrimmedGraph with it.
def _populate_issues_from_affected_trace_frames(self, graph: TraceGraph) -> None: """TraceFrames found in affected_files should be reachable via some issue instance. Follow traces of graph to find them and populate this TrimmedGraph with it. """ initial_trace_frames = [ ...