def moderate(bot, cmd, msg, user, room):
    reply = 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 acceptTeam(bot, cmd, msg):
    reply = ReplyObject('', reply=True, broadcast=True)
    meta, team = msg.replace(' ', '').split(',')
    if not team: return reply.response('You forgot a team')

    # Resolve links to teams
    if team.startswith('http'):
        team = PasteImporter.getPasteContent(team)
    if not team:
        return reply.response('Unsupported paste type (probably)')
    # If the pasted team was an importable instead of packed, pack it
    if not team.startswith('|'):
        team = BattleHandler.PSPackTeam(team)
    # Double check so it actually is packed
    if not team.startswith('|'):
        return reply.response(
            "This team doesn't look like a valid packed team :(")

    meta = bot.toId(meta)
    if not meta in bot.bh.teams:
        bot.bh.teams[meta] = []
    if not team in bot.bh.teams[meta]:
        bot.bh.teams[meta].append(team)
    else:
        return reply.response('I already have that team! :D')
    if not meta in bot.bh.supportedFormats:
        bot.bh.supportedFormats.append(meta)
    with open('plugins/battling/teams.yaml', 'w+') as file:
        yaml.dump(bot.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 untell(bot, cmd, msg, user):
    reply = 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 untell(bot, cmd, msg, user):
    reply = 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')
Exemple #5
0
def untourwl(bot, cmd, params, user, room):
    """ Independent command for removing a user from the tours whitelist.

    Reserved for room owners.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, the name of the user.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = ReplyObject('', True)
    targetRoom = room
    params = params.replace(', ', ',').split(',')
    if len(params) > 1:
        targetRoom = bot.getRoom(params[0])
        user = targetRoom.getUser(user.id)
        params.pop(0)
    if not user.hasRank('#'):
        return reply.response(
            'You do not have permission to change this. (Requires #)')
    target = bot.toId(params[0])
    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=params))
def tourhistory(bot, cmd, msg, user, room):
    reply = ReplyObject('', True)
    history = ''
    if msg:
        room = bot.getRoom(msg)
    for tour in room.pastTours:
        history += """
            Name: {name}
            Winner: {winner}
            Runner-Up: {runnerup}
            # of Participants: {players}
            Finals: {replay}\n""".format(
                name = tour.title,
                winner = tour.winner,
                runnerup = tour.runnerUp,
                players = len(tour.players),
                replay = tour.finals)

    r = requests.post('https://pastebin.com/api/api_post.php',
                    data = {
                        'api_dev_key': bot.apikeys['pastebin'],
                        'api_option':'paste',
                        'api_paste_code': textwrap.dedent(history),
                        'api_paste_private': 0,
                        'api_paste_expire_date':'N'})
    if 'Bad API request' in r.text:
        return reply.response('Something went wrong ({error})'.format(error = r.text))
    return reply.response(r.text)
Exemple #7
0
def tour(bot, cmd, params, user, room):
    """ Independent command for initiating tours in this room.

    This is only possible for rooms where this bot has at least '@' rank. Intended
    trusted users who do not have the required room rank.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, parameter(s) you'd give a normal /tour command on showdown.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = 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 :(")
    if params in {'gscnu', 'advnu'}:
        gen, name = ('gen3ou', 'ADV NU') if params == 'advnu' else ('gen2ou',
                                                                    'GSC NU')
        params = 'new {gen}, elimination\n/tour rules {bans}\n/tour name {name}'.format(
            gen=gen, bans=oldgenNUBanlists[params], name=name)
    return reply.response('/tour {rest}\n/modnote From {user}'.format(
        rest=params, user=user.name))
def triviaCommands(bot, cmd, msg, user, room):
    reply = 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 acceptTeam(bot, cmd, msg):
    reply = ReplyObject('', reply = True, broadcast = True)
    meta, team = msg.replace(' ', '').split(',')
    if not team: return reply.response('You forgot a team')


    # Resolve links to teams
    if team.startswith('http'):
        team = PasteImporter.getPasteContent(team)
    if not team:
        return reply.response('Unsupported paste type (probably)')
    # If the pasted team was an importable instead of packed, pack it
    if not team.startswith('|'):
        team = BattleHandler.PSPackTeam(team)
    # Double check so it actually is packed
    if not team.startswith('|'): return reply.response("This team doesn't look like a valid packed team :(")

    meta = bot.toId(meta)
    if not meta in bot.bh.teams:
        bot.bh.teams[meta] = []
    if not team in bot.bh.teams[meta]:
        bot.bh.teams[meta].append(team)
    else:
        return reply.response('I already have that team! :D')
    if not meta in bot.bh.supportedFormats:
        bot.bh.supportedFormats.append(meta)
    with open('plugins/battling/teams.yaml', 'w+') as file:
        yaml.dump(bot.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 tourhistory(bot, cmd, msg, user, room):
    reply = ReplyObject('', True)
    history = ''
    if msg:
        room = bot.getRoom(msg)
    for tour in room.pastTours:
        history += """
            Name: {name}
            Winner: {winner}
            Runner-Up: {runnerup}
            # of Participants: {players}
            Finals: {replay}\n""".format(
                name = tour.title,
                winner = tour.winner,
                runnerup = tour.runnerUp,
                players = len(tour.players),
                replay = tour.finals)

    r = requests.post('https://pastebin.com/api/api_post.php',
                    data = {
                        'api_dev_key': bot.apikeys['pastebin'],
                        'api_option':'paste',
                        'api_paste_code': textwrap.dedent(history),
                        'api_paste_private': 0,
                        'api_paste_expire_date':'N'})
    if 'Bad API request' in r.text:
        return reply.response('Something went wrong ({error})'.format(error = r.text))
    return reply.response(r.text)
def oldgentour(bot, cmd, msg, user, room):
    reply = 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 oldgentour(bot, cmd, msg, user, room):
    reply = 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 unbanthing(bot, cmd, msg, user, room):
    reply = 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 read(bot, cmd, msg, user):
    reply = 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 speify 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 read(bot, cmd, msg, user):
    reply = 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 speify 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 gettourwl(bot, cmd, params, user, room):
    reply = ReplyObject('', True, True)
    targetRoom = bot.getRoom(params)
    if not targetRoom: targetRoom = room
    if not user.hasRank('@'): return reply.response('You don\'t have permission to view the tour whitelist for {}'.format(targetRoom.title))
    if not targetRoom.tourwhitelist: return reply.response('No whitelist for room {}'.format(targetRoom.title))
    if bot.canStartTour(room) and len(targetRoom.tourwhitelist) > 5:
        return reply.response('!code - {}'.format('\n- '.join(targetRoom.tourwhitelist)))
    else:
        return reply.response('Whitelisted users in {room}: {users}'.format(room = targetRoom.title, users = ', '.join(targetRoom.tourwhitelist)))
def getranking(bot, cmd, msg, user, room):
    reply = 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, Loader = yaml.CLoader) # This file might be large, and CLoader has better performance

    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(user = 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 getranking(bot, cmd, msg, user, room):
    reply = 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, Loader = yaml.CLoader) # This file might be large, and CLoader has better performance

    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(user = 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 banthing(bot, cmd, msg, user, room):
    reply = 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 answer(bot, cmd, msg, user, room):
    reply = ReplyObject('', True, False, False, True, True)
    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
        # Save score
        Scoreboard[user.id] = 1 if user.id not in Scoreboard else Scoreboard[user.id] + 1
        with open('plugins/scoreboard.yaml', 'w') as ym:
            yaml.dump(Scoreboard, ym)
        return reply.response('Congratulations, {name} got it{time}\nThe solution was: {solution}'.format(name = user.name, time = timeTaken, solution = solved))
    return reply.response('{test} is wrong!'.format(test = msg.lstrip()))
Exemple #21
0
def getactivity(bot, cmd, params, user, room):
    """ Independent command for getting the activity of user(s) in a room.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, the name of the user.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = ReplyObject('', escape=True, pmreply=True, ignoreml=True)
    params = params.replace(', ', ',').split(',')
    targetRoom = room
    if room.isPM or bot.getRoom(params[0]):
        targetRoom = bot.getRoom(params.pop(0))
    user = '' if len(params) == 0 or params[0].isdigit(
    ) or params[0] == 'all' else params.pop(0)
    user = bot.toId(user)
    period = 30 if len(
        params) == 0 else sys.maxsize if params[0] == 'all' else int(
            params.pop(0))

    activityData = targetRoom.activityTracker.getActivityForPeriod(
        period, targetRoom, user)
    if len(activityData) == 0:
        return reply.response('No activity data found for room {room}'.format(
            room=targetRoom.title))
    lines = [
        'Activity in {room} for {user} the last {period} days:'.format(
            room=targetRoom.title, period=period, user='******'.format(user))
    ]
    for entry, count in activityData:
        lines.append('  {datename}: {count} lines'.format(datename=entry,
                                                          count=count))
    if bot.canBroadcast(room):
        return reply.response('!code ' + '\n'.join(lines))
    else:
        r = requests.post('https://pastebin.com/api/api_post.php',
                          data={
                              'api_dev_key': bot.apikeys['pastebin'],
                              'api_option': 'paste',
                              'api_paste_code': '\n'.join(lines),
                              'api_paste_private': 0,
                              'api_paste_expire_date': 'N'
                          })
        if 'Bad API request' in r.text:
            return reply.response(
                'Something went wrong ({error})'.format(error=r.text))
        return reply.response(r.text)
Exemple #22
0
def gettourwl(bot, cmd, params, user, room):
    reply = ReplyObject('', True, True)
    targetRoom = bot.getRoom(params)
    if not targetRoom: targetRoom = room
    user = targetRoom.getUser(user.id)
    if not user.hasRank('@'):
        return reply.response(
            'You don\'t have permission to view the tour whitelist for {}'.
            format(targetRoom.title))
    if not targetRoom.tourwhitelist:
        return reply.response('No whitelist for room {}'.format(
            targetRoom.title))
    return reply.response('Whitelisted users in {room}: {users}'.format(
        room=targetRoom.title, users=', '.join(targetRoom.tourwhitelist)))
def startLaddering(bot, cmd, msg, user):
    reply = ReplyObject('', reply = True)
    if not user.isOwner: return reply.response('Only owner is allowed to do this.')
    if bot.toId(msg) == 'false':
        bot.bh.clearLadderFormat()
        return reply.response('Stopped laddering.')
    if not bot.bh.setLadderFormat(msg): return reply.response('Starting to ladder failed, no valid teams for format: {}.'.format(msg))
    # Now that we know that we have valid teams for laddering, and the settings
    # to restart after finishing a game are set, we can now begin.

    # Note: To ladder in formats with random teams, add an empty string to that format in teams.yaml.
    bot.send('|/utm {}'.format(bot.bh.getRandomTeam(bot.bh.ladderFormat)))
    bot.send('|/search {}'.format(bot.bh.ladderFormat))
    return reply.response('Started laddering in format: {}'.format(bot.bh.ladderFormat))
def getranking(bot, cmd, msg, user, room):
    reply = 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)
    parts = list(map(bot.toId, msg.split(',')))
    roomTitle = ''
    if os.path.exists('plugins/stats/{room}'.format(room=parts[0])):
        roomTitle = parts.pop(0)
    elif os.path.exists('plugins/stats/{room}'.format(room=room.title)):
        roomTitle = room.title
    else:
        return reply.response('The room {} has no data about rankings'.format(
            msg.split(',')[0]))

    if not parts:
        return reply.response('No format given')

    if os.path.exists('plugins/stats/{room}/{format}'.format(room=roomTitle,
                                                             format=parts[0])):
        formatName = parts.pop(0)
        with open(
                'plugins/stats/{}/{}/tournament-rankings.yaml'.format(
                    roomTitle, formatName), 'r+') as yf:
            formatData = yaml.load(yf, Loader=Loader)
        try:
            userData = formatData[parts[0]]
            try:
                gamewins = userData['gamewins']
            except KeyError:
                gamewins = 'N/A'
            return reply.response(
                '{user} has played {games}, won {ind} games, and {wins} tours ({winrate:.1f}% tour win rate)'
                .format(user=parts[0],
                        games=userData['entered'],
                        ind=gamewins,
                        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))
    else:
        return reply.response(
            'The room has no data about the format {}'.format(parts[0]))
Exemple #25
0
def answer(bot, cmd, msg, user, room):
    reply = ReplyObject('', True, False, False, True, True)
    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
        # Save score
        Scoreboard[user.id] = 1 if user.id not in Scoreboard else Scoreboard[
            user.id] + 1
        with open('plugins/scoreboard.yaml', 'w') as ym:
            yaml.dump(Scoreboard, ym)
        return reply.response(
            'Congratulations, {name} got it{time}\nThe solution was: {solution}'
            .format(name=user.name, time=timeTaken, solution=solved))
    return reply.response('{test} is wrong!'.format(test=msg.lstrip()))
def leaveroom(bot, cmd, params, user, room):
    """ Independent command for making this bot leave a room.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, optional parameter like room name, if left empty
                function attempts to leave room where this command was invoked.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = ReplyObject()
    params = bot.removeSpaces(params)
    if not params: params = room.title
    if bot.leaveRoom(params):
        return reply.response('Leaving room {r} succeeded'.format(r = params))
    return reply.response('Could not leave room: {r}'.format(r = params))
def startLaddering(bot, cmd, msg, user):
    reply = ReplyObject('', reply=True)
    if not user.isOwner:
        return reply.response('Only owner is allowed to do this.')
    if bot.toId(msg) == 'false':
        bot.bh.clearLadderFormat()
        return reply.response('Stopped laddering.')
    if not bot.bh.setLadderFormat(msg):
        return reply.response(
            'Starting to ladder failed, no valid teams for format: {}.'.format(
                msg))
    # Now that we know that we have valid teams for laddering, and the settings
    # to restart after finishing a game are set, we can now begin.

    # Note: To ladder in formats with random teams, add an empty string to that format in teams.yaml.
    bot.send('|/utm {}'.format(bot.bh.getRandomTeam(bot.bh.ladderFormat)))
    bot.send('|/search {}'.format(bot.bh.ladderFormat))
    return reply.response('Started laddering in format: {}'.format(
        bot.bh.ladderFormat))
def tourwl(bot, cmd, params, user, room):
    """ Independent command for a user to tours whitelist.

    Reserved for room owners.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, the name of the user.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = ReplyObject('', True)
    if not user.hasRank('#'): return reply.response('You do not have permission to change this. (Requires #)')
    target = bot.toId(params)
    if not room.addToWhitelist(target): return reply.response('This user is already whitelisted in that room.')
    bot.saveDetails()
    return reply.response('{name} added to the whitelist in this room.'.format(name = params))
Exemple #29
0
def addEvent(robot, cmd, params, user, room):
    reply = ReplyObject('', reply=True, pmreply=True)
    if not user.hasRank('#'):
        return reply.response(
            "Permission denied, only Room Owners (#) and up can use this command."
        )

    with open('added-jobs.csv', 'a+') as jobs:
        jobs.write('{user},{job}\n'.format(user=user.id, job=params))

    date, frequency, joblist = params.replace('| ', '|').split('|')
    # Validate date string format first
    if not EventScheduler.validateDateString(date):
        return reply.response(
            'Invald date format. Expected format is YYYY/MM/DD HH:MM.')

    room.scheduler.addJob(date, frequency, joblist)
    return reply.response(
        'New event scheduled for {date}, repeating every {freq} days.'.format(
            date=date, freq=frequency))
Exemple #30
0
def tell(bot, cmd, msg, user):
    reply = 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 allowgames(bot, cmd, params, user, room):
    """ Independent command for changing permissions for games in this room.

    Reserved for room owners. They can decide to allow games/activities in their room.

    Args:
        bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
        cmd: string, the command that was send.
        room: Room, the room object that the command was sent from.
        params: string, required parameter indicating the status of games in this room.
        user: User, the user object of the user who sent the command.
    Returns:
        ReplyObject.
    """
    reply = 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.")
    params = bot.removeSpaces(params)
    if params 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 params 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 = params))
Exemple #32
0
def triviaCommands(bot, cmd, msg, user, room):
    reply = 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 tell(bot, cmd, msg, user):
    reply = 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 start(bot, cmd, msg, user, room):
    reply = ReplyObject('', True, False, False, True, True)
    if room.isPM and not cmd.startswith('score'): return reply.response("Don't try to play games in pm please")
    if msg == 'new':
        if not user.hasRank('%'): return reply.response('You do not have permission to start a game in this room. (Requires %)')
        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: ' + room.activity.getHint())
        return reply.response('There is no active anagram right now')
    elif msg == 'end':
        if not user.hasRank('%'): 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)\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 anagrams")
        return reply.response('This user has won {number} anagram{plural}'.format(number = Scoreboard[name], plural = '' if not type(Scoreboard[name]) == str and Scoreboard[name] < 2  else 's'))
    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 commands(bot, cmd, msg, user, room):
    reply = 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')
        room.activity = Workshop(bot.toId(msg[len('new '):]) if msg[len('new '):] else user.id)
        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')
    return reply.response('Unrecognized command: {cmd}'.format(cmd = msg if msg else 'nothing'))
Exemple #36
0
def start(bot, cmd, msg, user, room):
    reply = ReplyObject('', True, False, False, True, True)
    if room.isPM and not cmd.startswith('score'):
        return reply.response("Don't try to play games in pm please")
    if msg == 'new':
        if not user.hasRank('%'):
            return reply.response(
                'You do not have permission to start a game in this room. (Requires %)'
            )
        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: ' + room.activity.getHint())
        return reply.response('There is no active anagram right now')
    elif msg == 'end':
        if not user.hasRank('%'):
            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)\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 anagrams")
        return reply.response(
            'This user has won {number} anagram{plural}'.format(
                number=Scoreboard[name],
                plural='' if not type(Scoreboard[name]) == str
                and Scoreboard[name] < 2 else 's'))
    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')
Exemple #37
0
def commands(bot, cmd, msg, user, room):
    reply = 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')
        room.activity = Workshop(
            bot.toId(msg[len('new '):]) if msg[len('new '):] else user.id)
        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')
    return reply.response(
        'Unrecognized command: {cmd}'.format(cmd=msg if msg else 'nothing'))