def execute(cls, slack_wrapper, args, timestamp, channel_id, user_id, user_is_admin): current_members = slack_wrapper.get_channel_members(channel_id) # strip uid formatting invited_users = [user.strip("<>@") for user in args] # remove already present members invited_users = [user for user in invited_users if user not in current_members] failed_users = [] for member in invited_users: if not slack_wrapper.invite_user(member, channel_id)["ok"]: failed_users.append(member) if failed_users: log.exception("BotHandler::InviteCommand") raise InvalidCommand("Sorry, couldn't invite the following members to the channel: " + ' '.join(failed_users))
def add_file(self, data, filename): """Add a file to the commit.""" try: full_filename = os.path.join(self.repo_path, filename) with open(full_filename, "w") as f: f.write(data) porcelain.add(self.repo, full_filename) except Exception: # Anonymizing exceptions log.exception("GitHandler::add_file()") raise InvalidCommand( "Adding file failed: Please check your log files...")
def push(self, repo_user, repo_pass, repo_remote, repo_branch): """Push the current commit to git.""" try: porcelain.push( self.repo, "https://{}:{}@{}".format(repo_user, repo_pass, repo_remote), bytes(repo_branch, "utf-8")) except dulwich.errors.GitProtocolError: raise InvalidCommand( "Upload file failed: GitProtocolError - Check your username and password in the git configuration..." ) except KeyError: raise InvalidCommand( "Upload file failed: KeyError - Check your git configuration for missing keys..." ) except TypeError: raise InvalidCommand( "Upload file failed: TypeError - Did you forget to create a git configuration?" ) except Exception: log.exception("GitHandler::push()") raise InvalidCommand( "Upload file failed: Unknown - Please check your log files...")
def process(self, slack_wrapper, command, args, timestamp, channel, user, user_is_admin): """Check if enough arguments were passed for this command.""" if command in self.aliases: self.process(slack_wrapper, self.aliases[command], args, timestamp, channel, user, user_is_admin) elif command in self.commands: cmd_descriptor = self.commands[command] if cmd_descriptor: if len(args) < len(cmd_descriptor.arguments): raise InvalidCommand( self.command_usage(command, cmd_descriptor)) cmd_descriptor.command.execute(slack_wrapper, args, timestamp, channel, user, user_is_admin)
def get_challenge_by_name(database, challenge_name, ctf_channel_id): """ Fetch a Challenge object in the database with a given name and ctf channel ID. Return the matching Challenge object if found, or None otherwise. """ ctfs = pickle.load(open(database, "rb")) if ctf_channel_id not in ctfs: raise InvalidCommand("Could not find corresponding ctf channel. Try reloading ctf data.") for challenge in ctfs[ctf_channel_id].challenges: if challenge.name == challenge_name: return challenge return None
def execute(cls, slack_wrapper, args, timestamp, channel_id, user_id, user_is_admin): """Execute the As command.""" dest_user = args[0].lower() dest_command = args[1].lower().lstrip("!") dest_arguments = args[2:] user_obj = resolve_user_by_user_id(slack_wrapper, dest_user) if user_obj['ok']: dest_user_id = user_obj['user']['id'] # Redirecting command execution to handler factory handler_factory.process_command(slack_wrapper, dest_command, [dest_command] + dest_arguments, timestamp, channel_id, dest_user_id, user_is_admin) else: raise InvalidCommand("You have to specify a valid user (use @-notation).")
def post_ctf_data(ctf, title): """Create a post and a statistic file and upload it to the configured SolveTracker repository.""" if not ST_GIT_SUPPORT: raise Exception( "Sorry, but the SolveTracker support isn't configured...") try: now = datetime.datetime.now() post_data = resolve_ctf_template( ctf, title, "./templates/post_ctf_template", "./templates/post_challenge_template") post_filename = "_posts/{}-{}-{}-{}.md".format(now.year, now.month, now.day, ctf.name) stat_data = resolve_stats_template(ctf) stat_filename = "_stats/{}.json".format(ctf.name) git = GitHandler(ST_GIT_CONFIG.get("git_repopath")) git.add_file(post_data, post_filename) git.add_file(stat_data, stat_filename) git.commit("Solve post from {}".format(ctf.name)) git.push(ST_GIT_CONFIG.get("git_repouser"), ST_GIT_CONFIG.get("git_repopass"), ST_GIT_CONFIG.get("git_remoteuri"), ST_GIT_CONFIG.get("git_branch")) return ST_GIT_CONFIG.get("git_baseurl") except InvalidCommand as invalid_cmd: # Just pass invalid commands on raise invalid_cmd except Exception: log.exception("SolvePostHelper") raise InvalidCommand( "Something with your configuration files doesn't seem to be correct. Please check your logfiles..." )
def execute(cls, slack_wrapper, args, timestamp, channel_id, user_id, user_is_admin): if user_is_admin: if handler_factory.botserver.get_config_option("maintenance_mode"): import pdb; pdb.set_trace() else: InvalidCommand("Must be in maintenance mode to open a shell")
def execute(cls, slack_wrapper, args, timestamp, channel_id, user_id, user_is_admin): """Execute the save command.""" if not LINKSAVE_SUPPORT: raise InvalidCommand( "Save Link failed: Link saver not configured.") if args[0] not in CATEGORIES: raise InvalidCommand("Save Link failed: Invalid Category.") if LINKSAVE_CONFIG["allowed_users"] and user_id not in LINKSAVE_CONFIG[ "allowed_users"]: raise InvalidCommand( "Save Link failed: User not allowed to save links") message = slack_wrapper.get_message(channel_id, timestamp)["messages"][0]["text"] profile_details = slack_wrapper.get_member(user_id)["user"]["profile"] # http://www.noah.org/wiki/RegEx_Python#URL_regex_pattern url_regex = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+" url = re.search(url_regex, message) if not url: slack_wrapper.post_message( channel_id, "Save Link failed: Unable to extract URL", timestamp) return try: url_data = unfurl(url.group()) except requests.exceptions.Timeout as e: slack_wrapper.post_message(channel_id, "Save Link failed: Request timed out", timestamp) log.error(e) return data = { "options[staticman-token]": LINKSAVE_CONFIG["staticman-token"], "fields[title]": url_data["title"], "fields[link]": url.group(), "fields[excerpt]": url_data["desc"], "fields[category]": args[0], "fields[header][overlay_image]": url_data["img"], "fields[user]": profile_details["display_name"] or profile_details["real_name"] } resp = requests.post( "https://mystaticmanapp.herokuapp.com/v2/entry/{git_repo}/{git_branch}/links" .format_map(LINKSAVE_CONFIG), data=data).json() if resp["success"]: slack_wrapper.post_message(channel_id, "Link saved successfully", timestamp) else: slack_wrapper.post_message(channel_id, "Error saving the link", timestamp) log.error(resp)
def set_config_option_mock(self, option, value): if option in self.botserver.config: self.botserver.config[option] = value else: raise InvalidCommand("The specified configuration option doesn't exist: {}".format(option))