def allowgames(bot, cmd, room, msg, user): """Determines if a user is allowed to commence a chat game of any sort. Args: bot: Robot, connection between this funciton and the main program. cmd: str, the command the user is executing. msg: str, any message found after the command. user: user object. Returns: Reply object denoting the mesage to be returned and whether or not it the message should be sent in PMs or public chat. """ reply = r.ReplyObject(True) if not user.hasRank('#'): return reply.response( 'You do not have permission to change this. (Requires #)') if room.isPM: return reply.response("You can't use this command in a pm.") msg = bot.removeSpaces(msg) if msg in ['true', 'yes', 'y', 'True']: if room.allowGames: return reply.response( 'Chatgames are already allowed in this room.') room.allowGames = True return reply.response('Chatgames are now allowed in this room.') elif msg in ['false', 'no', 'n', ' False']: room.allowGames = False return reply.response('Chatgames are no longer allowed in this room.') return reply.response( '{param} is not a supported parameter'.format(param=msg))
def tell(bot, cmd, room, msg, user): reply = r.ReplyObject() notes = bot.usernotes if not msg: return reply.response('You need to specify a user and a ' 'message to send in the format: [user],' ' [message]') msg = msg.split(',') to = bot.toId(msg[0]) message = ','.join(msg[1:]).lstrip() if notes.alreadySentMessage(to, user.id): return reply.response('You already have a message to this' ' user waiting') if not message: return reply.response('You forgot a message') if len(message) > 150: return reply.response('Message is too long. Max limit is ' '150 characters') if len(to) >= 20: return reply.response("Username is too long. This user doesn't exist") notes.addMessage(to, user.name, message) reply.samePlace = True responseText = "I'll be sure to tell {user} that.".format(user=msg[0]) if to == user.id: responseText = "You sent yourself a message. Was this intended? It will work, but why?" return reply.response(responseText)
def leaveroom(bot, cmd, room, msg, user): reply = r.ReplyObject() msg = bot.removeSpaces(msg) if not msg: msg = room.title if bot.leaveRoom(msg): return reply.response('Leaving room {r} succeeded'.format(r=msg)) return reply.response('Could not leave room: {r}'.format(r=msg))
def untell(bot, cmd, room, msg, user): reply = r.ReplyObject() notes = bot.usernotes if not msg: return reply.response('You need to specify a user to remove') if not notes.hasMessage(msg): return reply.response('This user has no waiting messages') if not notes.removeMessage(msg, user.id): return reply.response('You have no message to this user waiting') return reply.response('Message removed')
def read(bot, cmd, room, msg, user): reply = r.ReplyObject() notes = bot.usernotes if not notes.hasMessage(user.id): return reply.response('You have no messages waiting') if not msg: # If the user didn't specify any amount to return, # give back a single message return reply.response(notes.getMessages(user.id, 1)) if not msg.isdigit() and int(msg) < 1: return reply.response('Please enter a positive integer') return reply.response(notes.getMessages(user.id, int(msg)))
def moderate(bot, cmd, room, msg, user): reply = r.ReplyObject('', True) if not msg: return reply.response( 'No parameters given. Command is ~moderate [room],True/False') if not user.hasRank('#'): return reply.response( 'You do not have permission to set this. (Requires #)') if not room.moderation.config['anything'] and not msg == 'anything': room.moderation.toggleRoomModeration() room.moderation.config[msg] = not room.moderation.config[msg] return reply.response( 'Moderation for {thing} is now turned {setting}'.format( thing=msg, setting='on' if room.moderation.config[msg] else 'off'))
def unbanthing(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, True) if not user.hasRank('#'): return reply.response( 'You do not have permission to do this. (Requires #)') if room.isPM: return reply.response("You can't unban things in PMs") error = room.moderation.removeBan(cmd[5:], msg) if not error: return reply.response(('Removed {thing} from the banlist {room}\n' '/modnote {user} removed {thing} from the' ' blacklist').format(thing=msg, room=room.title, user=user.name)) return reply.response(error)
def getranking(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, True) if not user.hasRank('%') and not room.isPM: reply.response( 'Listing the rankings require Room Driver (%) or higher.') # format is room (optional), format, user (if ever, also optional) with open('plugins/tournament-rankings.yaml', 'r+') as yf: yf.seek(0, 0) data = yaml.load(yf) parts = list(map(bot.toId, msg.split(','))) roomTitle = '' try: roomData = data[parts[0]] roomTitle = parts.pop(0) except KeyError: roomData = data[room.title] if room.title in data else None try: formatData = roomData[parts[0]] format = parts.pop(0) try: userData = formatData[parts[0]] return reply.response( '{user} has played {games} and won {wins} ({winrate:.1f}% win rate)' .format(use=parts[0], games=userData['entered'], wins=userData['won'], winrate=(userData['won'] / userData['entered']) * 100)) except IndexError: rankingsTable = Tournament.buildRankingsTable(formatData, format) if bot.canHtml(room): return reply.response('/addhtmlbox {}'.format(rankingsTable)) else: return reply.response('Cannot show full rankings in this room') except KeyError: return reply.response( '{user} has no data for {tier} in {room}'.format( user=parts[0], tier=format, room=roomTitle if roomTitle else room.title)) except TypeError: return reply.response('The room {} has no data about rankings'.format( msg.split(',')[0])) except IndexError: return reply.response('No format given') except KeyError: return reply.response( 'The room has no data about the format {}'.format(parts[0]))
def oldgentour(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, True) if not room.tour: return reply.response('No tour is currently active, so this command ' 'is disabled.') if not room.tour.format.startswith('gen'): return reply.response("The current tour isn't a previous generation, " "so this command is disabled.") pastGens = {'gen1': 'RBY', 'gen2': 'GSC', 'gen3': 'RSE', 'gen4': 'DPP'} warning = '' if room.tour.format[0:4] in pastGens: warning = "/wall Please note that bringing Pokemon that aren't **{gen} NU** will disqualify you\n".format( gen=pastGens[room.tour.format[0:4]]) return reply.response( warning + "/wall Sample teams here: http://www.smogon.com/forums/threads/3562659/" )
def handler(bot, cmd, room, msg, user): reply = r.ReplyObject('', True) if msg.startswith('new'): if not user.hasRank('@'): return reply.response("You don't have permission to start " "workshops (Requires @)") if room.activity: return reply.response('A room.activity is already in progress') host = bot.toId(msg[len('new '):]) if msg[len('new '):] else user.id room.activity = Workshop(host) return reply.response('A new workshop session was created') if not (room.activity and room.activity.isThisGame(Workshop)): return reply.response('No Workshop in progress right now') workshop = room.activity if msg.startswith('add'): if not workshop.hasHostingRights(user): return reply.response( 'Only the workshop host or a Room Moderator can add Pokemon') return reply.response(workshop.addPokemon(msg[4:].strip())) elif msg.startswith('remove'): if not workshop.hasHostingRights(user): return reply.response( 'Only the workshop host or a Room Moderator can remove Pokemon' ) return reply.response(workshop.removePokemon(msg[7:].strip())) elif msg == 'clear': if not workshop.hasHostingRights(user): return reply.response( 'Only the workshop host or a Room Moderator can clear the team' ) return reply.response(workshop.clearTeam()) elif msg == 'team': return reply.response(workshop.getTeam()) elif msg == 'end': if not workshop.hasHostingRights(user): return reply.response( 'Only the workshop host or a Room Moderator can end the workshop' ) bot.sendPm(user.id, workshop.pasteLog(room.title, bot.apikeys['pastebin'])) room.activity = None return reply.response('Workshop session ended') unreg_cmd = msg if msg else 'nothing' return reply.response('Unrecognized command: {cmd}'.format(unreg_cmd))
def start(bot, cmd, room, msg, user): global WHITELIST reply = r.ReplyObject('', True, False, True, True, False) if room.title == 'pm' and not cmd.startswith('score'): return reply.response("Don't try to play games in pm please") if msg == 'new': if not user.hasRank(WHITELIST_RANK) and user.id not in WHITELIST: return reply.response('You do not have permission to start a game in this room. (Requires {rank})'.format(rank=WHITELIST_RANK)) if room.activity: return reply.response('A game is already running somewhere') if not room.allowGames: return reply.response('This room does not support chatgames.') room.activity = Anagram() return reply.response('A new anagram has been created (guess with .a):\n' + room.activity.getWord()) elif msg == 'hint': if room.activity: return reply.response('The hint is: {hint}'.format(hint=room.activity.getHint())) return reply.response('There is no active anagram right now') elif msg == 'end': if not user.hasRank(WHITELIST_RANK) and user.id not in WHITELIST: return reply.response('You do not have permission to end the anagram. (Requires %)') if not (room.activity and room.activity.isThisGame(Anagram)): return reply.response('There is no active anagram or a different game is active.') solved = room.activity.getSolvedWord() room.activity = None return reply.response(('The anagram was forcefully ended by {baduser}. (Killjoy)\n' 'The solution was: **{solved}**').format(baduser=user.name, solved=solved)) elif msg.lower().startswith('score'): if msg.strip() == 'score': msg += ' {user}'.format(user=user.id) name = bot.toId(msg[len('score '):]) if name not in Scoreboard: return reply.response("This user never won any anagrams") return reply.response('This user has won {number} anagram(s)'.format(number=Scoreboard[name])) else: if msg: return reply.response(('{param} is not a valid parameter for .anagram.' ' Make guesses with .a').format(param=msg)) if room.activity and room.activity.isThisGame(Anagram): return reply.response('Current anagram: {word}'.format(word=room.activity.getWord())) return reply.response('There is no active anagram right now')
def banthing(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, True) if not user.hasRank('#'): return reply.response( 'You do not have permission to do this. (Requires #)') if room.isPM: return reply.response("You can't ban things in PMs") error = room.moderation.addBan(cmd[3:], msg) if not error: modnote = ('/modnote {user} added {thing} to the ' 'blacklist').format(thing=msg, user=user.name) ban = '' if msg in room.users: ban = '\n/roomban {user}, Was added to blacklist'.format(user=msg) return reply.response( 'Added {thing} to the banlist\n{note}{act}'.format(thing=msg, user=user.name, note=modnote, act=ban)) return reply.response(error)
def acceptTeam(self, cmd, room, msg, user): reply = r.ReplyObject('') meta, team = msg.split() if not team: return reply.response('You forgot a team') if not team.startswith('|'): return reply.response( "This team doesn't look like a valid packed team :(") if meta not in self.bh.teams: self.bh.teams[meta] = [] if meta not in self.bh.supportedFormats: self.bh.supportedFormats.append(meta) self.bh.teams[meta].append(team) with open('plugins/battling/teams.yaml', 'w+') as file: yaml.dump(self.bh.teams, file, default_flow_style=False, explicit_start=True) return reply.response( 'Saved that team for you so that I can play with it :)')
def answer(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, False, True, True, False) if not (room.activity and room.activity.isThisGame(Anagram)): return reply.response('There is no anagram active right now') if room.activity.isCorrect(re.sub(r'[ -]', '', msg).lower()): solved = room.activity.getSolvedWord() timeTaken = room.activity.getSolveTimeStr() room.activity = None # lambda expression to determine the user's score def start_score(u, s): return 1 if(u not in s) else s[u] + 1 Scoreboard[user.id] = start_score(user.id, Scoreboard) # write the score to file with open('plugins/anagram_scoreboard.yaml', 'w') as ym: yaml.dump(Scoreboard, ym) return reply.response(('Congratulations, {name} got it{time}\n' 'The solution was: {solution}').format(name=user.name, time=timeTaken, solution=solved)) return reply.response('{ans} is wrong!'.format(ans=msg.lstrip()))
def untourwl(bot, cmd, room, msg, user): """Attempts to remove a user from the whistlist of people who start tours. Args: bot: Robot, connection between this funciton and the main program. cmd: str, the command the user is executing. msg: str, any message found after the command. user: user object. Returns: Reply object denoting the mesage to be returned and whether or not it the message should be sent in PMs or public chat. """ reply = r.ReplyObject('', True) if not user.hasRank('#'): return reply.response(("You do not have permission to change this." " (Requires #)")) target = bot.toId(msg) if not room.delFromWhitelist(target): return reply.response('This user is not whitelisted in that room.') bot.saveDetails() return reply.response( "{name} removed from the whitelist in this room.".format(name=msg))
def commands(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, False, False, True, True) if room.isPM: return reply.response("Don't try to play games in pm please") if cmd == 'trivia': if not msg: return reply.response('{msg} is not an valid parameter for trivia') if room.activity: return reply.response('There is already a game running in this room') params = bot.removeSpaces(msg).split(',') if params[0] in ['start', 'begin']: if not room.allowGames: return reply.response('This room does not support chatgames.') kind = 'first' if len(params) > 1: kind = params[1] if user.hasRank('@'): room.activity = Trivia(bot.ws, room.title, kind) return reply.response('A new trivia session has started.') return reply.response('You do not have permission to set up a trivia session') elif params[0] in ['stop', 'end']: # The trivia class will solve everything after doing this. room.activity.endSession = True room.activity = None return reply.response('The trivia session has been ended') if cmd == 'ta': if not (room.activity and room.activity.isThisGame(Trivia)): return reply.response('There is no ongoing trivia session.') # Don't give information if wrong or right here, let Trivia deal with that if room.activity.tryAnswer(msg): if not room.activity.solver: room.activity.wasSolved(user.name) else: room.activity.multiple = True return reply.response('NoAnswer') return reply.response('')
def tour(bot, cmd, room, msg, user): """Determines if a user is allowed to commence a tour of any sort. Args: bot: Robot, connection between this funciton and the main program. cmd: str, the command the user is executing. msg: str, any message found after the command. user: user object. Returns: Reply object denoting the mesage to be returned and whether or not it the message should be sent in PMs or public chat. """ reply = r.ReplyObject('', True, True, True) if room.isPM: return reply.response("You can't use this command in a pm.") if not room.isWhitelisted(user): return reply.response( 'You are not allowed to use this command. (Requires whitelisting by a Room Owner)' ) if not bot.canStartTour(room): return reply.response( "I don't have the rank required to start a tour :(") return reply.response('/tour {rest}\n/modnote From {user}'.format( rest=msg, user=user.name))
def answer(bot, cmd, room, msg, user): reply = r.ReplyObject('', True, False, True, True, False) ans = list(msg.lower().split(' ')) if not (room.activity and room.activity.isThisGame(Periodic)): return reply.response('There is no periodic game active right now') if room.activity.check_ans(ans): solved = room.activity.get_solution() timeTaken = room.activity.getSolveTimeStr() room.activity = None # lambda expression to determine the user's score def start_score(u, s): return 1 if (u not in s) else s[u] + 1 Scoreboard[user.id] = start_score(user.id, Scoreboard) with open('plugins/periodic_scoreboard.yaml', 'w') as ym: yaml.dump(Scoreboard, ym) return reply.response( ('Congratulations, {name} got it{time}\n' 'The solution was: {solution}').format(name=user.name, time=timeTaken, solution=solved)) return reply.response('{test} is wrong!'.format(test=msg.lstrip()))
def start(bot, cmd, room, msg, user): global WHITELIST reply = r.ReplyObject('', True, False, True, True, True) if msg.startswith("'") and msg.endswith("'") or (msg.startswith('"') and msg.endswith('"')): return str(parse_text(msg)) if room.title == 'pm' and not cmd.startswith('score'): return reply.response("Don't try to play games in pm please") if msg == 'new': if not user.hasRank(WHITELIST_RANK) and user.id not in WHITELIST: return reply.response( 'You do not have permission to start a game in this room. (Requires {rank})' .format(rank=WHITELIST_RANK)) if room.activity: return reply.response('A game is already running somewhere') if not room.allowGames: return reply.response('This room does not support chat games.') room.activity = PERIODIC_OBJ room.activity.new_game() return reply.response( 'A new periodic game has been created (guess with .pa):\n' + room.activity.get_word()) elif msg == 'hint': if room.activity: return reply.response('The hint is: ' + room.activity.get_hint()) return reply.response('There is no active periodic game right now') elif msg == 'help': if room.activity: return reply.response('Here\'s a periodic table: ' + 'http://imgur.com/t/periodic_table/iolEzW4') return reply.response('There is no active periodic game right now') elif msg == 'end': if not user.hasRank(WHITELIST_RANK) and user.id not in WHITELIST: return reply.response(( 'You do not have permission to end the periodic game. (Requires {rank})' '').format(rank=WHITELIST_RANK)) if not (room.activity and room.activity.isThisGame(Periodic)): return reply.response( 'There is no active periodic game or a different game is active.' ) solved = room.activity.get_solution() room.activity = None return reply.response(( 'The periodic game was forcefully ended by {baduser}. (Killjoy)\nThe solution was: ' '**{solved}**').format(baduser=user.name, solved=solved)) elif msg.lower().startswith('score'): if msg.strip() == 'score': msg += ' {user}'.format(user=user.id) name = bot.toId(msg[len('score '):]) if name not in Scoreboard: return reply.response("This user never won any periodic games") return reply.response( 'This user has won {number} periodic game(s)'.format( number=Scoreboard[name])) else: if msg: return reply.response(( '{param} is not a valid parameter for periodic. Make guesses with .pa' '').format(param=msg)) if room.activity and room.activity.isThisGame(Periodic): return reply.response('Current periodic word: {word}'.format( word=room.activity.getWord())) return reply.response('There is no active periodic game right now')