def vet_file(basefile: str): """ Read in the file $BASEFILE as newline-separated list, offers elements to user one by one to vet via cmd line. Approved elements are stored in $BASEFILE.vetted. Elements-to-vet stored in $BASEFILE.in_prog_vet. If this file exists when `vet` is called, user has the option of continuing the in-progress vet or starting a new one. """ in_prog_file = fname_in_prog_vet(basefile) accepted = [] use_existing_vet = False if os.path.isfile(in_prog_file): print('Vet in progress, continue existing? [Y/n]') answer = utils.ask_user_yn() if answer: frontmatter, elems = utils.file_to_list(in_prog_file) _, accepted = utils.file_to_list(fname_vetted(basefile)) use_existing_vet = True else: os.remove(in_prog_file) # if no in-prog file but there exist a .vetted file? if not use_existing_vet: frontmatter, elems = utils.file_to_list(basefile) print('Elems to vet: {}'.format(len(elems))) finished = False i = 0 try: for i, elem in enumerate(elems): print('{} -- approve? [y/N]'.format(elem)) answer = utils.ask_user_yn(default=False) if answer: accepted.append(elem) print('hooray, finished vet!') finished = True finally: if len(accepted) > 0: utils.list_to_file(fname_vetted(basefile), frontmatter + accepted) if finished: print('Accepted {} candidates'.format(len(accepted))) if os.path.isfile(in_prog_file): os.remove(in_prog_file) else: utils.list_to_file(in_prog_file, frontmatter + elems[i:]) print('Accepted {} candidates ({} remaining)'.format( len(accepted), len(elems) - i))
def score_file(basefile: str): """ Read in the file $BASEFILE as newline-separated list, offers elements to user one by one to vet via cmd line to score. Approved elements are stored in $BASEFILE.scored. Elements-to-score stored in $BASEFILE.in_prog_score. If this file exists when `score` is called, user has the option of continuing the in-progress score or starting a new one. """ in_prog_file = fname_in_prog_score(basefile) scored = [] use_existing_score = False if os.path.isfile(in_prog_file): print('Score in progress, continue existing? [Y/n]') answer = utils.ask_user_yn() if answer: frontmatter, elems = utils.file_to_list(in_prog_file) _, scored = utils.file_to_list(fname_scored(basefile)) use_existing_score = True else: os.remove(in_prog_file) # if no in-prog file but there exist a .scored file? if not use_existing_score: frontmatter, elems = utils.file_to_list(basefile) print('Elems to score: {}'.format(len(elems))) finished = False i = 0 try: for i, elem in enumerate(elems): print(elem) score = ask_user_score() scored.append('{};{}'.format(elem, score)) print('hooray, finished scoring!') finished = True finally: if len(scored) > 0: utils.list_to_file(fname_scored(basefile), frontmatter + scored) if finished: print('Scored {} candidates'.format(len(scored))) if os.path.isfile(in_prog_file): os.remove(in_prog_file) else: utils.list_to_file(in_prog_file, frontmatter + elems[i:]) print('Scored {} candidates ({} remaining)'.format( len(scored), len(elems) - i))
def wikisort_file(file: str): _, names = utils.file_to_list(file) scores = {} couldnt_find = [] utils.print_progress_bar(0, len(names)) for i, name in enumerate(names): try: scores[name] = views_per_month(name) except: # should probably keep track of the exceptions (so can tell if it's rate limiting etc.) couldnt_find.append(name) finally: utils.print_progress_bar(i + 1, len(names)) print() print('---FAILED TO FIND---') print(couldnt_find) print('------') print() sort_by_views = [ '{}\t{}'.format(k, v) for k, v in sorted(scores.items(), key=lambda x: x[1], reverse=True) ] utils.list_to_file(fname_ranked(file), sort_by_views, do_dedupe=False)
def append_from_file(self, input_file_str): linelist = file_to_list(input_file_str) for line in linelist: result = [word.strip() for word in line.split(' ')] if len(result) != 3: self.__table['ERROR'] = self.addrflag('MALFORMED', 'ENTRY') print( '[dns_module]: Input \'{}\' from file \'{}\' is malformed. Unable to add entry to table.\n' .format(line, input_file_str)) else: if result[ 2] == DNS_table.flag.NS.value and self.__ts_hostname == '__NONE__': self.__ts_hostname = result[0] print( '[dns_module]: ts_hostname assigned as \'{}\'.'.format( result[0])) elif result[2] == DNS_table.flag.A.value: self.__table[result[0]] = self.addrflag( result[1], result[2]) print( '[dns_module]: \'{} : ({}, {})\' added to table from file \'{}\'.' .format(result[0], result[1], result[2], input_file_str)) print('')
def append_from_file(self, input_file_str): linelist = file_to_list(input_file_str) for line in linelist: result = [word.strip() for word in line.split(' ')] if len(result) != 3: self.__table['ERROR'] = self.addrflag('MALFORMED', 'ENTRY') msg = 'Input \'{}{}{}\' from file \'{}{}{}\' is malformed. Unable to add entry to table.\n'.format(K.color.bold.WHT, line, K.NRM, K.color.bold.WHT, input_file_str, K.NRM) log(logstat.ERR, funcname(), msg) else: if result[2] == DNS_table.flag.NS.value and self.__ts_hostname == '__NONE__': self.__ts_hostname = result[0] msg = 'ts_hostname assigned as \'{}{}{}\'.'.format(K.color.bold.WHT, result[0], K.NRM) log(logstat.LOG, funcname(), msg) elif result[2] == DNS_table.flag.A.value: self.__table[result[0]] = self.addrflag(result[1], result[2]) msg = '{}\'{} : ({}, {}){}\' added to table from file {}\'{}\'{}.'.format(K.color.bold.WHT, result[0], result[1], result[2], K.NRM, K.color.bold.WHT, input_file_str, K.NRM) log(logstat.LOG, funcname(), msg) print('')
def get_files(play_path, gender_path): play_lines_raw = file_to_list(play_path) try: gender = json_file_to_dict(gender_path) except FileNotFoundError: print("require gender file") gender = None return play_lines_raw, gender
def spookjoke(): name = random.choice(utils.file_to_list('Sp00k.txt')) path_name = slugify(name, word_boundary=True, separator="_") path = "{0}/{1}".format("spook", path_name) tweet_image = utils.get_image(path) name = re.sub(r' \([^)]*\)', '', name) m = "Oh oh! Looks like your command was stolen by {0}!! #Sp00ky".format(name) return m, tweet_image
def spookjoke(): name = random.choice(utils.file_to_list('Sp00k.txt')) path_name = slugify(name, word_boundary=True, separator="_") path = "{0}/{1}".format("spook", path_name) tweet_image = utils.get_image(path) name = re.sub(r' \([^)]*\)', '', name) m = "Oh oh! Looks like your command was stolen by {0}!! #Sp00ky".format( name) return m, tweet_image
def __init__(self, training_files, segment_length, mu_quantization, filter_length, sampling_rate): training_files = os.path.join('dataset', training_files) self.audio_files = utils.file_to_list(training_files) random.seed(123) random.shuffle(self.audio_files) self.segment_length = segment_length self.mu_quantization = mu_quantization self.sampling_rate = sampling_rate
def main(): # manifest_file, sourceSql, targetSql, version, appName = check_arg(sys.argv[1:]) # ini_file = "%s/config/%s.ini" % (os.environ['HOME'], os.environ['APP_NAME']) accounts = {"DV": "CISCODEV.US-EAST-1", "TS": "CISCOSTAGE.US-EAST-1", "PR": "CISCO.US-EAST-1"} # ini_file = "%s/config/%s.ini" % (os.environ['HOME'], appName) # config = ConfigObject(filename=ini_file) # ctx = open_database_connection(config, appName, accounts[targetSql[:2]]) # cs = ctx.cursor() # # targetPath = targetSql # if targetSql == 'PRD': # targetPath = 'PROD' # # path = "%s/%s/%s/sql/%s" % (os.environ['HOME'], # targetPath, # appName, # version) # # log_file_path = "%s/%s/%s/log/%s" % (os.environ['HOME'], # targetPath, # appName, # version) # if not os.path.exists(log_file_path): # os.mkdir(log_file_path) try: sqlFiles = file_to_list('release.manifest') fileName = extract_file_name('release.manifest') start_point_name = "start_point_" + fileName start_point_file = start_point_name + ".txt" file_start, sql_start = getStartPoint(start_point_name) done = True for i in range(file_start - 1, len(sqlFiles)): sqlFileName = extract_file_name(sqlFiles[i]) log_file = sqlFileName + ".log" setup_logger(sqlFileName, log_file) log = logging.getLogger(sqlFileName) log.info("SQL Execution Starts") sqlCommands = getTargetSqls(sqlFiles[i], 'PRD', 'DV3', log) pdb.set_trace() log.info(str(i + 1) + ".File " + sqlFiles[i] + ":") success = execute_sqls(cs, sqlCommands, i + 1, sql_start, start_point_name, path, log) if not success: done = False break log.info("SQL Execution Ends") if done: os.remove(start_point_file) finally: cs.close() ctx.close()
def dedupe_from_file(file: str): """ Read in the file $FILE as newline-separated list, dedupe list and write to $FILE.deduped """ frontmatter, elems = utils.file_to_list(file, do_dedupe=False) print('Elems before dedupe: {}'.format(len(elems))) deduped = utils.dedupe(elems, verbose=True) print('Elems after dedupe: {}'.format(len(deduped))) utils.list_to_file(fname_deduped(file), frontmatter + elems)
def waifu(gender, args="", otp=False, DISCORD=False, user_id=False): if gender == 0: list_name = "Waifu" end_tag = "1girl+solo" else: list_name = "Husbando" end_tag = "-1girl+-female" result = "" lines = utils.file_to_list( os.path.join(settings['list_loc'], list_name + " List.txt")) args = ' '.join(args.split()).lower() matched = [] ignore = ["high-school-dxd", "love-live", "aoki-hagane-no-arpeggio", "kantai-collection", "aikatsu", "akb0048", "idolmaster", "idolmaster-cinderella-girls"] if len(args) > 4: for entry in lines: if slugify(entry[1], word_boundary=True) in ignore: continue if slugify(args, word_boundary=True) ==\ slugify(entry[1], word_boundary=True): matched.append(entry) # It's not really that random if there isn't that many people matched. if len(matched) > 4: result = random.choice(matched) if not result: result = random.choice(lines) name, show, otp_img = result if otp: return name, show, otp_img path_name = slugify(name, word_boundary=True, separator="_") path = os.path.join(list_name, path_name) tweet_image = utils.get_image(path) if not tweet_image and not DISCORD: tags = [name.replace(" ", "_"), "solo", "-genderswap", end_tag] tweet_image = utils.get_image_online(tags, 0, 1, "", path) name = re.sub(r' \([^)]*\)', '', name) m = "Your {0} is {1} ({2})".format(list_name.title(), name, show) if user_id: st = "{} ({})".format(name, show) count_command(list_name, st, os.path.join(settings['user_count_loc'], user_id)) count_command(list_name, "{} ({})".format(name, show), settings['count_file']) return m, tweet_image
def main(argv): """Main function, where client function is called Args: Command line arguments (as per sys.argv) argv[1] - ls_hostname desired hostname for LS machine argv[2] - ls_listen_port desired port number for LS machine argv[3] - input_file_name (OPTIONAL) desired name of input file (queried hostnames) argv[4] - output_file_name (OPTIONAL) desired name of output file (resolved host names) Returns: Exit status, by default, 0 upon exit Raises: KeyboardInterrupt if user terminates program with (Ctrl + c) before completion SystemExit causes program to exit upon KeyboardInterrupt """ (ls_info, file_str) = check_args(argv) # ls_info[0] is LS's hostname # ls_info[1] is LS's port number # file_str[0] is the query input file string # file_str[1] is the query output file string print('') # read the input file into a list hostname_list = file_to_list(file_str[0]) if len(hostname_list) > 0: resolved_list = [] # if the hostname list has at least one element, proceed to LS server try: msg = 'Starting client routine. Hit (Ctrl + c) to quit.\n' log(logstat.LOG, funcname(), msg) resolved_list = query_ls(ls_info, hostname_list) except KeyboardInterrupt, SystemExit: print('') msg = 'User terminated program before completion.\n' log(logstat.LOG, funcname(), msg) if len(resolved_list) > 0: # if the resolved_list has at least one element, write to file write_to_file_from_list(file_str[1], resolved_list, 'w')
def main(): parser = argparse.ArgumentParser(description='Preprocess') parser.add_argument('--token-type', type=str, required=True, help='set token type (phoneme, morpheme, word') parser.add_argument('--save-dir', type=str, required=True, help='set output directory. ex) output (not included slash "/")') args = parser.parse_args() inputs = file_to_list('input/raw') if args.token_type == 'phoneme': text_to_phoneme(text=inputs, save_dir=args.save_dir) elif args.token_type == 'morpheme': text_to_morpheme(text=inputs, save_dir=args.save_dir) elif args.token_type == 'word': text_to_word(text=inputs, save_dir=args.save_dir)
def combinate_file(file: str): """ Read in the file of names $FILE as newline-separated list, and for every name, generate crossword candidates: [first last, first, last], etc. Stores results in $FILE.combinated. """ frontmatter, names = utils.file_to_list(file) results = [] for name in names: results.extend(combinate(name)) print('{} names resulted in {} combinations'.format( len(names), len(results))) utils.list_to_file(fname_combinated(file), frontmatter + results)
if not command: continue if reply: print("[{0}] Reading (Late): {1} ({2}): {3}".format( time.strftime("%Y-%m-%d %H:%M"), status.user.screen_name, status.user.id, status.text)) tweet_command(_API, status, tweet, command) TWEETS_READ.append(str(status.id)) with open(os.path.join(settings['ignore_loc'], "tweets_read.txt"), 'w') as file: file.write("\n".join(TWEETS_READ)) print("[INFO] Finished reading late tweets!") if __name__ == '__main__': BLOCKED_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Users.txt")) IGNORE_WORDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Words.txt")) LIMITED = False HAD_ERROR = False LAST_STATUS_CODE = 0 TWEETS_READ = [] MOD_IDS = [2780494890, 121144139] RATE_LIMIT_DICT = {} USER_LAST_COMMAND = OrderedDict() START_TIME = time.time() HANG_TIME = time.time() API = None STATUS_API = None SAPI = None TWEETS_READ = utils.file_to_list(
def acceptable_tweet(status): global USER_LAST_COMMAND global IGNORE_WORDS global BLOCKED_IDS tweet = status.text user = status.user # Ignore ReTweets. if tweet.startswith('RT'): return False, False if DEBUG: if user.id not in MOD_IDS: return False, False # Reload in case of manual updates. BLOCKED_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Users.txt")) IGNORE_WORDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Words.txt")) # Ignore bots and bad boys. if str(user.id) in BLOCKED_IDS: return False, False # Ignore some messages. if any(word.lower() in tweet.lower() for word in IGNORE_WORDS): return False, False # Make sure the message has @Bot in it. if not any("@" + a.lower() in tweet.lower() for a in settings['twitter_track']): return False, False # If the user @sauce_plz add "source" to the text as every @ is later removed. if "sauce" in tweet.lower(): tweet += " source" # Remove extra spaces. tweet = re.sub(' +', ' ', tweet).lstrip() # Remove @UserNames (usernames could trigger commands alone) tweet = tweet.replace("🚢👧", "Shipgirl") tweet = ' '.join( re.sub('(^|\n| )(@[A-Za-z0-9_🚢👧.]+)', ' ', tweet).split()) tweet = tweet.replace("#", "") # Find the command they used. command = utils.get_command(tweet) if command == "WaifuRegister" or command == "HusbandoRegister": # Cut the text off after the command word. reg = "({0})(?i)".format(command) if len(tweet) > (len(command) + len(settings['twitter_track'][0]) + 2): tweet = re.split(reg, tweet)[2].lstrip() # No command is found see if acceptable for a random waifu. if not command: # Ignore quote ReTweets. if tweet.startswith('"@'): return False, False # Ignore if it doesn't mention the main bot only. if settings['twitter_track'][0] not in status.text: return False, False # Last case, check if they're not replying to a tweet. if status.in_reply_to_status_id is None: command = "Waifu" else: return False, False if command == "Reroll": try: command = USER_LAST_COMMAND[user.id] if "Register" in command: return False, False elif "My" in command: return False, False except ValueError: return False, False else: USER_LAST_COMMAND[user.id] = command if len(USER_LAST_COMMAND) > 30: USER_LAST_COMMAND = (OrderedDict( islice(USER_LAST_COMMAND.items(), 20, None))) # Stop someone limiting the bot on their own. rate_time = datetime.datetime.now() rate_limit_secs = 10800 if user.id in RATE_LIMIT_DICT: # User is now limited (3 hours). if ((rate_time - RATE_LIMIT_DICT[user.id][0]) .total_seconds() < rate_limit_secs)\ and (RATE_LIMIT_DICT[user.id][1] >= 15): return False, False # User limit is over. elif ((rate_time - RATE_LIMIT_DICT[user.id][0]).total_seconds() > rate_limit_secs): del RATE_LIMIT_DICT[user.id] else: # User found, not limited, add one to the trigger count. RATE_LIMIT_DICT[user.id][1] += 1 else: # User not found, add them to RATE_LIMIT_DICT. # Before that quickly go through RATE_LIMIT_DICT # and remove all the finished unused users. for person in list(RATE_LIMIT_DICT): if ((rate_time - RATE_LIMIT_DICT[person][0]).total_seconds() > rate_limit_secs): del RATE_LIMIT_DICT[person] RATE_LIMIT_DICT[user.id] = [rate_time, 1] # This shouldn't happen but just in case. if not isinstance(command, str): return False, False tweet = tweet.lower().replace(command.lower(), " ", 1).strip() return tweet, command
OTP_END_TAGS = "+2girls+yuri+-comic" MAX_IN_FOLDER = 5 SLEEP_COUNT = 0 os.chdir(settings['list_loc']) for file in glob.glob("*.txt"): gender = "Waifu" is_list = True if file in IGNORE_TXTS: continue if "husbando" in file.lower() or "male" in file.lower(): # TODO: Temp continue gender = "Husbando" file = os.path.join(settings['list_loc'], file) lines = file_to_list(file) if isinstance(lines[2], str): is_list = False for line in lines: img_count = MAX_IN_FOLDER if is_list: name = line[0] elif "(x)" in line: gender = "OTP" names = line.split("(x)") names = [s.replace(" ", "_") for s in names] name = '+'.join(names) else: name = line if "#" in name: continue
for pos in range(min_pos, max_pos): total_fuel_consumption = 0 for key in lines: total_fuel_consumption += abs(key - pos) if total_fuel_consumption < min_fuel_consumption: min_fuel_consumption = total_fuel_consumption return min_fuel_consumption def part2(lines): min_pos, max_pos = min(lines), max(lines) min_fuel_consumption = 999**9 for pos in range(min_pos, max_pos): total_fuel_consumption = 0 for key in lines: for i in range(abs(key - pos)): total_fuel_consumption += i + 1 if total_fuel_consumption < min_fuel_consumption: min_fuel_consumption = total_fuel_consumption return min_fuel_consumption if __name__ == '__main__': lines = file_to_list('day07.txt', test=False, sep=',', cast=int) result1 = part1(lines) print("Day 7, part 1:", result1) result2 = part2(lines) print("Day 7, part 2:", result2)
def main(argv): """Main function, where client function is called Args: Command line arguments (as per sys.argv) argv[1] - rs_hostname desired hostname for RS program argv[2] - rs_listen_port desired port number for RS program argv[3] - ts_portno desired port number for TS program argv[4] - input_file_name (OPTIONAL) desired name of input file (queried_hostnames) argv[5] - output_file_name (OPTIONAL) desired name of output file Returns: Exit status, by default, 0 upon exit Raises: (none) """ arg_length = len(argv) usage_str = '\nUSAGE:\npython {} [rs_hostname] [rs_listen_port] [ts_listen_port]\npython {} [rs_hostname] [rs_listen_port] [ts_listen_port] [input_file_name]\npython {} [rs_hostname] [rs_listen_port] [ts_listen_port] [input_file_name] [output_file_name]\n'.format( argv[0], argv[0], argv[0]) rs_hostname = '' rs_portno = 0 ts_portno = 0 input_file_str = DEFAULT_INPUT_FILE_STR_HNS output_file_str = DEFAULT_OUTPUT_FILE_STR_RESOLVED hostname_list = [] resolved_list = [] if arg_length is 4: rs_hostname = argv[1] rs_portno = int(argv[2]) ts_portno = int(argv[3]) elif arg_length is 5: rs_hostname = argv[1] rs_portno = int(argv[2]) ts_portno = int(argv[3]) input_file_str = argv[4] elif arg_length is 6: rs_hostname = argv[1] rs_portno = int(argv[2]) ts_portno = int(argv[3]) input_file_str = argv[4] output_file_str = argv[5] else: print(usage_str) exit() print('') hostname_list = file_to_list(input_file_str) if len(hostname_list) > 0: resolved_list = query_servers(rs_hostname, rs_portno, hostname_list, ts_portno) if len(resolved_list) > 0: write_to_file_from_list(output_file_str, resolved_list, 'w') print('') return EX_OK
if reply: print("[{0}] Reading (Late): {1} ({2}): {3}".format( time.strftime("%Y-%m-%d %H:%M"), status.user.screen_name, status.user.id, status.text)) tweet_command(_API, status, tweet, command) TWEETS_READ.append(str(status.id)) with open(os.path.join(settings['ignore_loc'], "tweets_read.txt"), 'w') as file: file.write("\n".join(TWEETS_READ)) print("[INFO] Finished reading late tweets!") if __name__ == '__main__': BLOCKED_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Users.txt")) PATREON_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "patreon_users.txt")) IGNORE_WORDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Words.txt")) LIMITED = False HAD_ERROR = False LAST_STATUS_CODE = 0 TWEETS_READ = [] MOD_IDS = ["2780494890", "121144139"] RATE_LIMIT_DICT = {} USER_LAST_COMMAND = OrderedDict() START_TIME = time.time()
"Airing"] # Commands that will be added later. LATER_DISCORD_CMDS = ["WaifuRemove", "HusbandoRemove"] RATE_LIMIT_DICT = {} CHANNEL_TIMEOUT = {} USER_LAST_COMMAND = OrderedDict() # TODO: Add AceAnimatedBot when i make it work on my rss site BOT_ACCS = ["AcePictureBot", "AceEcchiBot", "AceYuriBot", "AceYaoiBot", "AceNSFWBot", "AceCatgirlBot", "AceAsianBot", "AceYuriNSFWBot", "AceWallpaperBot", "AceStatusBot"] BOT_ACCS = [x.lower() for x in BOT_ACCS] BOT_ACCS_STR = ["!apb " + x for x in BOT_ACCS] # List of bot accs BLOCKED_IDS = file_to_list( os.path.join(os.path.dirname(os.path.realpath(__file__)), "bot_ids.txt")) MOD_IDS = ["81515803085639680"] PATREON_IDS = file_to_list( os.path.join(settings['list_loc'], "Patreon Users.txt")) def is_patreon(twitter_id): return [True if twitter_id in PATREON_IDS else False][0] def get_twitter_id(discord_id): acc_list = open(discord_settings['acc_file'], 'r').read().splitlines() for acc in acc_list:
most_common_chars = _get_most_common_char(search_most_common) most_common_chars[4] = new_number_alignments[8][4] most_common_chars[6] = new_number_alignments[8][6] print(most_common_chars) for num in NUMBERS_ALIGNMENT.keys(): if num != 8 and num in new_number_alignments.keys(): alignment = get_serialized_alignment(new_number_alignments, num) alignment1 = get_serialized1_alignment(new_number_alignments, num) else: most_common_chars = NUMBERS_ALIGNMENT[num] alignment = get_serialized_alignment(NUMBERS_ALIGNMENT, num) alignment1 = get_serialized1_alignment(NUMBERS_ALIGNMENT, num) #print(num, alignment1, len(alignment)) #print(new_number_alignments, end="\n\n") print() return #new_number_alignments if __name__ == '__main__': lines = file_to_list('day08.txt', test=True) lines = get_deserialized_lines(lines) result1 = part2(lines) print("Day 8, part 1:", result1) #result2 = part2(lines) #print("Day 8, part 2:", result2)
current = preamble_slice_high preamble = lines[preamble_slice_low:preamble_slice_high] preamble_sums = get_preamble_sums(preamble) if lines[current] not in preamble_sums: return current, lines[current] return None def part2(result1, lines): position, value = result1 lines = lines[:position] for i in range(len(lines)): for j in range(i + 2, len(lines) + 1): suma = sum(lines[i:j]) if suma > value: break if suma == value: return min(lines[i:j]), max(lines[i:j]) if __name__ == '__main__': lines = file_to_list("day09.txt", test=False, cast=int) result1 = part1(lines) print("Day 9, part 1:", result1[1]) result2 = part2(result1, lines) print("Day 9, part 2:", sum(result2))
"'%key' are missing from the following config, please" + " fix it:", "config_upgraded": "Your config file has been updated to include the" + " following new fields:", "path_missing": "The following path could not be found:", "path_exists": "The following path already exists:", "path_unmakable": "The following error occurred when trying to " + "create this path:", "url_unreachable": "The following url was unreachable:", "yaml_error": "%file contains 1 or more syntax errors:", "template_error": "Your template(s) contain 1 or more syntax errors:", "template_extender_missing": "The following template could not be found:", "png_missing_out": "You must supply -o <file> to write the png file", "dot_missing": "To export a PNG graph you must install graphviz", "run_success": "%role_count roles were modified with this shell command:", "run_error": "There was an error running this shell command:", "help_config": "create a necessary config file to make ansigenome work", "help_scan": "scan a path containing Ansible roles and report back " + "useful stats", "help_gendoc": "generate a README from the meta file for each role", "help_genmeta": "augment existing meta files to be compatible with" + " Ansigenome", "help_export": "export roles to a dependency graph, requirements file" + " and more", "help_init": "init new roles with a custom meta file and tests", "help_run": "run shell commands inside of each role's directory", } TEST_PATH = os.path.join(os.path.sep, "tmp", "ansigenome") X11_COLORS = utils.file_to_list(os.path.join(PACKAGE_RESOURCE, "colors"))
def tweet_command(_API, status, tweet, command): tweet_image = False user = status.user # Mod command is_mod = [True if str(user.id) in MOD_IDS else False][0] if command == "DelLimits": if is_mod: their_id, cmd = tweet.split(' ', 2) remove_all_limit(their_id, cmd) print("[INFO] Removed limits for {0} - {1}".format( their_id, cmd)) return False, False if str(user.id) not in PATREON_IDS: if not is_mod: user_is_limited = user_spam_check(user.id, user.screen_name, command) if isinstance(user_is_limited, str): # User hit limit, tweet warning command = "" tweet = user_is_limited elif not user_is_limited: # User is limited, return print("[{0}] User is limited! Ignoring...".format( time.strftime("%Y-%m-%d %H:%M"))) return False if settings['count_on']: func.count_trigger(command, user.id) if command == "DiscordConnect": tweet = func.DiscordConnect(tweet, user.id) if command == "DiscordJoin": tweet = re.sub('http\S+', '', tweet).strip() for url in status.entities['urls']: tweet += "" + url['expanded_url'] break tweet = func.DiscordJoin(tweet) # Joke Commands if command == "spook": tweet, tweet_image = func.spookjoke() if command == "Spoiler": tweet = random.choice(utils.file_to_list( os.path.join(settings['list_loc'], "spoilers.txt"))) elif command == "!Level": tweet = func.get_level(user.id) # Main Commands if command == "Waifu": tweet, tweet_image = func.waifu(0, tweet) elif command == "Husbando": tweet, tweet_image = func.waifu(1, tweet) gender = utils.gender(status.text) if gender == 0: g_str = "waifu" else: g_str = "husbando" if "Register" in command: follow_result = is_following(user.id) if follow_result == "Limited": tweet = ("The bot is currently limited on checking stuff.\n" "Try again in 15 minutes!") func.remove_one_limit(user.id, g_str.lower() + "register") elif follow_result == "Not Genuine": tweet = ("Your account wasn't found to be genuine.\n" "Help: {url}").format( url=func.config_get('Help URLs', 'not_genuine')) elif not follow_result: tweet = ("You must follow @AcePictureBot to register!\n" "Help: {url}").format( url=func.config_get('Help URLs', 'must_follow')) else: tweet, tweet_image = func.waifuregister(user.id, user.screen_name, tweet, gender) if "My" in command: skip_dups = False if "my{g_str}+".format(g_str=g_str) in tweet.lower(): skip_dups = True if "my{g_str}-".format(g_str=g_str) in tweet.lower(): func.delete_used_imgs(str(user.id), False) tweet, tweet_image = func.mywaifu(user.id, gender, False, skip_dups) if "Remove" in command: tweet = func.waifuremove(user.id, gender) if command == "OTP": tweet, tweet_image = func.otp(tweet) # TODO: Remove this over sometime and change kohai to kouhai on the site if command == "Kohai": command = "Kouhai" list_cmds = ["Shipgirl", "Touhou", "Vocaloid", "Imouto", "Idol", "Shota", "Onii", "Onee", "Sensei", "Monstergirl", "Witchgirl", "Tankgirl", "Senpai", "Kouhai"] if command in list_cmds: tweet, tweet_image = func.random_list(command, tweet) if command == "Airing": tweet = func.airing(tweet) # No results found. if not tweet: return False if command == "Source": tweet = func.source(_API, status) if tweet: tweet = "@{0} {1}".format(user.screen_name, tweet) post_tweet(_API, tweet, tweet_image, command, status)
def acceptable_tweet(status): global USER_LAST_COMMAND global IGNORE_WORDS global BLOCKED_IDS tweet = status.text user = status.user # Ignore ReTweets. if tweet.startswith('RT'): return False, False if DEBUG: if str(user.id) not in MOD_IDS: return False, False # Reload in case of manual updates. BLOCKED_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Users.txt")) PATREON_IDS = utils.file_to_list( os.path.join(settings['list_loc'], "patreon_users.txt")) IGNORE_WORDS = utils.file_to_list( os.path.join(settings['list_loc'], "Blocked Words.txt")) # Ignore bots and bad boys. if str(user.id) in BLOCKED_IDS: return False, False # Ignore some messages. if any(word.lower() in tweet.lower() for word in IGNORE_WORDS): return False, False # Make sure the message has @Bot in it. if not any("@" + a.lower() in tweet.lower() for a in settings['twitter_track']): return False, False # If the user @sauce_plz add "source" to the text if "sauce" in tweet.lower(): tweet += " source" # Remove extra spaces. tweet = re.sub(' +', ' ', tweet).lstrip() # Remove @UserNames (usernames could trigger commands alone) tweet = tweet.replace("🚢👧", "Shipgirl") tweet = ' '.join( re.sub('(^|\n| )(@[A-Za-z0-9_🚢👧.+-]+)', ' ', tweet).split()) tweet = tweet.replace("#", "") # Find the command they used. command = utils.get_command(tweet) if command == "WaifuRegister" or command == "HusbandoRegister" \ or command == "DiscordConnect": # Cut the text off after the command word. reg = "({0})(?i)".format(command) if len(tweet) > (len(command) + len(settings['twitter_track'][0]) + 2): tweet = re.split(reg, tweet)[2].lstrip() # No command is found see if acceptable for a random waifu. if not command: # Ignore quote ReTweets. if tweet.startswith('"@'): return False, False # Ignore if it doesn't mention the main bot only. if settings['twitter_track'][0] not in status.text: return False, False # Last case, check if they're not replying to a tweet. if status.in_reply_to_status_id is None: command = "Waifu" else: return False, False if command == "Reroll": try: command = utils.get_command(USER_LAST_COMMAND[user.id]) if "Register" in command: return False, False elif "My" in command: return False, False elif command is False: return False, False except (ValueError, KeyError): return False, False else: USER_LAST_COMMAND[user.id] = tweet if len(USER_LAST_COMMAND) > 30: USER_LAST_COMMAND = (OrderedDict( islice(USER_LAST_COMMAND.items(), 20, None))) # Stop someone limiting the bot on their own. rate_time = datetime.datetime.now() rate_limit_secs = 10800 rate_limit_user = 20 if str(user.id) in PATREON_IDS: # Still a limit just in case rate_limit_user = 35 if user.id in RATE_LIMIT_DICT: # User is now limited (3 hours). if ((rate_time - RATE_LIMIT_DICT[user.id][0]) .total_seconds() < rate_limit_secs)\ and (RATE_LIMIT_DICT[user.id][1] >= rate_limit_user): return False, False # User limit is over. elif ((rate_time - RATE_LIMIT_DICT[user.id][0]) .total_seconds() > rate_limit_secs): del RATE_LIMIT_DICT[user.id] else: # User found, not limited, add one to the trigger count. RATE_LIMIT_DICT[user.id][1] += 1 else: # User not found, add them to RATE_LIMIT_DICT. # Before that quickly go through RATE_LIMIT_DICT # and remove all the finished unused users. for person in list(RATE_LIMIT_DICT): if ((rate_time - RATE_LIMIT_DICT[person][0]) .total_seconds() > rate_limit_secs): del RATE_LIMIT_DICT[person] RATE_LIMIT_DICT[user.id] = [rate_time, 1] # This shouldn't happen but just in case. if not isinstance(command, str): return False, False tweet = tweet.lower().replace(command.lower(), " ", 1).strip() return tweet, command
def tweet_command(_API, status, tweet, command): tweet_image = False user = status.user # Mod command is_mod = [True if user.id in MOD_IDS else False][0] if command == "DelLimits": if is_mod: their_id, cmd = tweet.split(' ', 2) remove_all_limit(their_id, cmd) print("[INFO] Removed limits for {0} - {1}".format(their_id, cmd)) return False, False if not is_mod: user_is_limited = user_spam_check(user.id, user.screen_name, command) if isinstance(user_is_limited, str): # User hit limit, tweet warning command = "" tweet = user_is_limited elif not user_is_limited: # User is limited, return print("[{0}] User is limited! Ignoring...".format( time.strftime("%Y-%m-%d %H:%M"))) return False if settings['count_on']: func.count_trigger(command, user.id) # Joke Commands if command == "spook": tweet, tweet_image = func.spookjoke() if command == "Spoiler": tweet = random.choice( utils.file_to_list( os.path.join(settings['list_loc'], "spoilers.txt"))) elif command == "!Level": tweet = func.get_level(user.id) # Main Commands if command == "Waifu": tweet, tweet_image = func.waifu(0, tweet) elif command == "Husbando": tweet, tweet_image = func.waifu(1, tweet) gender = utils.gender(status.text) if "Register" in command: follow_result = is_following(user.id) if follow_result == "Limited": tweet = ("The bot is currently limited on checking stuff.\n" "Try again in 15 minutes!") if gender == 0: gender = "waifu" else: gender = "husbando" func.remove_one_limit(user.id, gender.lower() + "register") elif follow_result == "Not Genuine": tweet = ("Your account wasn't found to be genuine.\n" "Help: {url}").format( url=func.config_get('Help URLs', 'not_genuine')) elif not follow_result: tweet = ("You must follow @AcePictureBot to register!\n" "Help: {url}").format( url=func.config_get('Help URLs', 'must_follow')) else: tweet, tweet_image = func.waifuregister(user.id, user.screen_name, tweet, gender) if "My" in command: tweet, tweet_image = func.mywaifu(user.id, gender) if "Remove" in command: tweet = func.waifuremove(user.id, gender) if command == "OTP": tweet, tweet_image = func.otp(tweet) # TODO: Remove this over sometime and change kohai to kouhai on the site if command == "Kohai": command = "Kouhai" list_cmds = [ "Shipgirl", "Touhou", "Vocaloid", "Imouto", "Idol", "Shota", "Onii", "Onee", "Sensei", "Monstergirl", "Witchgirl", "Tankgirl", "Senpai", "Kouhai" ] if command in list_cmds: tweet, tweet_image = func.random_list(command, tweet) if command == "Airing": tweet = func.airing(tweet) # No results found. if not tweet: return False if command == "Source": tweet = func.source(_API, status) if tweet: tweet = "@{0} {1}".format(user.screen_name, tweet) post_tweet(_API, tweet, tweet_image, command, status)
" fix it:", "config_upgraded": "Your config file has been updated to include the" + " following new fields:", "path_missing": "The following path could not be found:", "path_exists": "The following path already exists:", "path_unmakable": "The following error occurred when trying to " + "create this path:", "url_unreachable": "The following url was unreachable:", "yaml_error": "%file contains 1 or more syntax errors:", "template_error": "Your template(s) contain 1 or more syntax errors:", "template_extender_missing": "The following template could not be found:", "png_missing_out": "You must supply -o <file> to write the png file", "dot_missing": "To export a PNG graph you must install graphviz", "run_success": "%role_count roles were modified with this shell command:", "run_error": "There was an error running this shell command:", "help_config": "create a necessary config file to make ansigenome work", "help_scan": "scan a path containing Ansible roles and report back " + "useful stats", "help_gendoc": "generate a README from the meta file for each role", "help_genmeta": "augment existing meta files to be compatible with" + " Ansigenome", "help_export": "export roles to a dependency graph, requirements file" + " and more", "help_init": "init new roles with a custom meta file and tests", "help_run": "run shell commands inside of each role's directory", } TEST_PATH = os.path.join(os.path.sep, "tmp", "ansigenome") X11_COLORS = utils.file_to_list(os.path.join(PACKAGE_RESOURCE, "colors"))
def __init__(self, user_id, username, name, gender): self.user_id = user_id self.username = username self.org_name = name self.name = self.clean_name(name) self.subscribe = False self.disable = False self.override = False self.multinames = False self.noimages = False self.notenough = False self.offline = False self.soup = False if gender == 0: self.end_tags_main = "+solo" self.end_tags = "+-male+solo+-1boy+-genderswap" self.gender = "waifu" self.filename = "users_waifus.json" self.pic_limit = 30 elif gender == 1: self.end_tags_main = "+solo+-1girl+-female" self.end_tags = "+solo+-1girl+-female+-genderswap" self.gender = "husbando" self.filename = "users_husbandos.json" self.pic_limit = 25 blocked_waifus = file_to_list( os.path.join(settings['list_loc'], 'Blocked Waifus.txt')) self.disable = any([ True for i in blocked_waifus if i in self.name]) if self.disable: return None self.date = datetime.datetime.now().strftime("%Y-%m-%d") user_waifus_file = open( os.path.join(settings['list_loc'], self.filename), 'r', encoding='utf-8') self.user_waifus = json.load(user_waifus_file) user_waifus_file.close() count = 0 for a, datalist in self.user_waifus.items(): for datadict in datalist: if str(datadict["twitter_id"]) == str(self.user_id): try: self.subscribe = bool(datadict['wednesday']) except: self.subscribe = False datalist.pop(count) count += 1 for entry in self.user_waifus['users']: if self.name == entry['name']: self.override = True self.site_index = entry['web_index'] break self.known = [["anarchy_stocking", "stocking_(psg)"], ["hestia", "hestia_(danmachi!)"], ["zelda", "princess_zelda"], ["asuka", "asuka_langley"]] for [known, work] in self.known: if self.name == known or '_'.join(reversed(self.name.split("_"))) == known: self.name = work self.override = True break if self.override: return None
return get_solution(nums_subset, matrix) def part2(nums, matrices): min_subset_items = 5 nums_subset = nums[:min_subset_items] winners = [] winner = False while min_subset_items < len(nums): nums_subset.append(nums[min_subset_items]) for i, matrix in enumerate(matrices): winner = is_winner(nums_subset, matrix) if winner and i not in (item[0] for item in winners): winners.append((i, matrix, copy.deepcopy(nums_subset))) winner = False min_subset_items += 1 return get_solution(winners[-1][2], winners[-1][1]) if __name__ == '__main__': lines = file_to_list('day04.txt', test=False) nums, matrices = get_deserialized_lines(lines) result1 = part1(nums, matrices) print("Day 4, part 1:", result1) result2 = part2(nums, matrices) print("Day 4, part 2:", result2)
def get_deserialized_lines(lines): deserialized = {} for line in lines: key, value = line.split("-") if key not in deserialized.keys(): deserialized[key] = [] if value not in deserialized.keys(): deserialized[value] = [] if value != 'start': deserialized[key].append(value) if key != 'start': deserialized[value].append(key) #deserialized.pop('end') return deserialized def part2(lines): return if __name__ == '__main__': lines = file_to_list("day12.txt", test=True) lines = get_deserialized_lines(lines) result1 = part1(lines) print("Day 12, part 1:", result1) result2 = part2(lines) print("Day 12, part 2:", result2)
def tweet_command(API, status, message, command): tweet = False tweet_image = False user = status['user'] # Mod command is_mod = [True if user['id_str'] in MOD_IDS else False][0] is_patreon = [True if user['id_str'] in PATREON_IDS else False][0] if command == "DelLimits": if is_mod: their_id, cmd = message.split(' ', 2) remove_all_limit(their_id, cmd) print("[INFO] Removed limits for {0} - {1}".format( their_id, cmd)) return "Removed!", False if command == "AllowAcc": if is_mod: func.allow_user(message) print("[INFO] Allowing User {0} to register!".format(message)) ALLOWED_IDS.append(message) if not is_patreon and not is_mod: user_is_limited = user_spam_check(user['id_str'], user['screen_name'], command) if isinstance(user_is_limited, str): # User hit limit, tweet warning command = "" tweet = user_is_limited elif not user_is_limited: # User is limited, return print("[{0}] User is limited! Ignoring...".format( time.strftime("%Y-%m-%d %H:%M"))) return False if settings['count_on'] and command: func.count_command("Global", command, settings['count_file']) func.count_command("Commands", command, os.path.join(settings['user_count_loc'], user['id_str'])) if command == "PicTag": if is_mod or is_patreon: get_imgs = 1 try: count = int(re.search(r'\d+', message).group()) except (AttributeError): count = False if count: if count > 4: get_imgs = 4 elif count < 1: get_imgs = 1 else: get_imgs = count tweet, tweet_image = func.pictag(message.replace(str(count), ""), repeat_for=get_imgs) if command == "DiscordConnect": tweet = func.DiscordConnect(message, user['id_str']) if command == "DiscordJoin": tweet = ("Invite the bot by using this: " "https://discordapp.com/oauth2/authorize?" "&client_id=170367887393947648&scope=bot") # Joke Commands if command == "spook": tweet, tweet_image = func.spookjoke() if command == "Spoiler": tweet = random.choice(utils.file_to_list( os.path.join(settings['list_loc'], "spoilers.txt"))) elif command == "!Level": tweet = func.get_level(twitter_id=user['id_str']) # Main Commands if command == "Waifu": tweet, tweet_image = func.waifu(0, message, user_id=user['id_str']) elif command == "Husbando": tweet, tweet_image = func.waifu(1, message, user_id=user['id_str']) gender = utils.gender(status['text']) if gender == 0: g_str = "waifu" else: g_str = "husbando" if "Register" in command: is_allowed = [True if user['id_str'] in ALLOWED_IDS else False][0] if is_mod: is_allowed = True follow_result = is_following(user['id_str'], is_allowed) if follow_result == "Limited": tweet = ("The bot is currently limited on checking stuff.\n" "Try again in 15 minutes!") func.remove_one_limit(user['id_str'], g_str.lower() + "register") elif follow_result == "Not Genuine": tweet = ("Your account wasn't found to be genuine.\n" "Help: {url}").format( url=func.config_get('Help URLs', 'not_genuine')) elif not follow_result: tweet = ("You must follow @AcePictureBot to register!\n" "Help: {url}").format( url=func.config_get('Help URLs', 'must_follow')) else: tweet, tweet_image = func.waifuregister(user['id_str'], user['screen_name'], message, gender) if "My" in command: skip_dups = False get_imgs = 1 if "my{g_str}+".format(g_str=g_str) in message.lower(): skip_dups = True if "my{g_str}-".format(g_str=g_str) in message.lower(): func.delete_used_imgs(user['id_str'], False) if is_mod or is_patreon: try: count = int(re.search(r'\d+', message).group()) except (AttributeError): count = False if count: if count > 4: get_imgs = 4 elif count < 1: get_imgs = 1 else: get_imgs = count tweet, tweet_image = func.mywaifu(user['id_str'], gender, False, skip_dups, get_imgs) if "Remove" in command: tweet = func.waifuremove(user['id_str'], gender) if command == "OTP": tweet, tweet_image = func.otp(message) list_cmds = ["Shipgirl", "Touhou", "Vocaloid", "Imouto", "Idol", "Shota", "Onii", "Onee", "Sensei", "Monstergirl", "Witchgirl", "Tankgirl", "Senpai", "Kouhai", "Granblue"] if command in list_cmds: tweet, tweet_image = func.random_list(command, message) if command == "Airing": tweet = func.airing(message) # No results found. if not tweet: return False if command == "Source": tweet = func.source(API, status) if tweet or tweet_image: tweet = "@{0} {1}".format(user['screen_name'], tweet) post_tweet(API, tweet, tweet_image, command, status)
def find_options(current_jolt, jolts, options=[]): if len(jolts) == 1: return options for i, jolt in enumerate(jolts): if jolt - current_jolt <= 3: options.append() options += find_options(jolt, jolts[i + 1:], options) def part2(jolts): arrangements = list() initial_jolts = get_initial_jolts(jolts) for start, initial_jolt in initial_jolts: options = find_options(initial_jolt, jolts[start + 1:]) arrangements.append(options) return arrangements if __name__ == '__main__': lines = file_to_list("day10.txt", test=True, cast=int) lines = sorted(lines) part1(lines) result1 = len(DIFFERENCES[1]) * len(DIFFERENCES[3]) print("Day 10, part 1:", result1) result2 = part2(lines) print("Day 10, part 2:", result2)
def __init__(self, user_id, username, name, gender): self.user_id = user_id self.username = username self.org_name = name self.name = self.clean_name(name) self.subscribe = False self.disable = False self.override = False self.multinames = False self.noimages = False self.notenough = False self.offline = False self.soup = False if gender == 0: self.end_tags_main = "+solo" self.end_tags = "+-male+solo+-1boy+-genderswap" self.gender = "waifu" self.filename = "users_waifus.json" self.pic_limit = 30 elif gender == 1: self.end_tags_main = "+solo+-1girl+-female" self.end_tags = "+solo+-1girl+-female+-genderswap" self.gender = "husbando" self.filename = "users_husbandos.json" self.pic_limit = 25 blocked_waifus = file_to_list( os.path.join(settings['list_loc'], 'Blocked Waifus.txt')) self.disable = any([True for i in blocked_waifus if i in self.name]) if self.disable: return None self.date = datetime.datetime.now().strftime("%Y-%m-%d") user_waifus_file = open(os.path.join(settings['list_loc'], self.filename), 'r', encoding='utf-8') self.user_waifus = json.load(user_waifus_file) user_waifus_file.close() count = 0 for a, datalist in self.user_waifus.items(): for datadict in datalist: if str(datadict["twitter_id"]) == str(self.user_id): try: self.subscribe = bool(datadict['wednesday']) except: self.subscribe = False datalist.pop(count) count += 1 for entry in self.user_waifus['users']: if self.name == entry['name']: self.override = True self.site_index = entry['web_index'] break self.known = [["anarchy_stocking", "stocking_(psg)"], ["hestia", "hestia_(danmachi!)"], ["zelda", "princess_zelda"], ["asuka", "asuka_langley"]] for [known, work] in self.known: if self.name == known or '_'.join(reversed( self.name.split("_"))) == known: self.name = work self.override = True break if self.override: return None
def random_list(list_name, args="", DISCORD=False): gender = "waifu" hashtag = "" search_for = "" m = False lines = False show_series = False scrape_images = True if list_name == "Shipgirl": if "aoki" in args: lines = utils.file_to_list('Shipgirl Aoki.txt') elif "all" in args: if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl All OTP.txt') else: lines = utils.file_to_list('Shipgirl Aoki.txt') lines += utils.file_to_list('Shipgirl.txt') else: hashtag = "#Kancolle" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl OTP.txt') else: lines = utils.file_to_list('Shipgirl.txt') elif list_name == "Touhou": hashtag = "#Touhou" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Touhou OTP.txt') else: lines = utils.file_to_list('Touhou.txt') elif list_name == "Vocaloid": hashtag = "#Vocaloids" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Vocaloid OTP.txt') else: lines = utils.file_to_list('Vocaloid.txt') elif list_name == "Imouto": list_name = "Imouto" show_series = True lines = utils.file_to_list('Imouto.txt') elif list_name == "Idol": show_series = True if "love live" in args or "lovelive" in args: search_for = "Love Live!" hashtag = "#LoveLive" if "otp" in args: list_name = "Love Live! OTP" show_series = False lines = utils.file_to_list('Idol Love Live OTP.txt') elif "cinderella" in args or "cinderella" in args: search_for = "Idolmaster Cinderella Girls" hashtag = "#Idolmaster" elif "idolmaster" in args or "idolm@ster" in args: search_for = "Idolmaster" hashtag = "#Idolmaster" elif "akb0048" in args: search_for = "AKB0048" hashtag = "#akb0048" elif "wake" in args: search_for = "Wake Up Girls!" hashtag = "#WUG_JP" elif "aikatsu" in args: search_for = "Aikatsu!" hashtag = "#Aikatsu" if "male" in args: list_name = "Male Idol" lines = utils.file_to_list('Idol Males.txt') else: if not lines: lines = utils.file_to_list('Idol.txt') if search_for: temp_lines = [] for line in lines: if line[1] == search_for: temp_lines.append(line) lines = temp_lines del temp_lines elif list_name == "Shota": show_series = True gender = "husbando" lines = utils.file_to_list('Shota.txt') elif list_name == "Onii": list_name = "Onii-chan" show_series = True gender = "husbando" lines = utils.file_to_list('Onii-chan.txt') elif list_name == "Onee": list_name = "Onee-chan" show_series = True lines = utils.file_to_list('Onee-chan.txt') elif list_name == "Sensei": show_series = True if "female" in args: lines = utils.file_to_list('Sensei Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Sensei Male.txt') else: lines = utils.file_to_list('Sensei Male.txt') lines += utils.file_to_list('Sensei Female.txt') elif list_name == "Senpai": show_series = True if "female" in args: lines = utils.file_to_list('Senpai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Senpai Male.txt') else: lines = utils.file_to_list('Senpai Male.txt') lines += utils.file_to_list('Senpai Female.txt') elif list_name == "Kouhai": show_series = True if "female" in args: lines = utils.file_to_list('Kouhai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Kouhai Male.txt') else: lines = utils.file_to_list('Kouhai Male.txt') lines += utils.file_to_list('Kouhai Female.txt') elif list_name == "Monstergirl": show_series = True scrape_images = True lines = utils.file_to_list('Monstergirl.txt') elif list_name == "Witchgirl": hashtag = "#s_witch" show_series = False scrape_images = True lines = utils.file_to_list('Witchgirl.txt') elif list_name == "Tankgirl": hashtag = "#garupan" show_series = False scrape_images = True lines = utils.file_to_list('Tankgirl.txt') # Under heavy stuff random.choice can be very weak # so just a quick way to make sure it's 'random random' random.shuffle(lines) entry = random.choice(lines) if list_name.endswith("OTP"): names = entry.split("(x)") if list_name == "Touhou": tags = "{0}+{1}+2girls+yuri+touhou+-asai_genji+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) if "love live" in list_name.lower(): tags = "{0}+{1}+2girls+yuri+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) else: tags = "{0}+{1}+yuri+2girls+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) name = "{0}(x){1}".format(names[0], names[1]) else: if isinstance(entry, list): name = entry[0] show = entry[1] else: name = entry if scrape_images: tags = "{0}+solo".format(name.replace(" ", "_")) path_name = slugify(name, word_boundary=True, separator="_") path = "{0}/{1}".format(gender.lower(), path_name) tweet_image = utils.get_image(path) if scrape_images and not DISCORD or not tweet_image and not DISCORD: tweet_image_temp = utils.get_image_online(tags, 0, 1, "", path) if tweet_image_temp is not False: tweet_image = tweet_image_temp name = re.sub(r' \([^)]*\)', '', name) hashtag = "" # TODO: Temp (testing with twitter) if show_series: m = "Your {0} is {1} ({2}) {3}".format(list_name, name, show, hashtag) elif list_name.endswith("OTP"): name_one = re.sub(r' \([^)]*\)', '', names[0]) name_two = re.sub(r' \([^)]*\)', '', names[1]) name = "{0} x {1}".format(name_one, name_two) if not m: m = "Your {0} is {1} {2}".format(list_name, name, hashtag) if not list_name.endswith("OTP"): count_trigger(name, gender) return m, tweet_image
def random_list(list_name, args="", DISCORD=False, user_id=False): gender = "waifu" hashtag = "" search_for = "" m = False lines = False end_tags = False show_series = False scrape_images = True message_layout = False if list_name == "Shipgirl": if "aoki" in args: lines = utils.file_to_list('Shipgirl Aoki.txt') elif "all" in args: if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl All OTP.txt') else: lines = utils.file_to_list('Shipgirl Aoki.txt') lines += utils.file_to_list('Shipgirl.txt') else: hashtag = "#Kancolle" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl OTP.txt') else: lines = utils.file_to_list('Shipgirl.txt') elif list_name == "Touhou": hashtag = "#Touhou" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Touhou OTP.txt') else: lines = utils.file_to_list('Touhou.txt') elif list_name == "Vocaloid": hashtag = "#Vocaloids" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Vocaloid OTP.txt') else: lines = utils.file_to_list('Vocaloid.txt') elif list_name == "Imouto": list_name = "Imouto" show_series = True lines = utils.file_to_list('Imouto.txt') elif list_name == "Idol": show_series = True if "love live" in args or "lovelive" in args: search_for = "Love Live!" hashtag = "#LoveLive" if "otp" in args: list_name = "Love Live! OTP" show_series = False lines = utils.file_to_list('Idol Love Live OTP.txt') elif "cinderella" in args or "cinderella" in args: search_for = "Idolmaster Cinderella Girls" hashtag = "#Idolmaster" elif "idolmaster" in args or "idolm@ster" in args: search_for = "Idolmaster" hashtag = "#Idolmaster" elif "akb0048" in args: search_for = "AKB0048" hashtag = "#akb0048" elif "wake" in args: search_for = "Wake Up Girls!" hashtag = "#WUG_JP" elif "aikatsu" in args: search_for = "Aikatsu!" hashtag = "#Aikatsu" if "male" in args: list_name = "Male Idol" lines = utils.file_to_list('Idol Males.txt') else: if not lines: lines = utils.file_to_list('Idol.txt') if search_for: temp_lines = [] for line in lines: if line[1] == search_for: temp_lines.append(line) lines = temp_lines del temp_lines elif list_name == "Shota": show_series = True gender = "husbando" lines = utils.file_to_list('Shota.txt') elif list_name == "Onii": list_name = "Onii-chan" show_series = True gender = "husbando" lines = utils.file_to_list('Onii-chan.txt') elif list_name == "Onee": list_name = "Onee-chan" show_series = True lines = utils.file_to_list('Onee-chan.txt') elif list_name == "Sensei": show_series = True if "female" in args: lines = utils.file_to_list('Sensei Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Sensei Male.txt') else: if random.randint(0, 10) < 3: gender = "husbando" lines = utils.file_to_list('Sensei Male.txt') else: lines = utils.file_to_list('Sensei Female.txt') elif list_name == "Senpai": show_series = True if "female" in args: lines = utils.file_to_list('Senpai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Senpai Male.txt') else: if random.randint(0, 10) < 3: gender = "husbando" lines = utils.file_to_list('Senpai Male.txt') else: lines = utils.file_to_list('Senpai Female.txt') elif list_name == "Kouhai": show_series = True if "female" in args: lines = utils.file_to_list('Kouhai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Kouhai Male.txt') else: if random.randint(0, 10) < 3: gender = "husbando" lines = utils.file_to_list('Kouhai Male.txt') else: lines = utils.file_to_list('Kouhai Female.txt') elif list_name == "Monstergirl": show_series = True scrape_images = True lines = utils.file_to_list('Monstergirl.txt') elif list_name == "Witchgirl": hashtag = "#s_witch" show_series = False scrape_images = True lines = utils.file_to_list('Witchgirl.txt') elif list_name == "Tankgirl": hashtag = "#garupan" show_series = False scrape_images = True lines = utils.file_to_list('Tankgirl.txt') elif list_name == "Granblue": hashtag = "" show_series = False scrape_images = True lines = utils.file_to_list('Granblue.txt') message_layout = "{name} has joined your party!" end_tags = "+granblue_fantasy" # Under heavy stuff random.choice can be very weak # so just a quick way to make sure it's 'random random' random.shuffle(lines) entry = random.choice(lines) if list_name.endswith("OTP"): names = entry.split("(x)") if list_name == "Touhou": tags = "{0}+{1}+2girls+yuri+touhou+-asai_genji+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) if "love live" in list_name.lower(): tags = "{0}+{1}+2girls+yuri+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) else: tags = "{0}+{1}+yuri+2girls+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) name = "{0}(x){1}".format(names[0], names[1]) else: if isinstance(entry, list): name = entry[0] show = entry[1] else: name = entry if scrape_images: tags = "{0}+solo+-genderswap".format(name.replace(" ", "_")) path_name = slugify(name, word_boundary=True, separator="_") path = "{0}/{1}".format(gender.lower(), path_name) tweet_image = utils.get_image(path) if end_tags: tags = tags + end_tags if scrape_images and not DISCORD or not tweet_image and not DISCORD: tweet_image_temp = utils.get_image_online(tags, 0, 1, "", path) if tweet_image_temp is not False: tweet_image = tweet_image_temp name = re.sub(r' \([^)]*\)', '', name) hashtag = "" # TODO: Temp (testing with twitter) if show_series: m = "Your {0} is {1} ({2}) {3}".format(list_name, name, show, hashtag) elif list_name.endswith("OTP"): name_one = re.sub(r' \([^)]*\)', '', names[0]) name_two = re.sub(r' \([^)]*\)', '', names[1]) name = "{0} x {1}".format(name_one, name_two) if not m: if message_layout: m = message_layout.format(name=name) else: m = "Your {0} is {1} {2}".format(list_name, name, hashtag) if not list_name.endswith("OTP"): if user_id: if show_series: st = "{} ({})".format(list_name, name, show) else: st = "{}".format(name) count_command(list_name, st, os.path.join(settings['user_count_loc'], user_id)) count_command(list_name, name, settings['count_file']) return m, tweet_image
# Commands that will be added later. LATER_DISCORD_CMDS = ["WaifuRemove", "HusbandoRemove"] RATE_LIMIT_DICT = {} CHANNEL_TIMEOUT = {} USER_LAST_COMMAND = OrderedDict() # TODO: Add AceAnimatedBot when i make it work on my rss site BOT_ACCS = [ "AcePictureBot", "AceEcchiBot", "AceYuriBot", "AceYaoiBot", "AceNSFWBot", "AceCatgirlBot", "AceAsianBot", "AceYuriNSFWBot", "AceWallpaperBot", "AceStatusBot" ] BOT_ACCS = [x.lower() for x in BOT_ACCS] BOT_ACCS_STR = ["!apb " + x for x in BOT_ACCS] # List of bot accs BLOCKED_IDS = file_to_list( os.path.join(os.path.dirname(os.path.realpath(__file__)), "bot_ids.txt")) MOD_IDS = ["81515803085639680"] PATREON_IDS = file_to_list( os.path.join(settings['list_loc'], "Patreon Users.txt")) def is_patreon(twitter_id): return [True if twitter_id in PATREON_IDS else False][0] def get_twitter_id(discord_id): acc_list = open(discord_settings['acc_file'], 'r').read().splitlines() for acc in acc_list: # acc[0] Twitter | acc[1] Discord ID
def random_list(list_name, args=""): gender = "waifu" hashtag = "" search_for = "" m = False lines = False show_series = False scrape_images = True if list_name == "Shipgirl": if "aoki" in args: lines = utils.file_to_list('Shipgirl Aoki.txt') elif "all" in args: if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl All OTP.txt') else: lines = utils.file_to_list('Shipgirl Aoki.txt') lines += utils.file_to_list('Shipgirl.txt') else: hashtag = "#Kancolle" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Shipgirl OTP.txt') else: lines = utils.file_to_list('Shipgirl.txt') elif list_name == "Touhou": hashtag = "#Touhou" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Touhou OTP.txt') else: lines = utils.file_to_list('Touhou.txt') elif list_name == "Vocaloid": hashtag = "#Vocaloids" if "otp" in args: list_name += " OTP" lines = utils.file_to_list('Vocaloid OTP.txt') else: lines = utils.file_to_list('Vocaloid.txt') elif list_name == "Imouto": list_name = "Imouto" show_series = True lines = utils.file_to_list('Imouto.txt') elif list_name == "Idol": show_series = True if "love live" in args or "lovelive" in args: search_for = "Love Live!" hashtag = "#LoveLive" if "otp" in args: list_name = "Love Live! OTP" show_series = False lines = utils.file_to_list('Idol Love Live OTP.txt') elif "cinderella" in args or "cinderella" in args: search_for = "Idolmaster Cinderella Girls" hashtag = "#Idolmaster" elif "idolmaster" in args or "idolm@ster" in args: search_for = "Idolmaster" hashtag = "#Idolmaster" elif "akb0048" in args: search_for = "AKB0048" hashtag = "#akb0048" elif "wake" in args: search_for = "Wake Up Girls!" hashtag = "#WUG_JP" elif "aikatsu" in args: search_for = "Aikatsu!" hashtag = "#Aikatsu" if "male" in args: list_name = "Male Idol" lines = utils.file_to_list('Idol Males.txt') else: if not lines: lines = utils.file_to_list('Idol.txt') if search_for: temp_lines = [] for line in lines: if line[1] == search_for: temp_lines.append(line) lines = temp_lines del temp_lines elif list_name == "Shota": show_series = True gender = "husbando" lines = utils.file_to_list('Shota.txt') elif list_name == "Onii": list_name = "Onii-chan" show_series = True gender = "husbando" lines = utils.file_to_list('Onii-chan.txt') elif list_name == "Onee": list_name = "Onee-chan" show_series = True lines = utils.file_to_list('Onee-chan.txt') elif list_name == "Sensei": show_series = True if "female" in args: lines = utils.file_to_list('Sensei Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Sensei Male.txt') else: lines = utils.file_to_list('Sensei Male.txt') lines += utils.file_to_list('Sensei Female.txt') elif list_name == "Senpai": show_series = True if "female" in args: lines = utils.file_to_list('Senpai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Senpai Male.txt') else: lines = utils.file_to_list('Senpai Male.txt') lines += utils.file_to_list('Senpai Female.txt') elif list_name == "Kouhai": show_series = True if "female" in args: lines = utils.file_to_list('Kouhai Female.txt') elif "male" in args: gender = "husbando" lines = utils.file_to_list('Kouhai Male.txt') else: lines = utils.file_to_list('Kouhai Male.txt') lines += utils.file_to_list('Kouhai Female.txt') elif list_name == "Monstergirl": show_series = True scrape_images = True lines = utils.file_to_list('Monstergirl.txt') elif list_name == "Witchgirl": hashtag = "#s_witch" show_series = False scrape_images = True lines = utils.file_to_list('Witchgirl.txt') elif list_name == "Tankgirl": hashtag = "#garupan" show_series = False scrape_images = True lines = utils.file_to_list('Tankgirl.txt') # Under heavy stuff random.choice can be very weak # so just a quick way to make sure it's 'random random' random.shuffle(lines) entry = random.choice(lines) if list_name.endswith("OTP"): names = entry.split("(x)") if list_name == "Touhou": tags = "{0}+{1}+2girls+yuri+touhou+-asai_genji+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) if "love live" in list_name.lower(): tags = "{0}+{1}+2girls+yuri+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) else: tags = "{0}+{1}+yuri+2girls+-comic".format( names[0].replace(" ", "_"), names[1].replace(" ", "_")) name = "{0}(x){1}".format(names[0], names[1]) else: if isinstance(entry, list): name = entry[0] show = entry[1] else: name = entry if scrape_images: tags = "{0}+solo".format(name.replace(" ", "_")) path_name = slugify(name, word_boundary=True, separator="_") path = "{0}/{1}".format(gender.lower(), path_name) tweet_image = utils.get_image(path) if scrape_images and not tweet_image: tweet_image = utils.get_image_online(tags, 0, 1, "", path) name = re.sub(r' \([^)]*\)', '', name) if show_series: m = "Your {0} is {1} ({2}) {3}".format(list_name, name, show, hashtag) elif list_name.endswith("OTP"): name_one = re.sub(r' \([^)]*\)', '', names[0]) name_two = re.sub(r' \([^)]*\)', '', names[1]) name = "{0} x {1}".format(name_one, name_two) if not m: m = "Your {0} is {1} {2}".format(list_name, name, hashtag) if not list_name.endswith("OTP"): count_trigger(name, gender) return m, tweet_image