text
stringlengths
81
112k
Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. :exc:`~AuthenticationError`: If there is a OperationFailure due to Authentication failure after connecting to the database. :exc:`~Config...
Add the routes to an app def add_routes(app): """Add the routes to an app""" for (prefix, routes) in API_SECTIONS: api = Api(app, prefix=prefix) for ((pattern, resource, *args), kwargs) in routes: kwargs.setdefault('strict_slashes', False) api.add_resource(resource, patt...
Set the chat as yourself. In this context, "yourself" means the user behind the master channel. Every channel should relate this to the corresponding target. Returns: EFBChat: This object. def self(self) -> 'EFBChat': """ Set the chat as yourself. In this co...
Set the chat as a system chat. Only set for channel-level and group-level system chats. Returns: EFBChat: This object. def system(self) -> 'EFBChat': """ Set the chat as a system chat. Only set for channel-level and group-level system chats. Returns: ...
Shortcut property, if alias exists, this will provide the alias with name in parenthesis. Otherwise, this will return the name def long_name(self) -> str: """ Shortcut property, if alias exists, this will provide the alias with name in parenthesis. Otherwise, this will return the name ...
Verify the completeness of the data. Raises: ValueError: When this chat is invalid. def verify(self): """ Verify the completeness of the data. Raises: ValueError: When this chat is invalid. """ if any(not i for i in (self.chat_uid, self.module_i...
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features ...
Check prerequisites of the framework, including Python version, installation of modules, etc. Returns: Optional[str]: If the check is not passed, return error message regarding failed test case. None is returned otherwise. def prerequisite_check(): """ Check prerequisites of the f...
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features ...
Verify the validity of message. def verify(self): """ Verify the validity of message. """ if self.author is None or not isinstance(self.author, EFBChat): raise ValueError("Author is not valid.") else: self.author.verify() if self.chat is None or n...
Version bump logic def bump_version(v: version.Version, level: str) -> str: """Version bump logic""" release: List[int] = list(v.release) stage: Optional[str] pre: Optional[int] stage, pre = v.pre if v.pre else (None, None) dev: Optional[int] = v.dev post: Optional[int] = v.post if lev...
Decorator for slave channel's "additional features" interface. Args: name (str): A human readable name for the function. desc (str): A short description and usage of it. Use ``{function_name}`` in place of the function name in the description. Returns: The decor...
Get the base data path for EFB. This can be defined by the environment variable ``EFB_DATA_PATH``. If ``EFB_DATA_PATH`` is not defined, this gives ``~/.ehforwarderbot``. This method creates the queried path if not existing. Returns: The base path. def get_base_path() -> Path:...
Get the path for persistent storage of a module. This method creates the queried path if not existing. Args: module_id (str): Module ID Returns: The data path of indicated module. def get_data_path(module_id: str) -> Path: """ Get the path for persistent storage of a modu...
Get path for configuration file. Defaulted to ``~/.ehforwarderbot/profiles/profile_name/channel_id/config.yaml``. This method creates the queried path if not existing. The config file will not be created, however. Args: module_id (str): Module ID. ext (Optional[Str]): Extension...
Get the path to custom channels Returns: The path for custom channels. def get_custom_modules_path() -> Path: """ Get the path to custom channels Returns: The path for custom channels. """ channel_path = get_base_path() / "modules" if not channel_path.exists(): cha...
Locate module by module ID Args: module_id: Module ID module_type: Type of module, one of ``'master'``, ``'slave'`` and ``'middleware'`` def locate_module(module_id: str, module_type: str = None): """ Locate module by module ID Args: module_id: Module ID module_type: T...
Register the channel with the coordinator. Args: channel (EFBChannel): Channel to register def add_channel(channel: EFBChannel): """ Register the channel with the coordinator. Args: channel (EFBChannel): Channel to register """ global master, slaves if isinstance(channel, ...
Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register def add_middleware(middleware: EFBMiddleware): """ Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register """ global middlewares ...
Deliver a message to the destination channel. Args: msg (EFBMsg): The message Returns: The message sent by the destination channel, includes the updated message ID from there. Returns ``None`` if the message is not sent. def send_message(msg: 'EFBMsg') -> Optional['EFBMsg']: ...
Deliver a message to the destination channel. Args: status (EFBStatus): The status def send_status(status: 'EFBStatus'): """ Deliver a message to the destination channel. Args: status (EFBStatus): The status """ global middlewares, master if status is None: return ...
Return the module instance of a provided module ID Args: module_id: Module ID, with instance ID if available. Returns: Module instance requested. Raises: NameError: When the module is not found. def get_module_by_id(module_id: str) -> Union[EFBChannel, EFBMiddleware]: """ ...
Initialize all channels. def init(conf): """ Initialize all channels. """ logger = logging.getLogger(__name__) # Initialize mimetypes library mimetypes.init([pkg_resources.resource_filename('ehforwarderbot', 'mimetypes')]) # Initialize all channels # (Load libraries and modules and i...
Start threads for polling def poll(): """ Start threads for polling """ coordinator.master_thread.start() for i in coordinator.slave_threads: coordinator.slave_threads[i].start()
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...
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. def setup_telemetry(key: str): """ Setup telemetry EH Fo...
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 Returns: con(class): Connect...
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: query_execution(dict)::: resul...
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 calculations connect_times(list): List of connect_tim...
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)::: usedram(float): Amount of memory (in MB) used...
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 compi...
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 N...
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="Dia...
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-a...
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(...
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, ...
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.py gen-py/mapd/ttyp...
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)...
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 be called. e.g. <function say_hello at 0x10...
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_reconnect' is specified we retrieve a...
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. Note: The RTM API only supports posting simple messages formatted using our default message formatting mode. It does not support attachments or other message formatting modes. For this reason we recommend us...
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: SlackClientNotConnectedError: Websocket connection is closed. def...
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 specified callback is not callable. ...
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 retrieve a new url and reconnect any time the...
Process messages received on the WebSocket connection. Iteration terminates when the client is stopped or it disconnects. async def _read_messages(self): """Process messages received on the WebSocket connection. Iteration terminates when the client is stopped or it disconnects. """ ...
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. 'bot_added' data (dict): The data Slack sent. e...
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. def _execute_callback_async(self, callback, data): """Execute the callback asynchrono...
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.pro...
Retreives the WebSocket info from Slack. Returns: A tuple of websocket information. e.g. ( "wss://...", { "self": {"id": "U01234ABC","name": "robotoverlord"}, "team": { "domain": ...
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 amount of wait time specified via 'max_wait_time'. However, if ...
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 s...
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 w...
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. """...
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.ge...
Renames a channel. Args: channel (str): The channel id. e.g. 'C1234567890' name (str): The new channel name. e.g. 'newchannel' def channels_rename(self, *, channel: str, name: str, **kwargs) -> SlackResponse: """Renames a channel. Args: channel (str): The c...
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. e.g. '1234567890.123456' def channels_replies(self, *, channel: str, thread_ts: str, *...
Unarchives a channel. Args: channel (str): The channel id. e.g. 'C1234567890' def channels_unarchive(self, *, channel: str, **kwargs) -> SlackResponse: """Unarchives a channel. Args: channel (str): The channel id. e.g. 'C1234567890' """ self._validate_x...
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' def chat_delete(self, *, channel: str, ts: str, **kwargs) -> SlackResponse: """Deletes a message. ...
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' def chat_getPermalink( self, *, channel: str, message_ts: str, **kwargs ) -> SlackResponse: """Re...
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' def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse: """Share a me message into a channel. ...
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' text (str): The message you'd like to share. e.g. 'Hello world' text is not requ...
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 unfurl behavior to. e.g. '1234567890.123456' unfurls (dict): a dict of the specific URLs you're offering an u...
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'] def conversations_invite( self, *, channel: str, users: List[str], **kwargs ) -> SlackResponse: """I...
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. e.g. '1234567890.123456' def conversations_replies(self, *, channel: str, ts: str, **kwargs) ->...
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' def conversations_setTopic( self, *, channel: str, topic: str, **kwargs ) -> SlackResponse: """Sets the topic for a...
Open a dialog with a user. Args: dialog (dict): A dictionary of dialog arguments. { "callback_id": "46eh782b0", "title": "Request something", "submit_label": "Request", "state": "Max", ...
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. Args: num_minutes (int): The snooze duration. e.g. 60 def dnd_setSnooze(self, *, num_minutes: int, **kwargs) -> SlackResponse: """Turns on Do Not Disturb mode for the current user, or changes its duration. ...
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. 'F1234467890' def files_comments_add(self, *, comment: str, file: 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' def files_comments_delete(self, *, file: str, id: str, **kwargs) -> SlackResponse: """Deletes an existing comment on a file. Args...
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 file id. e.g. 'F1234467890' id (str): The file comment id. e.g. 'Fc1234567890' def files_comments_edit( ...
Deletes a file. Args: id (str): The file id. e.g. 'F1234467890' 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(...
Gets information about a team file. Args: id (str): The file id. e.g. 'F1234467890' 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({"i...
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. Args: id (str): The file id. e.g. 'F1234467890' def files_sharedPublicURL(self, *, id: str, **kwargs) -> SlackResponse: """Enables a file for public/external sharing. Args: id (str): The file id. e.g. 'F1234467890' ""...
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 (str): Supply content when you'd like to create an editable text file containing the specified text. e.g. 'launch plan'...
Clones and archives a private channel. Args: channel (str): The group id. e.g. 'G1234567890' def groups_createChild(self, *, channel: str, **kwargs) -> SlackResponse: """Clones and archives a private channel. Args: channel (str): The group id. e.g. 'G1234567890' ...
Invites a user to a private channel. Args: channel (str): The group id. e.g. 'G1234567890' user (str): The user id. e.g. 'U1234567890' def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse: """Invites a user to a private channel. Args: ...
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. e.g. '1234567890.123456' def groups_replies(self, *, channel: str, thread_ts: ...
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' def groups_setPurpose(self, *, channel: str, purpose: str, **kwargs) -> SlackResponse: """Sets the purpose for a pri...
Opens a direct message channel. Args: user (str): The user id to open a DM with. e.g. 'W1234567890' 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' ...
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'] def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse: """For Enter...
Closes a multiparty direct message channel. Args: channel (str): Multiparty Direct message channel to close. e.g. 'G1234567890' def mpim_close(self, *, channel: str, **kwargs) -> SlackResponse: """Closes a multiparty direct message channel. Args: channel (str): Multipa...
Fetches history of messages and events from a multiparty direct message. Args: channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890' def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse: """Fetches history of messages and events from a multiparty d...
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', 'U2345678901', 'U3456789012'] def mpim_open(self, *, users: List[str], **kwargs) ->...
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 (str): Issued when you created your application. e.g. '33fea0113f5b1' code (str): The code param returned via the...
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' timestamp (str): Timestamp of the message to add reaction to. e.g. '1234567890.1234...
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. '1602288000'), the number of seconds until the reminder (if within 24 h...
Marks a reminder as complete. Args: reminder (str): The ID of the reminder to be marked as complete. e.g. 'Rm12345678' def reminders_complete(self, *, reminder: str, **kwargs) -> SlackResponse: """Marks a reminder as complete. Args: reminder (str): The ...
Gets information about a reminder. Args: reminder (str): The ID of the reminder. e.g. 'Rm12345678' def reminders_info(self, *, reminder: str, **kwargs) -> SlackResponse: """Gets information about a reminder. Args: reminder (str): The ID of the reminder. e.g. 'Rm1234567...
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. Args: query (str): Search query. May contains booleans, etc. e.g. 'pickleface' def search_messages(self, *, query: str, **kwargs) -> SlackResponse: """Searches for messages matching a query. Args: query (str): Sea...
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 Args: name (str): A name for the User Group. Must be unique among User Groups. e.g. 'My Test Team' def usergroups_create(self, *, name: str, **kwargs) -> SlackResponse: """Create a User Group Args: name (str): A name for the User Gro...