def tweet_setlist(): tmp = authorize_new_twit('text/twitter') # 140 character limit with 5 character (X/Y) taken into account setlist = filehandle.get_list('text/setlist') gig = filehandle.get_list('text/gig')[0] tweets = [] msg = '%s: %s' % (gig, setlist.pop(0)) while len(setlist) > 0: # Message length, (X/Y), and space in between if (len(msg) + len(setlist[0]) + 2) >= 135: tweets.append(msg) msg = '' if msg == '': msg = setlist.pop(0) else: msg = '%s, %s' % (msg, setlist.pop(0)) tweets.append(msg) for i, status in enumerate(tweets): tmp.update_status('%s (%d/%d)' % (status, i + 1, len(tweets)))
def generate(irc): try: openers = get_list('text/opener') songs = get_list('text/songs') piano = get_list('text/piano') setclosers = get_list('text/setcloser') gigclosers = get_list('text/gigcloser') except IOError as e: print(e) randomset = { 'main': [], 'encore1': [], 'encore2': [] } encorecount = random.randint(0, 1) construct_main_set(randomset, openers, songs, piano, setclosers) irc.msg(create_set_string(randomset['main'])) if encorecount == 0: construct_single_encore(randomset, openers, songs, gigclosers) irc.msg("ENCORE: " + create_set_string(randomset['encore1'])) else: construct_double_encore(randomset, openers, songs, setclosers, gigclosers) irc.msg("ENCORE 1: " + create_set_string(randomset['encore1'])) irc.msg("ENCORE 2: " + create_set_string(randomset['encore2']))
def last_played(irc, args): total_search = True opts = get_long_opts(args) song = txtfunctions.acronym_replace(' '.join(opts['other'])) if ((opts['range'] != None and opts['range'] != [-1,-1]) or opts['country'] != None or opts['tour'] != None): total_search = False if song.lower() in [s.lower() for s in filehandle.get_list('text/setlist')]: gig = filehandle.get_list('text/gig') if date_in_range(gig, opts['range']): irc.msg ('%s was last played at: %s' % (song, gig[0])) return if total_search: database = filehandle.get_list('text/archive.db') for entry in database: if entry.startswith('lp!'): db_song = entry.split('!')[1].split('::')[0] if song.lower() == db_song: db_file = entry.split('!')[1].split('::')[1] setlist = filehandle.get_list(db_file) irc.msg('%s was last played at: %s' % (song, setlist[0])) return tours = sorted(os.listdir('GigArchive')) for tour in reversed(tours): if opts['tour'] is not None: if opts['tour'] != tour_name(tour): continue gigs = sorted(os.listdir('GigArchive/%s' % tour)) for filename in reversed(gigs): if (not date_in_range(filename, opts['range']) or (opts['country'] is not None and opts['country'] != country_code(filename))): continue gig_file = 'GigArchive/%s/%s' % (tour, filename) setlist = filehandle.get_list(gig_file) if song.lower() in [s.lower() for s in setlist]: irc.msg('%s was last played at: %s' % (song, setlist[0])) if total_search: if len(database) >= 100: database.pop(0) database.append('lp!%s::%s' % (song.lower(), gig_file)) filehandle.put_list('text/archive.db', database) return irc.msg('I do not seem to have information on that song for the given options.')
def authorize_new_twit(filename): print("Authorizing twitter account from file.") CONSUMER_KEY = '' CONSUMER_KEY_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' text = filehandle.get_list(filename) for line in text: splitLine = line.split('=') if len(splitLine) < 2: continue arg = splitLine[0].strip() value = splitLine[1].strip() if arg == "CONSUMER_KEY": CONSUMER_KEY = value elif arg == "CONSUMER_KEY_SECRET": CONSUMER_KEY_SECRET = value elif arg == "ACCESS_TOKEN": ACCESS_TOKEN = value elif arg == "ACCESS_TOKEN_SECRET": ACCESS_TOKEN_SECRET = value auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_KEY_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) twit = tweepy.API(auth) return twit
def song_count(irc, args): total_search = True opts = get_long_opts(args) if ((opts['range'] != None and opts['range'] != [-1,-1]) or opts['country'] != None or opts['tour'] != None): total_search = False song = txtfunctions.acronym_replace(' '.join(opts['other'])) database = filehandle.get_list('text/archive.db') if total_search: for entry in database: if entry.startswith('c!'): db_song = entry.split('!')[1].split('=')[0] if db_song == song.lower(): count = int(entry.split('!')[1].split('=')[1]) irc.msg("%s has been played %d times." % (song, count)) return count = 0 tours = os.listdir('GigArchive') for tour in tours: if opts['tour'] == tour_name(tour): tours = [tour] break for tour in tours: gigs = os.listdir('GigArchive/%s' % tour) for filename in gigs: if not total_search: if (not date_in_range(filename, opts['range']) or (opts['country'] is not None and opts['country'] != country_code(filename))): continue setlist = filehandle.get_list('GigArchive/%s/%s' % (tour, filename)) if song.lower() in [s.lower() for s in setlist]: count = count + 1 if total_search: if len(database) >= 100: database.pop(0) database.append('c!%s=%d' % (song.lower(), count)) filehandle.put_list('text/archive.db', database) irc.msg("%s has been played %d times." % (song, count))
def print_set_by_date(irc, date): date = date.replace('/', '-') try: qyear = year_value(date) except ValueError: irc.msg('Error: Invalid date format.') return database = filehandle.get_list('text/archive.db') for entry in database: if '::' not in entry: continue db_date = entry.split('::')[0] if date == db_date: db_file = entry.split('::')[1].strip() setlist = filehandle.get_list(db_file) irc.msg(setlist[0] + ':') setprint = txtfunctions.create_set_string(setlist[1:]) irc.msg(setprint) return tours = sorted(os.listdir('GigArchive')) for tour in tours: if tour_in_range(tour, qyear): gigs = sorted(os.listdir('GigArchive/%s' % tour)) for gig in gigs: if gig_date(gig) == date: gig_file = 'GigArchive/%s/%s' % (tour, gig) try: setlist = filehandle.get_list(gig_file) except IOError: irc.msg('Error opening gig file.') return irc.msg(setlist[0] + ':') setprint = txtfunctions.create_set_string(setlist[1:]) irc.msg(setprint) if len(database) >= 100: database.pop(0) database.append('%s::%s' % (date, gig_file)) filehandle.put_list('text/archive.db', database) return irc.msg('Could not find the gig from that date.')
def random_game(filename): try: options = filehandle.get_list(filename) except IOError: raise IOError("Could not open file for random_game") randomResult = random.choice(options) randomResult = filehandle.remove_nr(randomResult) return randomResult
def random_phrase(): try: randomList = filehandle.get_list("text/botphrases") except IOError: raise IOError("Error opening file from random_phrase") phrase = random.choice(randomList) phrase = phrase.replace("%d", "%d" % random.randint(2, 20)) phrase = phrase.encode().decode("unicode_escape") return phrase
def print_recent_setlist(irc): tours = sorted(os.listdir('GigArchive')) tour = tours.pop() gigs = sorted(os.listdir('GigArchive/%s' % tour)) gig = gigs.pop() setlist = filehandle.get_list('GigArchive/%s/%s' % (tour, gig)) irc.msg('%s:' % setlist[0]) setprint = txtfunctions.create_set_string(setlist[1:]) irc.msg(setprint)
def manson_game(nick): try: mansonList = filehandle.get_list('text/manson') except IOError: raise IOError("Could not open file for manson_game") nickExists = False mansonRand = random.randint(1,10) # True/False, whether or not Mansons will be added or removed mansonAddDec = random.randint(0,1) for entry in mansonList: currentNick = entry.split(':')[0] if nick == currentNick: try: nickPosition = mansonList.index(entry) except: raise IndexError("Error getting index from manson list") nickExists = True if mansonAddDec == 0: mansonCount = 0 - mansonRand else: mansonCount = mansonRand if nickExists: value = mansonList[nickPosition].split(':')[1] value = int(value) mansonCount = value + mansonCount mansonList[nickPosition] = "%s:%d" % (nick, mansonCount) else: try: mansonList.append("%s:%d" % (nick, mansonCount)) except: raise IndexError("Error appending new manson entry") mansonList = sorted(mansonList, key=str.lower) try: filehandle.put_list('text/manson', mansonList) except IOError: raise IOError("Error writing manson list") if mansonAddDec == 0: return ("%s lost %d Mansons. Your total number of Mansons is now %d" % (nick, mansonRand, mansonCount)) elif mansonAddDec == 1: return ("%s gained %d Mansons. Your total number of Mansons is now %d" % (nick, mansonRand, mansonCount))
def refresh(): global INDEX global UNDOLIST UNDOLIST = [] try: setlist = filehandle.get_list(SETFILE) except IOError as i: print(i) UNDOLIST.append(setlist) INDEX = 0
def delete_song(argument): compared = False deleteCount = 0 songs = argument.split(', ') songCount = len(songs) print('Deleting %d songs...' % (songCount)) try: setlist = filehandle.get_list('text/setlist') except IOError: raise IOError("Error getting set for delete_song") for song in songs: compared = False song = acronym_replace(song) sys.stdout.write('Comparing song: %s' % (song)) try: songIndex = setlist.index(song) compared = True except: None if compared: try: setlist.remove(song) deleteCount = deleteCount + 1 except: print("Error deleting song") sys.stdout.write('\tDELETED') print('\n') print('Deleted %d/%d songs' % (deleteCount, songCount)) try: filehandle.put_list('text/setlist', setlist) except IOError: raise IOError("Error writing set for delete_song") if (deleteCount == 0): outputMsg = 'Could not delete any songs.' else: outputMsg = 'Deleted %d out of %d songs.' % (deleteCount, songCount) return outputMsg
def find_setlist(irc, args): strict = False if '--strict' in shlex.split(args): strict = True opts = get_long_opts(args) queries = [q.lower() for q in opts['other']] found = {} tours = os.listdir('GigArchive') for tour in tours: if opts['tour'] == tour_name(tour): tours = [tour] break for tour in tours: gigs = os.listdir('GigArchive/%s' % tour) for filename in gigs: if (not date_in_range(filename, opts['range']) or (opts['country'] is not None and opts['country'] != country_code(filename))): continue setlist = filehandle.get_list('GigArchive/%s/%s' % (tour, filename)) set_lower = [s.lower() for s in setlist] ckey = filename.split()[0] found[ckey] = 0 for q in queries: if filename.lower().find(q) != -1: found[ckey] += 1 if q in set_lower: found[ckey] += 1 if found[ckey] == 0: del found[ckey] elif found[ckey] != len(queries) and strict: del found[ckey] if len(found) == 0: irc.msg("No gigs found for given query.") else: sorted_found = sorted(found, key=found.get, reverse=True) output = "\"%s\"" % sorted_found[0] for gig in sorted_found[1:]: if len(output) + len(gig) + 2 > 400: break output = "%s, \"%s\"" % (output, gig) irc.msg("Possible setlists: %s" % output)
def song_pop(): try: undoList = filehandle.get_list('text/setlist') except IOError: raise IOError("Error opening file for song_undo") if len(undoList) != 0: del undoList[len(undoList) - 1] else: raise IndexError("Empty setlist") try: filehandle.put_list('text/setlist', undoList) except IOError: raise IOError("Error rewriting list for song_undo") return
def add(): global INDEX global UNDOLIST try: setlist = filehandle.get_list(SETFILE) except IOError as i: print(i) if INDEX == len(UNDOLIST) - 1: UNDOLIST.append(setlist) elif INDEX < len(UNDOLIST) - 1: UNDOLIST[INDEX + 1] = setlist UNDOLIST = UNDOLIST[0:INDEX + 2] INDEX += 1
def url_shorten(url): # API change, need to fix return url f = filehandle.get_list("text/urlkey") if len(f) > 0: key = f[0].strip() else: return "" request_url = "%s?key=%s?url=%s" % (waaiURL, key, url) r = requests.get("%s" % request_url) data = r.json() if data["success"] == False: return url return data["data"]["url"]
def print_set(filename): try: fileList = filehandle.get_list(filename) except IOError: raise IOError("Error opening file to print") fileLength = len(fileList) if fileLength == 0: print('EMPTY SETLIST') return '' else: if filename == 'text/previous': print('Printing PREVIOUS') return "%s: %s" % (filehandle.remove_nr(fileList[0]), create_set_string(fileList[1:])) else: print('Printing set') return create_set_string(fileList)
def replace_song(argument): compared = False songs = argument.split(', ') length = len(songs) if length != 2: print("Invalid replacement arguments") outputMsg = "ERROR: Invalid number of arguments." return outputMsg else: try: setlist = filehandle.get_list('text/setlist') except IOError: raise IOError("Error getting setlist for replace_song") compareSong = songs[0] compareSong = acronym_replace(compareSong) replaceSong = songs[1] replaceSong = acronym_replace(replaceSong) sys.stdout.write('Replacing %s with %s' % (compareSong, replaceSong)) try: songIndex = setlist.index(compareSong) setlist[songIndex] = replaceSong compared = True except: print('Replace Error: Song not found') outputMsg = "ERROR: Could not find the song to replace." return outputMsg if compared: try: filehandle.put_list('text/setlist', setlist) except IOError: raise IOError("Error writing set for replace_song") sys.stdout.write('\t[DONE]\n') outputMsg = "Song has been replaced" return outputMsg
def insert_song(argument): compared = False songs = argument.split(', ') length = len(songs) if length != 2: print("Invalid replacement arguments") return "ERROR: Invalid number of arguments." else: try: setlist = filehandle.get_list('text/setlist') except IOError: raise IOError("Error getting setlist for insert_song") insertSong = songs[0] insertSong = acronym_replace(insertSong) compareSong = songs[1] compareSong = acronym_replace(compareSong) sys.stdout.write('Inserting %s before %s' % (insertSong, compareSong)) try: songIndex = setlist.index(compareSong) setlist.insert(songIndex, insertSong) compared = True except: print('Compare Error: Song not found') return "ERROR: Could not find the song to insert before." if compared: try: filehandle.put_list('text/setlist', setlist) except IOError: raise IOError("Error writing set for insert_song") sys.stdout.write('\t[DONE]\n') outputMsg = ("Inserted %s before %s" % (insertSong, compareSong)) return outputMsg
def set_previous(): setlist = filehandle.get_list('text/setlist') gig = filehandle.get_list('text/gig') tour = filehandle.get_list('text/tour') print('GIG: %s' % (gig)) if len(gig) == 0: print('SetPrevious Error: GIG not found') outputString = 'ERROR: No gig set.' return outputString if len(setlist) == 0: print('SetPrevious Error: Empty setlist') outputString = 'ERROR: Setlist is empty.' return outputString gig = gig[0] tour = tour[0].strip() sys.stdout.write('FORMATTING GIG NAME...') try: gigParse = gig.split('/') if len(gigParse) > 1: i = 1 gigFileName = gigParse[0] while i < len(gigParse): gigFileName = '%s-%s' % (gigFileName, gigParse[i]) i += 1 else: gigFileName = gigParse[0] except: raise RuntimeError("Error formatting gig") sys.stdout.write('\t[DONE]\n') gigFileName = gigFileName.split('\x0A')[0] gigFileName = gigFileName.split('\r')[0] print('GIG FILE NAME: %s' % (gigFileName)) sys.stdout.write('Writing previous setlist...') archivePath = "GigArchive/" + tour + "/" + gigFileName gig = [gig] try: filehandle.put_list('text/previous', gig) filehandle.put_list(archivePath, gig) except IOError: raise IOError("Error writing setlists for set_previous") for entry in setlist: try: filehandle.list_append('text/previous', entry) filehandle.list_append(archivePath, entry) except IOError: raise IOError("Error appending song for set_previous") sys.stdout.write('\t[DONE]\nUpdating database...') database = filehandle.get_list('text/archive.db') for entry in database: if entry.startswith('c!'): song = entry.split('!')[1].split('=')[0] if song in [s.lower() for s in setlist]: count = int(entry.split('!')[1].split('=')[1]) count = count + 1 database[database.index(entry)] = 'c!%s=%d' % (song, count) elif entry.startswith('lp!'): song = entry.split('!')[1].split('::')[0] if song in [s.lower() for s in setlist]: database[database.index(entry)] = 'lp!%s::%s' % (song, archivePath) filehandle.put_list('text/archive.db', database) sys.stdout.write('\t[DONE]\nTweeting setlist...') twit.tweet_setlist() sys.stdout.write('\t[DONE]\n') outputString = "Current setlist copied over as previous set." return outputString
def command_run(text, irc, commands): if text.IRCcmd == "JOIN" and irc.joinmsg() and irc.isAwake(): if text.nick != irc.nick(): irc.msg("Welcome to the sexy plane %s. " "Enter !commands to view the bot functions." % text.nick) if text.nick in irc.modlist: if text.command in ("!wake\r\n", "!wake"): irc.wake() irc.resumeTimers() irc.msg("BellamyBot is online.") elif text.command in ("!sleep\r\n", "!sleep"): irc.sleep() irc.pauseTimers() irc.msg("Sleep mode activated") elif text.command == "!joinmsg": if text.argument in ("on\r\n", "on"): irc.activateJoinMsg() print("Join messages ON") elif text.argument in ("off\r\n", "off"): irc.deactivateJoinMsg() print("Join messages OFF") elif text.command == "!timers": if text.argument in ("on\r\n", "on"): irc.resumeTimers() elif text.argument in ("off\r\n", "off"): irc.pauseTimers() elif text.command == "!gamemode": if text.argument in ("on\r\n", "on"): irc.activateGames() print("Game mode ON") elif text.argument in ("off\r\n", "off"): irc.deactivateGames() print("Game mode OFF") elif text.command == "!setgig": try: filehandle.clear_file('text/gig') filehandle.list_append('text/gig', text.argument) except IOError as e: print(e) elif text.command == "!settour": try: filehandle.clear_file('text/tour') filehandle.list_append('text/tour', text.argument) except IOError as e: print(e) # Setlist controls elif text.command == "!add": txtfunctions.add_song(text.argument) undo.add() elif text.command == "!exp": original = filehandle.remove_nr(text.argument) check = txtfunctions.acronym_replace(text.argument) if check == original: irc.msg("There is no expansion for " + original) else: irc.msg(original + " expands to " + check) elif text.command in ("!clearset\r\n", "!clearset"): try: filehandle.clear_file('text/setlist') undo.refresh() except IOError as e: print(e) irc.msg("Current setlist has been cleared.") elif text.command in ("!pop\r\n", "!pop"): try: txtfunctions.song_pop() except IOError as e: print(e) return except IndexError as i: print(i) return undo.add() irc.msg("The last song has been erased") elif text.command == "!insert": try: response = txtfunctions.insert_song(text.argument) except IOError as e: print(e) return if response.find('ERROR') == -1: undo.add() irc.msg(response) elif text.command == "!replace": try: response = txtfunctions.replace_song(text.argument) except IOError as e: print(e) if response.find('ERROR') == -1: undo.add() irc.msg(response) elif text.command == "!delete": try: response = txtfunctions.delete_song(text.argument) except IOError as e: print(e) if response != 'Could not delete any songs.': undo.add() irc.msg(response) elif text.command in ("!setprevious\r\n", "!setprevious"): try: response = txtfunctions.set_previous() except IOError as e: print(e) except RuntimeError as r: print(r) irc.msg(response) elif text.command in ("!undo\r\n", "!undo"): if undo.undo(): irc.msg("Undid last change to setlist.") elif text.command in ("!redo\r\n", "!redo"): if undo.redo(): irc.msg("Redid last change to setlist.") elif text.command == "!cmd": cmd.function(irc, commands, text.argument) # All user commands if text.command in ("!bot\r\n", "!bot"): statePhrase = ("BellamyBot version %s created by Kueller917. Status: " % irc.version()) if irc.isAwake(): statePhrase = statePhrase + "ONLINE" else: statePhrase = statePhrase + "OFFLINE" irc.msg(statePhrase) elif text.command in ("!gig\r\n", "!gig"): try: gig = filehandle.get_list('text/gig') except IOError as e: print(e) irc.msg(gig[0]) elif text.command in ("!previous\r\n", "!previous"): gigarchive.print_recent_setlist(irc) elif text.command == "!message": try: filehandle.list_append('text/ircmsg', "%s: %s" % (text.nick, filehandle.remove_nr(text.argument))) except IOError as e: print(e) if len(irc.owners) > 0: irc.memo(irc.owners[0], "You have a message from %s" % text.nick) elif text.command in ("!source\r\n", "!source"): sourceMsg = ("Get your own copy of BellamyBot today! %s" % irc.source()) irc.msg(sourceMsg) # State dependent commands if irc.isAwake(): # General commands if text.command in ("!setlist\r\n", "!setlist"): setmsg = "CURRENT SETLIST: " try: currentset = txtfunctions.print_set('text/setlist') except IOError as e: print(e) if currentset == '': currentset = "...is empty" setmsg = setmsg + currentset irc.msg(setmsg) elif text.command == "!count": gigarchive.song_count(irc, text.argument) elif text.command == "!lastplayed": song = txtfunctions.acronym_replace(text.argument) gigarchive.last_played(irc, song) elif text.command == "!findset": gigarchive.find_setlist(irc, text.argument.strip()) elif text.command == "!loadset": date = text.argument.strip() setlist = gigarchive.print_set_by_date(irc, date) elif text.command == "!info": try: infolist = filehandle.get_list('text/info') except IOError: print('Error opening file info') return command = text.argument.strip() for line in infolist: if line.split(':')[0] == command: irc.msg(line.split(':')[1]) elif text.command == "!eval": ev = boteval.BotEval() ev.eval(irc, text.argument) elif text.command in ("!commands\r\n", "!commands"): irc.msg("Set commands: !gig, !setlist, !previous, !findset, " "!loadset, !count, !lastplayed.") irc.msg("Other: !bot, !source, !closer, !opener, !realfan, " "!roulette, !setfm, !ru-roulette, !setgen. Use !info " "for a description of any command.") elif text.command.strip() in commands: cmd.execute(irc, commands, text) if irc.gamesActive(): # Games if text.command in ("!closer\r\n", "!closer"): try: closer = musegames.random_game('text/gigcloser') except IOError as e: print(e) irc.msg("%s\'s gig has closed with %s!" % (text.nick, closer)) elif text.command in ("!opener\r\n", "!opener"): try: opener = musegames.random_game('text/opener') except IOError as e: print(e) irc.msg("%s\'s gig has opened with %s!" % (text.nick, opener)) elif text.command in ("!realfan\r\n", "!realfan"): if randint(0,1): irc.msg("%s is a REAL FAN. Good for you." % text.nick) else: irc.msg("%s is not a REAL FAN. Go away." % text.nick) elif text.command in ("!roulette\r\n", "!roulette"): output = musegames.T2L_roulette() if output != -1: irc.msg(output) else: irc.greenOn() irc.greenNick(text.nick) irc.msg("You landed on GREEN! Type !green to get your song") elif text.command in ("!green\r\n", "!green"): if irc.greenActive(): if irc.checkGreen(text.nick): irc.greenOff() irc.greenNick(None) irc.msg(musegames.roulette_green(text.nick)) else: irc.msg("You did not land on green.") elif text.command in ("!setfm\r\n", "!setfm"): setlist = setlistfm.get_setlist(irc.mbid()) for messagePart in setlist: irc.msg(messagePart) elif text.command in ("!manson\r\n", "!manson"): try: mansons = musegames.manson_game(text.nick) except IOError as e: print(e) except IndexError as i: print(i) irc.msg(mansons) elif text.command in ("!ru-roulette\r\n", "!ru-roulette"): timercommands.russian_roulette(irc, text.nick) elif text.command in ("!setgen\r\n", "!setgen"): setlistgenerator.generate(irc)