Ejemplo n.º 1
0
def onCommand(message_in):
    if message_in.command == 'eat':
        author = displayname.name(message_in.author)
        member = message_in.body.strip()

        # Check if we're eating nothing
        if member == "":
            nothingList = ['you sit quietly and eat *nothing*...',
                            'you\'re *sure* there was something to eat, so you just chew on nothingness...',
                            'there comes a time when you need to realize that you\'re just chewing nothing for the sake of chewing.  That time is now.']

            randnum = random.randint(0, len(nothingList) - 1)
            return message.message('*{}*, {}'.format(author, nothingList[randnum]))

        # Check if we're eating a member
        memberCheck = displayname.memberForName(member, message_in.server)
        if memberCheck:
            # We're eating a member - let's do a bot-check
            if memberCheck.id == message_in.server.me.id:
                # It's me!
                memberList = ['you try to eat *me* - but unfortunately, I saw it coming - your jaw hangs open as I deftly sidestep.',
                                'your mouth hangs open for a brief second before you realize that *I\'m* eating *you*.',
                                'I\'m a bot.  You can\'t eat me.',
                                'your jaw clamps down on... wait... on nothing, because I\'m *digital!*.',
                                'what kind of bot would I be if I let you eat me?']

            elif memberCheck.id == message_in.author.id:
                # We're eating...  ourselves?
                memberList = ['you clamp down on your own forearm - not surprisingly, it hurts.',
                                'you place a finger into your mouth, but *just can\'t* force yourself to bite down.',
                                'you happily munch away, but can now only wave with your left hand.',
                                'wait - you\'re not a sandwich!',
                                'you might not be the smartest...']

            else:
                memName = displayname.name(memberCheck)
                memberList = ['you unhinge your jaw and consume *{}* in one bite.'.format(memName),
                                'you try to eat *{}*, but you just can\'t quite do it - you spit them out, the taste of failure hanging in your mouth...'.format(memName),
                                'you take a quick bite out of *{}*.  They probably didn\'t even notice.'.format(memName),
                                'you sink your teeth into *{}\'s* shoulder - they turn to face you, eyes wide as you try your best to scurry away and hide.'.format(memName),
                                'your jaw clamps down on *{}* - a satisfying *crunch* emanates as you finish your newest meal.'.format(memName)]
            randnum = random.randint(0, len(memberList) - 1)
            return message.message('*{}*, {}'.format(author, memberList[randnum]))

        # Assume we're eating something else
        itemList = ['you take a big chunk out of *{}*. *Delicious.*'.format(member),
                        'your teeth sink into *{}* - it tastes satisfying.'.format(member),
                        'you rip hungrily into *{}*, tearing it to bits!'.format(member),
                        'you just can\'t bring yourself to eat *{}* - so you just hold it for awhile...'.format(member),
                        'you attempt to bite into *{}*, but you\'re clumsier than you remember - and fail...'.format(member),]

        randnum = random.randint(0, len(itemList) - 1)
        return message.message('*{}*, {}'.format(author, itemList[randnum]))
Ejemplo n.º 2
0
async def onCommand(message_in):
    if message_in.command == 'plugins':
        plugin_list = []
        for plugin_in in Bot.plugins:
            plugin_list.append(plugin_in.name)
        return message.Message(body='```{}```'.format(', '.join(plugin_list)))

    if message_in.command == 'commands' or message_in.command == 'help':
        cmd_names = []
        cmd_descs = []
        for botcommand in Bot.commands:
            if botcommand.devcommand != True:
                cmd_names.append(botcommand.name)
                cmd_descs.append(botcommand.shortdesc)
        cmd_list = []
        pad_len = len(max(cmd_names, key=len))
        for index, value in enumerate(cmd_names):
            cmd_list.append('{} - {}'.format(cmd_names[index].ljust(pad_len),
                                             cmd_descs[index]))
        return message.Message(body='```{}```'.format('\n'.join(cmd_list)))

    if message_in.command == 'info':
        sha = git.git_commit()
        track = git.git_branch()
        remote = git.get_remote()
        link = git.get_url()
        if track == 'master':
            embed = discord.Embed(color=discord.Color.red())
        elif track == 'unstable':
            embed = discord.Embed(color=discord.Color.gold())
        elif track == 'stable':
            embed = discord.Embed(color=discord.Color.green())
        else:
            embed = discord.Embed(color=discord.Color.light_grey())
        embed.set_author(
            name='Project StarBot v0.2.0-{} on track {}'.format(
                sha[:7], track),
            url=link,
            icon_url=
            'https://pbs.twimg.com/profile_images/616309728688238592/pBeeJQDQ.png'
        )
        embed.add_field(name="Bot Team Alpha",
                        value="CorpNewt\nSydney Erickson\nGoldfish64")
        embed.add_field(
            name="Source Code",
            value=
            "Interested in poking around inside the bot?\nClick on the link above!"
        )
        embed.set_footer(text="Pulled from {}".format(remote))
        return message.Message(embed=embed)

    if message_in.command == 'plugintree':
        dups = commands_detect_dups()
        plugin_string = '```\n'
        for plugin_in in Bot.plugins:
            plugin_string += '{}\n'.format(plugin_in.name)
            plugin_commands = len(plugin_in.commands)
            index = 0
            for command_in in plugin_in.commands:
                index += 1
                if plugin_commands != index:
                    if command_in.name in dups:
                        plugin_string += '├ {} <-- duplicate\n'.format(
                            command_in.name)
                    else:
                        plugin_string += '├ {}\n'.format(command_in.name)
                else:
                    if command_in.name in dups:
                        plugin_string += '└ {} <-- duplicate\n'.format(
                            command_in.name)
                    else:
                        plugin_string += '└ {}\n'.format(command_in.name)
        plugin_string += '```'
        return message.Message(body=plugin_string)

    if message_in.command == 'uptime':
        time_current = int(time.time())
        time_str = readableTime.getReadableTimeBetween(Bot.startTime,
                                                       time_current)
        return message.Message(body='I\'ve been up for *{}*.'.format(time_str))

    if message_in.command == 'hostinfo':
        # Get information about host environment.
        time_current = int(time.time())

        # CPU stats.
        cpu_threads = os.cpu_count()
        cpu_usage = psutil.cpu_percent(interval=1)

        # Memory stats.
        mem_stats = psutil.virtual_memory()
        mem_percent = mem_stats.percent
        mem_used = convert_size(mem_stats.used)
        mem_total = convert_size(mem_stats.total)

        # Platform info.
        platform_current = platform.platform()

        # Python version info.
        pyver_major = sys.version_info.major
        pyver_minor = sys.version_info.minor
        pyver_micro = sys.version_info.micro
        pyver_release = sys.version_info.releaselevel

        # Storage info.
        stor = psutil.disk_usage('/')
        stor_used = convert_size(stor.used)
        stor_total = convert_size(stor.total)
        stor_free = convert_size(stor.total - stor.used)

        # Format hostinfo with OS, CPU, RAM, storage, and other bot info.
        msg = '***{}\'s*** **Home:**\n'.format(
            displayname.name(message_in.server.me))
        msg += '```Host OS       : {}\n'.format(platform_current)
        msg += 'Host Python   : {}.{}.{} {}\n'.format(pyver_major, pyver_minor,
                                                      pyver_micro,
                                                      pyver_release)
        if not isinstance(cpu_threads, int):
            msg += 'Host CPU usage: {}% of {}\n'.format(
                cpu_usage, platform.machine())
        elif cpu_threads > 1:
            msg += 'Host CPU usage: {}% of {} ({} threads)\n'.format(
                cpu_usage, platform.machine(), cpu_threads)
        else:
            msg += 'Host CPU usage: {}% of {} ({} thread)\n'.format(
                cpu_usage, platform.machine(), cpu_threads)
        msg += 'Host RAM      : {} ({}%) of {}\n'.format(
            mem_used, mem_percent, mem_total)
        msg += 'Host storage  : {} ({}%) of {} - {} free\n'.format(
            stor_used, stor.percent, stor_total, stor_free)
        msg += 'Hostname      : {}\n'.format(platform.node())
        msg += 'Host uptime   : {}```'.format(
            readableTime.getReadableTimeBetween(psutil.boot_time(),
                                                time.time()))

        # Return completed message.
        return message.Message(body=msg)

    if message_in.command == 'cpuinfo':
        # Get CPU usage and create string for message.
        cpu_pcts = psutil.cpu_percent(interval=0.1, percpu=True)
        cpu_pct_str = '{}\n'.format(platform.processor())
        cpu_threads = psutil.cpu_count()
        cpu_cores = psutil.cpu_count(logical=False)
        cpu_arch = platform.machine()
        # First, check to see if we can accurately determine the number of physical cores. If not, omit the core count.
        if not cpu_cores:
            if cpu_threads > 1:
                cpu_pct_str += '{} threads of {}'.format(cpu_threads, cpu_arch)
            else:
                cpu_pct_str += '{} thread of {}'.format(cpu_threads, cpu_arch)
        elif cpu_cores > 1:  # Multiple cores.
            cpu_pct_str += '{} threads - {} cores of {}'.format(
                cpu_threads, cpu_cores, cpu_arch)
        else:
            if psutil.cpu_count() > 1:  # Multiple threads, single core.
                cpu_pct_str += '{} threads - {} core of {}'.format(
                    cpu_threads, cpu_cores, cpu_arch)
            else:  # Single thread, single core.
                cpu_pct_str += '{} thread - {} core of {}'.format(
                    cpu_threads, cpu_cores, cpu_arch)

        # Build CPU usage graph.
        cpu_pct_str += '\n\n'
        for index, value in enumerate(cpu_pcts):
            cpu_pct_str += 'CPU {}: {}\n'.format(
                str(index), progressBar.makeBar(cpu_pcts[index]))

        # Return completed message.
        return message.Message(body='```{}```'.format(cpu_pct_str))

    if message_in.command == 'setprefix':
        if settings.owners_check(message_in.author.id):
            prefix = message_in.body.split(' ', 1)[-1]
            settings.prefix_set(message_in.server.id, prefix)
            return message.Message(body='Prefix set to {}'.format(prefix))
        else:
            return message.Message(body='Only my owner can set the prefix!')

    if message_in.command == 'getprefix':
        return message.Message(body='Prefix is {}'.format(
            settings.prefix_get(message_in.server.id)))

    if message_in.command == 'speedtest':
        if settings.owners_check(message_in.author.id):
            speed = pyspeedtest.SpeedTest()
            msg = '**Speed Test Results:**\n'
            msg += '```\n'
            msg += '    Ping: {}\n'.format(round(speed.ping(), 2))
            msg += 'Download: {}MB/s\n'.format(
                round(speed.download() / 1024 / 1024, 2))
            msg += '  Upload: {}MB/s```'.format(
                round(speed.upload() / 1024 / 1024, 2))
            return message.Message(body=msg)
        else:
            return message.Message(
                body='You do not have permisison to run a speedtest.')

    if message_in.command == "addowner":
        if settings.owners_get():
            try:
                if settings.owners_check(message_in.author.id):
                    member = message_in.body.strip()
                    new_member = displayname.memberForName(
                        member, message_in.server)

                    if settings.owners_check(new_member.id):
                        return message.Message(
                            body="User is already an owner.")
                    elif new_member.bot:
                        return message.Message(body="Bots cannot be owners.")
                    else:
                        settings.owners_add(new_member.id)
                        return message.Message(
                            body="Added owner successfully.")
                else:
                    return message.Message(
                        body="You aren't an owner of the bot.")
            except AttributeError:
                return message.Message(body="Invalid user.")
        else:
            settings.owners_add(message_in.author.id)
            return message.Message(
                body=
                "You have successfully claimed yourself as the first owner!")

    if message_in.command == 'owners':
        owners = []
        if not settings.owners_get():
            return message.Message(body='I have no owners')
        for owner in settings.owners_get():
            user = displayname.memberForID(str(owner), message_in.server)
            if user:
                owners.append(str(user.name))
            else:
                owners.append(str(owner))
        owner_list = ', '.join(owners)
        return message.Message(body=owner_list)

    if message_in.command == SERVERSCMD:
        # Get server count.
        servercount = len(Bot.client.servers)

        # Return message.
        if servercount == 1:
            return message.Message(
                "I am a member of **{} server**!".format(servercount))
        else:
            return message.Message(
                "I am a member of **{} servers**!".format(servercount))

    if message_in.command == 'messages':
        # Get server.
        server = message_in.server

        # If the server is null, show error.
        if not server:
            return message.Message("This is not a server. :wink:")

        msg_count = Bot.messagesSinceStart
        msg_count_server = logging.message_count_get(server.id)
        msg = "I've witnessed *{} messages* since I started and *{} messages* overall!"
        return message.Message(msg.format(msg_count, msg_count_server))

    if message_in.command == 'invite':

        class perm_admin:
            value = 8

        return message.Message(
            body=discord.utils.oauth_url(Bot.client.user.id, perm_admin))

    if message_in.command == NICKNAMECMD:
        if message_in.channel.permissions_for(
                message_in.author).manage_nicknames:
            # Change nickname.
            await Bot.client.change_nickname(message_in.server.me,
                                             message_in.body.strip())
            # if message_in.server.me.nick:
            #    return message.Message("My new nickname in this server is **{}**".format(message_in.server.me.nick))
            #else:
            #   return message.Message("My nickname has been removed.")
            return message.Message("My nickname has been changed.")
        else:
            return message.Message(
                "You cannot change nicknames on this server.")

    if message_in.command == 'ping':
        return message.Message(body='PONG! Bot is up!')
Ejemplo n.º 3
0
async def onCommand(message_in):
    '''Run plugin commands.'''

    # Get user.
    if message_in.server:
        me = message_in.server.me
    else:
        me = message_in.channel.me

    # Lenny.
    if message_in.command == LENNYCMD:
        # Create message.
        msg = "( ͡° ͜ʖ ͡°)"

        # Append extra on if needed.
        if message_in.body.strip():
            msg += "\n" + message_in.body.strip()

        # Return message.
        return message.Message(msg, delete=True)

    # Shrug.
    if message_in.command == SHRUGCMD:
        # Create message.
        msg = r"¯\_(ツ)_/¯"

        # Append extra on if needed.
        if message_in.body.strip():
            msg += "\n" + message_in.body.strip()

        # Return message.
        return message.Message(msg, delete=True)

    # Tableflip.
    if message_in.command == TABLEFLIPCMD:
        # Create message.
        msg = "(╯°□°)╯︵ ┻━┻"

        # Append extra on if needed.
        if message_in.body.strip():
            msg += "\n" + message_in.body.strip()

        # Return message.
        return message.Message(msg, delete=True)

    # Fart.
    if message_in.command == FARTCMD:
        # Make farts.
        fart_list = [
            "Poot", "Prrrrt", "Thhbbthbbbthhh", "Plllleerrrrffff", "Toot",
            "Blaaaaahnk", "Squerk"
        ]
        randnum = random.randint(0, len(fart_list) - 1)
        msg = '{}'.format(fart_list[randnum])

        # Append extra on if needed.
        if message_in.body.strip():
            msg += "\n" + message_in.body.strip()

        # Return fart message.
        return message.Message(msg, delete=True)

    if message_in.command == BETACMD:
        return message.Message(body='It looks like something went wrong',
                               file="beta.jpg")

    if message_in.command == EATCMD:
        author = displayname.name(message_in.author)
        member = message_in.body.strip()
        if message_in.server:
            mem_check = displayname.memberForName(member,
                                                  message_in.server.members,
                                                  me)
        else:
            mem_check = displayname.memberForName(
                member, message_in.channel.recipients, me)

        # Check if we're eating nothing
        if member == "":
            msg_list = [
                'you sit quietly and eat *nothing*...',
                'you\'re *sure* there was something to eat, so you just chew on nothingness...',
                'there comes a time when you need to realize that you\'re just chewing nothing for the sake of chewing.  That time is now.'
            ]
        elif mem_check:
            # We're eating a member - let's do a bot-check
            if mem_check.id == me.id:
                # It's me!
                msg_list = [
                    'you try to eat *me* - but unfortunately, I saw it coming - your jaw hangs open as I deftly sidestep.',
                    'your mouth hangs open for a brief second before you realize that *I\'m* eating *you*.',
                    'I\'m a bot.  You can\'t eat me.',
                    'your jaw clamps down on... wait... on nothing, because I\'m *digital!*.',
                    'what kind of bot would I be if I let you eat me?'
                ]

            elif mem_check.id == message_in.author.id:
                # We're eating...  ourselves?
                msg_list = [
                    'you clamp down on your own forearm - not surprisingly, it hurts.',
                    'you place a finger into your mouth, but *just can\'t* force yourself to bite down.',
                    'you happily munch away, but can now only wave with your left hand.',
                    'wait - you\'re not a sandwich!',
                    'you might not be the smartest...'
                ]

            else:
                mem_name = displayname.name(mem_check)
                msg_list = [
                    'you unhinge your jaw and consume *{}* in one bite.'.
                    format(mem_name),
                    'you try to eat *{}*, but you just can\'t quite do it - you spit them out, the taste of failure hanging in your mouth...'
                    .format(mem_name),
                    'you take a quick bite out of *{}*.  They probably didn\'t even notice.'
                    .format(mem_name),
                    'you sink your teeth into *{}\'s* shoulder - they turn to face you, eyes wide as you try your best to scurry away and hide.'
                    .format(mem_name),
                    'your jaw clamps down on *{}* - a satisfying *crunch* emanates as you finish your newest meal.'
                    .format(mem_name)
                ]
        else:
            msg_list = [
                'you take a big chunk out of *{}*. *Delicious.*'.format(
                    member),
                'your teeth sink into *{}* - it tastes satisfying.'.format(
                    member),
                'you rip hungrily into *{}*, tearing it to bits!'.format(
                    member),
                'you just can\'t bring yourself to eat *{}* - so you just hold it for awhile...'
                .format(member),
                'you attempt to bite into *{}*, but you\'re clumsier than you remember - and fail...'
                .format(member)
            ]

        randnum = random.randint(0, len(msg_list) - 1)
        return message.Message('*{}*, {}'.format(author, msg_list[randnum]))
Ejemplo n.º 4
0
async def onCommand(message_in):
    # Initialize Database

    database.init()
    OffsetTable = Table('offsets', TableTypes.pGlobal)

    # Get user.
    if message_in.server:
        me = message_in.server.me
    else:
        me = message_in.channel.me

    if message_in.command == 'setoffset':
        # Normalize offset

        offsetstr = message_in.body.strip()

        if offsetstr == "":
            return message.Message(
                'Incorrect Offset format. Has to be in +/-HH:MM!')

        if offsetstr[0] == '+':
            prefix = '+'
        else:
            prefix = ''

        try:
            hours, minutes = map(int, offsetstr.split(':'))
        except Exception:
            try:
                hours = int(offsetstr)
                minutes = 0
            except Exception:
                return message.Message(
                    'Incorrect Offset format. Has to be in +/-HH:MM!')
        normalizedoffset = '{}{}:{}'.format(prefix, hours, minutes)

        # Set Offset in Database

        # Try to update Offset if it exists
        existingOffset = Table.search(OffsetTable, 'id',
                                      '{}'.format(message_in.author.id))

        if existingOffset != None:
            existingOffset.edit(
                dict(id=message_in.author.id, offset=normalizedoffset))
        else:
            # Create new entry
            Table.insert(
                OffsetTable,
                dict(id=message_in.author.id, offset=normalizedoffset))
            # Get time right now

        # Return time along with offset
        timeutc = datetime.datetime.utcnow()
        # Apply offset

        if hours > 0:
            # Apply positive offset
            timedelta = datetime.timedelta(hours=hours, minutes=minutes)
            newTime = timeutc + timedelta
        elif hours < 0:
            # Apply negative offset
            timedelta = datetime.timedelta(hours=(-1 * hours),
                                           minutes=(-1 * minutes))
            newTime = timeutc - timedelta
        else:
            # No offset
            newTime = timeutc

        return message.Message(
            'Your UTC offset has been set to *{}*, for which the time is {}.'.
            format(normalizedoffset, newTime.strftime("%I:%M %p")))

    if message_in.command == 'time':
        memberOrOffset = message_in.body.strip()

        # Check whose time we need (or if we got an offset)

        if not memberOrOffset:
            member = message_in.author
        else:
            # Try to get a user first
            member = displayname.memberForName(memberOrOffset,
                                               message_in.server, me)

        if member:
            existingOffset = Table.search(OffsetTable, 'id',
                                          '{}'.format(member.id))

            # Check if entry exists
            try:
                offset = existingOffset.data[1]
            except Exception:
                return message.Message(
                    '*{}* didn\'t set an offset. Set an offset with `!setoffset (offset)`.'
                    .format(displayname.name(member)))
        else:
            # Assume input is offset
            offset = memberOrOffset

        offset = offset.replace('+', '')

        # Split time string by : and get hour/minute values
        try:
            hours, minutes = map(int, offset.split(':'))
        except Exception:
            try:
                hours = int(offset)
                minutes = 0
            except Exception:
                return message.Message(
                    'Invalid offset format. Has to be in +/-HH:MM!')

        # Get time right now
        timeutc = datetime.datetime.utcnow()
        # Apply offset

        if hours > 0:
            # Apply positive offset
            offsetmsg = 'UTC+{}'.format(offset)
            timedelta = datetime.timedelta(hours=hours, minutes=minutes)
            newTime = timeutc + timedelta
        elif hours < 0:
            # Apply negative offset
            offsetmsg = 'UTC{}'.format(offset)
            timedelta = datetime.timedelta(hours=(-1 * hours),
                                           minutes=(-1 * minutes))
            newTime = timeutc - timedelta
        else:
            # No offset
            newTime = t

        if member:
            msg = '{}; where *{}* is, it\'s currently *{}*'.format(
                offsetmsg, displayname.name(member),
                newTime.strftime("%I:%M %p"))
        else:
            msg = '{} is currently *{}*'.format(offsetmsg,
                                                newTime.strftime("%I:%M %p"))
        # Say message
        return message.Message(msg)