コード例 #1
0
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)
コード例 #2
0
def pokedex(robot, cmd, params, user, room):
    cmd = re.sub('-(?:mega(?:-(x|y))?|primal)', '', cmd)
    substitutes = {
        'gourgeist-s':
        'gourgeist-small',  # This doesn't break Arceus-Steel like adding |S to the regex would
        'gourgeist-l':
        'gourgeist-large',  # and gourgeist-s /pumpkaboo-s still get found, because it matches the
        'gourgeist-xl':
        'gourgeist-super',  # entry for gougeist/pumpkaboo-super
        'pumpkaboo-s': 'pumpkaboo-small',
        'pumpkaboo-l': 'pumpkaboo-large',
        'pumpkaboo-xl': 'pumpkaboo-super',
        'giratina-o': 'giratina-origin',
        'mr.mime': 'mr_mime',
        'mimejr.': 'mime_jr'
    }
    # Just in case do a double check before progressing...
    if cmd.lower() not in (robot.removeSpaces(p).lower() for p in Pokedex):
        return ReplyObject('{cmd} is not a valid command'.format(cmd=cmd),
                           True)
    if cmd in substitutes:
        cmd = substitutes[cmd]
    if params not in ('rb', 'gs', 'rs', 'dp', 'bw', 'xy', 'sm'):
        params = 'sm'
    if robot.canHtml(room):
        return ReplyObject(
            '/addhtmlbox <a href="http://www.smogon.com/dex/{gen}/pokemon/{mon}/">{capital} analysis</a>'
            .format(gen=params, mon=cmd, capital=cmd.title()), True, True)
    return ReplyObject(
        'Analysis: http://www.smogon.com/dex/{gen}/pokemon/{mon}/'.format(
            gen=params, mon=cmd),
        reply=True,
        pmreply=True)
コード例 #3
0
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)
コード例 #4
0
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')
コード例 #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))
コード例 #6
0
ファイル: commands.py プロジェクト: theonekami/AnonRadio
def forcerestart(robot, cmd, params, user):
    if user.hasRank('#'):
        # Figure out how to do this
        robot.closeConnection()
        return ReplyObject('')
    return ReplyObject(
        'You do not have permisson to use this command. (Only for owner)')
コード例 #7
0
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'))
コード例 #8
0
def newautojoin(robot, cmd, params, user):
    if user.hasRank('#'):
        # Join the room before adding it to list of autojoined rooms
        robot.joinRoom(params)
        robot.saveDetails(True)
        return ReplyObject("New autojoin ({room}) added.".format(room = params))
    return ReplyObject("You don't have permission to save settings. (Requires #)")
コード例 #9
0
def savedetails(robot, cmd, params, user):
    """ Save current robot.details to details.yaml (moves rooms to joinRooms)
     Please note that this command will remove every comment from details.yaml, if those exist."""
    if user.hasRank('#'):
        robot.saveDetails()
        return ReplyObject('Details saved.', True)
    return ReplyObject("You don't have permission to save settings. (Requires #)")
コード例 #10
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]))
コード例 #11
0
def links(robot, cmd, params):
    params = params.lower()
    if not params: params = 'nu'
    if params in Links[cmd]:
        return ReplyObject(Links[cmd][params], True)
    return ReplyObject(
        '{tier} is not a supported format for {command}'.format(
            tier=params if params else "''", command=cmd), True)
コード例 #12
0
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/")
コード例 #13
0
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/")
コード例 #14
0
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)))
コード例 #15
0
ファイル: messages.py プロジェクト: kLuck6/PokemonShowdownBot
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)
コード例 #16
0
def setbroadcast(robot, cmd, params, user):
    params = robot.removeSpaces(params)
    if params in User.Groups or params in ['off', 'no', 'false']:
        if user.hasRank('#'):
            if params in ['off', 'no', 'false']: params = ' '
            if robot.details['broadcastrank'] == params:
                return ReplyObject('Broadcast rank is already {rank}'.format(rank = params if not params == ' ' else 'none'), True)
            robot.details['broadcastrank'] = params
            return ReplyObject('Broadcast rank set to {rank}. (This is not saved on reboot)'.format(rank = params if not params == ' ' else 'none'), True)
        return ReplyObject('You are not allowed to set broadcast rank. (Requires #)')
    return ReplyObject('{rank} is not a valid rank'.format(rank = params if not params == ' ' else 'none'))
コード例 #17
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()))
コード例 #18
0
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))
コード例 #19
0
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))
コード例 #20
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)))
コード例 #21
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()))
コード例 #22
0
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 :)')
コード例 #23
0
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))
コード例 #24
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))
コード例 #25
0
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))
コード例 #26
0
def randteam(robot, cmd):
    # Helper function that calculates if the team sucks against any specific type
    def acceptableWeakness(team):
        if not team: return False
        comp = {t: {'weak': 0, 'res': 0} for t in Types}
        for poke in team:
            types = Pokedex[poke]['types']
            if len(types) > 1:
                for matchup in Types:
                    eff = Types[types[0]][matchup] * Types[types[1]][matchup]
                    if eff > 1:
                        comp[matchup]['weak'] += 1
                    elif eff < 1:
                        comp[matchup]['res'] += 1
            else:
                for matchup in Types:
                    if Types[types[0]][matchup] > 1:
                        comp[matchup]['weak'] += 1
                    elif Types[types[0]][matchup] < 1:
                        comp[matchup]['res'] += 1
        for t in comp:
            if comp[t]['weak'] >= 3:
                return False
            if comp[t]['weak'] >= 2 and comp[t]['res'] <= 1:
                return False
        return True

    cmd = cmd.replace('team', 'poke')
    team = set()
    hasMega = False
    attempts = 0
    while len(team) < 6 or not acceptableWeakness(team):
        poke = choice(list(tiers[cmd]))
        # Test if share dex number with anything in the team
        if [p for p in team if Pokedex[poke]['num'] == Pokedex[p]['num']]:
            continue
        if hasMega and '-Mega' in poke:
            continue
        team |= {poke}
        if not acceptableWeakness(team):
            team -= {poke}
        elif '-Mega' in poke:
            hasMega = True
        if len(team) >= 6:
            break
        attempts += 1
        if attempts >= 100:
            # Prevents locking up if a pokemon turns the team to an impossible genration
            # Since the team is probably bad anyway, just finish it and exit
            while len(team) < 6:
                team |= {choice(list(tiers[cmd]))}
            break
    return ReplyObject(' / '.join(list(team)), True)
コード例 #27
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))
コード例 #28
0
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 :)')
コード例 #29
0
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')
コード例 #30
0
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)
コード例 #31
0
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)))
コード例 #32
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)
コード例 #33
0
ファイル: commands.py プロジェクト: theonekami/AnonRadio
def stats(robot, cmd, params):
    params = params.split(',')
    res1, temp1 = bdtest.ret_stats(params[0])
    try:
        res2, temp2 = bdtest.ret_stats(params[1])
    except:
        temp2 = str("")
        res2 = dict()
        res2[temp2] = (0, 0)
    A = res1[temp1][0] + res2[temp2][0]
    M = res1[temp1][1] + res2[temp2][1]
    temp = temp1 + " " + temp2
    x = "The stats for " + temp + " are Attack:" + str(A) + " Magic:" + str(M)
    ##    print(tempp)
    return ReplyObject(x)
コード例 #34
0
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)))
コード例 #35
0
def uptime(robot):
    mods = [86400, 3600, 60]
    seconds = (datetime.datetime.now() - robot.startTime).total_seconds()
    uptime = []
    for mod in mods:
        unit, seconds = divmod(seconds, mod)
        uptime.append(int(unit))

    uptime[0] = '{} day{}, '.format(
        uptime[0], 's' if uptime[0] > 1 else '') if uptime[0] > 0 else ''
    uptime[1] = '{} hour{} and '.format(
        uptime[1], 's' if uptime[1] > 1 else '') if uptime[1] > 0 else ''
    uptime[2] = '{} minute{}.'.format(uptime[2], 's' if uptime[2] != 1 else '')
    return ReplyObject(
        'Current uptime is: {uptime}'.format(uptime=''.join(uptime)),
        True,
        broadcast=True)
コード例 #36
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)
コード例 #37
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)
コード例 #38
0
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))
コード例 #39
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('')
コード例 #40
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]))
コード例 #41
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'))
コード例 #42
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')