black: Reformat skipping string normalization.

This commit is contained in:
PIG208 2021-05-28 17:03:46 +08:00 committed by Tim Abbott
parent 5580c68ae5
commit fba21bb00d
178 changed files with 6562 additions and 4469 deletions

View file

@ -10,40 +10,43 @@ def parse_args() -> argparse.Namespace:
mutually_exclusive_args = parser.add_mutually_exclusive_group(required=True)
# config-file or use-env-vars made mutually exclusive to prevent conflicts
mutually_exclusive_args.add_argument(
'--config-file', '-c',
'--config-file',
'-c',
action='store',
help='Config file for the Botserver. Use your `botserverrc` for multiple bots or'
'`zuliprc` for a single bot.'
'`zuliprc` for a single bot.',
)
mutually_exclusive_args.add_argument(
'--use-env-vars', '-e',
'--use-env-vars',
'-e',
action='store_true',
help='Load configuration from JSON in ZULIP_BOTSERVER_CONFIG environment variable.'
help='Load configuration from JSON in ZULIP_BOTSERVER_CONFIG environment variable.',
)
parser.add_argument(
'--bot-config-file',
action='store',
default=None,
help='Config file for bots. Only needed when one of '
'the bots you want to run requires a config file.'
'the bots you want to run requires a config file.',
)
parser.add_argument(
'--bot-name', '-b',
'--bot-name',
'-b',
action='store',
help='Run a single bot BOT_NAME. Use this option to run the Botserver '
'with a `zuliprc` config file.'
'with a `zuliprc` config file.',
)
parser.add_argument(
'--hostname',
action='store',
default="127.0.0.1",
help='Address on which you want to run the Botserver. (default: %(default)s)'
help='Address on which you want to run the Botserver. (default: %(default)s)',
)
parser.add_argument(
'--port',
action='store',
default=5002,
type=int,
help='Port on which you want to run the Botserver. (default: %(default)d)'
help='Port on which you want to run the Botserver. (default: %(default)d)',
)
return parser.parse_args()

View file

@ -30,12 +30,15 @@ def read_config_section(parser: configparser.ConfigParser, section: str) -> Dict
}
return section_info
def read_config_from_env_vars(bot_name: Optional[str] = None) -> Dict[str, Dict[str, str]]:
bots_config = {} # type: Dict[str, Dict[str, str]]
json_config = os.environ.get('ZULIP_BOTSERVER_CONFIG')
if json_config is None:
raise OSError("Could not read environment variable 'ZULIP_BOTSERVER_CONFIG': Variable not set.")
raise OSError(
"Could not read environment variable 'ZULIP_BOTSERVER_CONFIG': Variable not set."
)
# Load JSON-formatted environment variable; use OrderedDict to
# preserve ordering on Python 3.6 and below.
@ -51,26 +54,34 @@ def read_config_from_env_vars(bot_name: Optional[str] = None) -> Dict[str, Dict[
first_bot_name = list(env_config.keys())[0]
bots_config[bot_name] = env_config[first_bot_name]
logging.warning(
"First bot name in the config list was changed from '{}' to '{}'".format(first_bot_name, bot_name)
"First bot name in the config list was changed from '{}' to '{}'".format(
first_bot_name, bot_name
)
)
else:
bots_config = dict(env_config)
return bots_config
def read_config_file(config_file_path: str, bot_name: Optional[str] = None) -> Dict[str, Dict[str, str]]:
def read_config_file(
config_file_path: str, bot_name: Optional[str] = None
) -> Dict[str, Dict[str, str]]:
parser = parse_config_file(config_file_path)
bots_config = {} # type: Dict[str, Dict[str, str]]
if bot_name is None:
bots_config = {section: read_config_section(parser, section)
for section in parser.sections()}
bots_config = {
section: read_config_section(parser, section) for section in parser.sections()
}
return bots_config
logging.warning("Single bot mode is enabled")
if len(parser.sections()) == 0:
sys.exit("Error: Your Botserver config file `{0}` does not contain any sections!\n"
"You need to write the name of the bot you want to run in the "
"section header of `{0}`.".format(config_file_path))
sys.exit(
"Error: Your Botserver config file `{0}` does not contain any sections!\n"
"You need to write the name of the bot you want to run in the "
"section header of `{0}`.".format(config_file_path)
)
if bot_name in parser.sections():
bot_section = bot_name
@ -80,7 +91,9 @@ def read_config_file(config_file_path: str, bot_name: Optional[str] = None) -> D
bot_section = parser.sections()[0]
bots_config[bot_name] = read_config_section(parser, bot_section)
logging.warning(
"First bot name in the config list was changed from '{}' to '{}'".format(bot_section, bot_name)
"First bot name in the config list was changed from '{}' to '{}'".format(
bot_section, bot_name
)
)
ignored_sections = parser.sections()[1:]
@ -98,6 +111,7 @@ def parse_config_file(config_file_path: str) -> configparser.ConfigParser:
parser.read(config_file_path)
return parser
# TODO: Could we use the function from the bots library for this instead?
def load_module_from_file(file_path: str) -> ModuleType:
# Wrapper around importutil; see https://stackoverflow.com/a/67692/3909240.
@ -107,6 +121,7 @@ def load_module_from_file(file_path: str) -> ModuleType:
spec.loader.exec_module(lib_module)
return lib_module
def load_lib_modules(available_bots: List[str]) -> Dict[str, Any]:
bots_lib_module = {}
for bot in available_bots:
@ -118,10 +133,14 @@ def load_lib_modules(available_bots: List[str]) -> Dict[str, Any]:
lib_module = import_module(module_name)
bots_lib_module[bot] = lib_module
except ImportError:
error_message = ("Error: Bot \"{}\" doesn't exist. Please make sure "
"you have set up the botserverrc file correctly.\n".format(bot))
error_message = (
"Error: Bot \"{}\" doesn't exist. Please make sure "
"you have set up the botserverrc file correctly.\n".format(bot)
)
if bot == "api":
error_message += "Did you forget to specify the bot you want to run with -b <botname> ?"
error_message += (
"Did you forget to specify the bot you want to run with -b <botname> ?"
)
sys.exit(error_message)
return bots_lib_module
@ -133,15 +152,14 @@ def load_bot_handlers(
) -> Dict[str, lib.ExternalBotHandler]:
bot_handlers = {}
for bot in available_bots:
client = Client(email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"])
client = Client(
email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"],
)
bot_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bots', bot)
bot_handler = lib.ExternalBotHandler(
client,
bot_dir,
bot_details={},
bot_config_parser=third_party_bot_conf
client, bot_dir, bot_details={}, bot_config_parser=third_party_bot_conf
)
bot_handlers[bot] = bot_handler
@ -176,13 +194,17 @@ def handle_bot() -> str:
bot_config = config
break
else:
raise BadRequest("Cannot find a bot with email {} in the Botserver "
"configuration file. Do the emails in your botserverrc "
"match the bot emails on the server?".format(event['bot_email']))
raise BadRequest(
"Cannot find a bot with email {} in the Botserver "
"configuration file. Do the emails in your botserverrc "
"match the bot emails on the server?".format(event['bot_email'])
)
if bot_config['token'] != event['token']:
raise Unauthorized("Request token does not match token found for bot {} in the "
"Botserver configuration file. Do the outgoing webhooks in "
"Zulip point to the right Botserver?".format(event['bot_email']))
raise Unauthorized(
"Request token does not match token found for bot {} in the "
"Botserver configuration file. Do the outgoing webhooks in "
"Zulip point to the right Botserver?".format(event['bot_email'])
)
app.config.get("BOTS_LIB_MODULES", {})[bot]
bot_handler = app.config.get("BOT_HANDLERS", {})[bot]
message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot]
@ -213,17 +235,24 @@ def main() -> None:
try:
bots_config = read_config_file(options.config_file, options.bot_name)
except MissingSectionHeaderError:
sys.exit("Error: Your Botserver config file `{0}` contains an empty section header!\n"
"You need to write the names of the bots you want to run in the "
"section headers of `{0}`.".format(options.config_file))
sys.exit(
"Error: Your Botserver config file `{0}` contains an empty section header!\n"
"You need to write the names of the bots you want to run in the "
"section headers of `{0}`.".format(options.config_file)
)
except NoOptionError as e:
sys.exit("Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
"You need to add option `{1}` with appropriate value in section `{2}` of `{0}`"
.format(options.config_file, e.option, e.section))
sys.exit(
"Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
"You need to add option `{1}` with appropriate value in section `{2}` of `{0}`".format(
options.config_file, e.option, e.section
)
)
available_bots = list(bots_config.keys())
bots_lib_modules = load_lib_modules(available_bots)
third_party_bot_conf = parse_config_file(options.bot_config_file) if options.bot_config_file is not None else None
third_party_bot_conf = (
parse_config_file(options.bot_config_file) if options.bot_config_file is not None else None
)
bot_handlers = load_bot_handlers(available_bots, bots_config, third_party_bot_conf)
message_handlers = init_message_handlers(available_bots, bots_lib_modules, bot_handlers)
app.config["BOTS_LIB_MODULES"] = bots_lib_modules
@ -231,5 +260,6 @@ def main() -> None:
app.config["MESSAGE_HANDLERS"] = message_handlers
app.run(host=options.hostname, port=int(options.port), debug=True)
if __name__ == '__main__':
main()