Example #1
0
 async def fortune(self, ctx, *val: str):
     msg = ctx.message
     """Display a fortune from the unix `fortune` program"""
     allowedCookies = [
         "fortunes", "riddles", "literature", "chucknorris", "pony"
     ]
     toPass = []
     for s in val:
         current = s.lower().strip()
         if current in allowedCookies:
             toPass.append(current)
     if len(toPass) > 0:
         args = ' '.join(toPass)
     else:
         args = "fortunes riddles literature chucknorris pony"
     command = "/usr/games/fortune -e " + args
     output = os.popen(command).read()
     output.strip()
     toSend = output
     if 'botChannel' in self.bot.servers[msg.server.id].settings:
         botChan = getChannelById(
             self.client,
             self.bot.servers[msg.server.id].settings['botChannel'][0])
         if botChan.id != msg.channel.id:
             toSend = msg.author.mention + "\n" + toSend
         sentMsg = await sendMessage(self.client, botChan, toSend)
     else:
         sentMsg = await self.client.say(toSend)
     return
Example #2
0
    async def on_member_join(self, member):
        if member.server.id not in self.bot.servers:
            self.bot.addServer(member.server, self.bot.defaultServerSettings,
                               self.bot.defaultServerReactions)

        botChan = member.server.default_channel
        if 'botChannel' in self.bot.servers[ctx.message.server.id].settings:
            botChan = getChannelById(
                self.client,
                self.bot.servers[member.server.id].settings['botChannel'][0])

        settings = self.bot.servers[member.server.id].settings
        if 'welcomeMessage' in settings:
            reply = settings['welcomeMessage'][0]
            channel = member.server.default_channel
            if member.id is not self.client.user.id:
                data = AccessData(member, self.client.user)
                try:
                    await self.client.send_message(channel,
                                                   safe_format(reply, data))
                except AttributeError:
                    await self.client.send_message(
                        botChan,
                        "Something is fishy with this reply: `{}`".format(
                            reply))
                return
            return
Example #3
0
    async def on_message(self, msg):
        if msg.author == self.client.user or msg.author.bot:
            # Don't let the bot reply to itself and if the sender is a bot
            # then don't process that message. It could cause a loop.
            return

        # Check to see if the server is registered in the bot
        if msg.server and msg.server.id not in self.bot.servers:
            # Add a new server to the server dict.
            self.bot.addServer(msg.server, self.bot.defaultServerSettings,
                               self.bot.defaultServerReactions)
            if 'botChannel' in self.bot.servers[msg.server.id].settings:
                self.bot.servers[msg.server.id].botChannel = getChannelById(
                    self.client,
                    self.bot.servers[msg.server.id].settings["botChannel"][0])

        await self.client.process_commands(msg)

        # Server is None if the msg is a PM.
        # Use direct reference to "None" to avoid confusion
        if msg.channel.is_private:
            await handlePersonalMessage(msg, self.bot, self.client)
            return

        # If the bot was mentioned directly handle that in a special way
        if msg.content.startswith("<@{}>".format(self.client.user.id)):
            await handleBotMention(msg, self.bot, self.client)
            # We don't return afterwards because it could also be a valid
            # message for handle()

        # Make sure we don't handle a message that's a command
        if not msg.content.startswith(self.bot.botSettings['prefix']):
            await handle(msg, self.bot, self.client)
            return
Example #4
0
 async def loadMarkovError(self, error, ctx):
     botChan = ctx.message.channel
     prepend = ""
     if 'botChannel' in self.bot.servers[ctx.message.server.id].settings:
         botChan = getChannelById(
             self.client, self.bot.servers[
                 ctx.message.server.id].settings['botChannel'][0])
         if botChan.id != ctx.message.channel.id:
             prepend = ctx.message.author.mention + "\n"
     if isinstance(error, commands.CheckFailure):
         await self.client.send_message(botChan, prepend + "Sorry, you don't have the Manage Server "\
             "permission.")
         return
Example #5
0
 async def echo(self, ctx, *val: str):
     """Echo your message"""
     msg = ctx.message
     toSend = ' '.join(str(x) for x in val)
     if 'botChannel' in self.bot.servers[msg.server.id].settings:
         botChan = getChannelById(
             self.client,
             self.bot.servers[msg.server.id].settings['botChannel'][0])
         if botChan.id != msg.channel.id:
             toSend = msg.author.mention + "\n" + toSend
         sentMsg = await sendMessage(self.client, botChan, toSend)
     else:
         sentMsg = await self.client.say(toSend)
     # Add the message id to the echo message log
     self.bot.servers[msg.server.id].echoMessages[msg.id] = sentMsg
     return
Example #6
0
 async def loadMarkov(self, ctx):
     botChan = ctx.message.channel
     prepend = ""
     if 'botChannel' in self.bot.servers[ctx.message.server.id].settings:
         botChan = getChannelById(
             self.client, self.bot.servers[
                 ctx.message.server.id].settings['botChannel'][0])
         if botChan.id != ctx.message.channel.id:
             prepend = ctx.message.author.mention + "\n"
     try:
         success = await loadMarkovFromServer(ctx.message.server, self.bot,
                                              self.client)
         if success > 0:
             await self.client.send_message(
                 botChan,
                 prepend + "Success! Loaded " + str(success) + " messages.")
         elif success == 0:
             await self.client.send_message(
                 botChan, prepend + "No messages to load.")
         else:
             await self.client.send_message(
                 botChan, prepend + "Error: Markov messages not loaded.")
     except Exception as e:
         print(str(e))
Example #7
0
    async def timer(self, ctx, time=None, name=None):
        botChan = ctx.message.channel
        prepend = ""
        if 'botChannel' in self.bot.servers[ctx.message.server.id].settings:
            botChan = getChannelById(
                self.client, self.bot.servers[
                    ctx.message.server.id].settings['botChannel'][0])
            if botChan.id != ctx.message.channel.id:
                prepend = ctx.message.author.mention + "\n"
        serverId = ctx.message.server.id
        """Sets a timer. Usage: timer XhYmZs [NAME]"""
        def timerUsage():
            return ("Usage: `timer XhYmZs [NAME]`\n" +
                    "Quotes also work: \"5 minutes 30 seconds\"")

        def convertToSeconds(value, desc):
            if desc == TimeDenum.S:
                return value
            if desc == TimeDenum.M:
                return value * 60
            if desc == TimeDenum.H:
                return value * 3600

        if not time:
            await self.client.send_message(
                botChan,
                prepend + "Not enough arguments.\n{}".format(timerUsage()))
            return

        validTimes = {
            'seconds': TimeDenum.S,
            'second': TimeDenum.S,
            'sec': TimeDenum.S,
            's': TimeDenum.S,
            'min': TimeDenum.M,
            'minutes': TimeDenum.M,
            'minute': TimeDenum.M,
            'm': TimeDenum.M,
            'hours': TimeDenum.H,
            'hour': TimeDenum.H,
            'h': TimeDenum.H
        }
        callingUser = ctx.message.author.id
        timeSplit = [("".join(x)).strip()
                     for _, x in itertools.groupby(time, key=str.isdigit)]
        timeNum = 0
        try:
            timeNum = int(timeSplit[0])
        except ValueError:
            await self.client.send_message(
                botChan, prepend +
                "Unrecognized time: {}\n{}".format(time, timerUsage()))
            return
        if len(timeSplit) > 1:
            timeNum = 0
            count = 0
            add = 0
            desc = ""
            while count < len(timeSplit):
                try:
                    add = int(timeSplit[count])
                except ValueError:
                    await self.client.send_message(
                        botChan, prepend +
                        "Unrecognized time: {}\n{}".format(time, timerUsage()))
                    return
                if count + 1 < len(timeSplit):
                    desc = timeSplit[count + 1]
                    if desc.lower() in validTimes:
                        timeNum += convertToSeconds(add,
                                                    validTimes[desc.lower()])
                    else:
                        await self.client.send_message(
                            botChan, prepend +
                            "Unrecognized time multiplier: {}\n{}".format(
                                desc, timerUsage()))
                        return
                else:
                    await self.client.send_message(
                        botChan,
                        prepend + "Unexpected time termination: {}\n{}".format(
                            time, timerUsage()))
                    return
                count += 2
        # TODO: Format in more useful way
        expireTime = "{} seconds".format(timeNum)
        if not name:
            # Requires Python 3.6+
            name = ''.join(
                random.choices(string.ascii_uppercase + string.digits, k=6))
        if ('maxTimerSeconds' in self.bot.servers[serverId].settings
                and timeNum >
                self.bot.servers[serverId].settings['maxTimerSeconds'][0]):
            await self.client.send_message(
                botChan, prepend +
                "The time requested is too much. Please use a smaller number.")
            return
        await self.client.send_message(
            botChan, prepend +
            "Timer called `{}` started. It will expire in {}.".format(
                name, expireTime))
        await asyncio.sleep(timeNum)
        await self.client.send_message(
            botChan, "<@{}> Timer `{}` expired.".format(callingUser, name))
        return
async def reactToMessage(msg, bot, client):
    botChan = msg.channel
    prepend = ""
    if 'botChannel' in bot.servers[msg.server.id].settings:
        botChan = getChannelById(
            client, bot.servers[msg.server.id].settings['botChannel'][0])
        if botChan.id != msg.channel.id:
            prepend = msg.author.mention + "\n"
    for _, (reg, reply, prob) in bot.servers[msg.server.id].reactions.items():
        try:
            re.compile(reg)
        except re.error:
            await client.send_message(
                botChan, prepend +
                "Something is wrong with this regex: `{}`".format(reg))
            continue
        if re.match(reg, msg.content, re.IGNORECASE):
            if prob == 0:
                s = 1
            else:
                s = random.randint(1, prob)
            if (s == 1):
                data = AccessData(msg.author, client.user)
                try:
                    await client.send_message(
                        botChan, prepend + safe_format(reply, data))
                except AttributeError:
                    await client.send_message(
                        botChan, prepend +
                        "Something is fishy with this reply: `{}`".format(
                            reply))
                return

    if re.match(".*", msg.content, re.IGNORECASE):
        s = random.randint(0, 20000)
        if (s == 42):
            n = random.randint(1, 3)
            if (n == 1):
                await client.send_message(
                    botChan, prepend +
                    "Here's a peek behind the scenes of me, {}: <https://www.youtube.com/watch?v=dQw4w9WgXcQ>"
                    .format(client.user.name))
            if (n == 2):
                await client.send_message(
                    botChan, prepend +
                    "Perfection: <https://www.youtube.com/watch?v=dQw4w9WgXcQ>"
                )
            if (n == 3):
                await client.send_message(
                    botChan, prepend +
                    "<https://www.youtube.com/watch?v=dQw4w9WgXcQ> Obligations"
                )

    if re.match("^(grr)", msg.content, re.IGNORECASE):
        s = random.randint(0, 3)
        if (s == 1):
            await client.send_message(
                botChan, prepend + "http://i.imgur.com/FH7f5Ta.gif")
        if (s == 2):
            await client.send_message(
                botChan,
                prepend + "_{} pats you on the head_".format(client.user.name))
        return

    if re.match(
            ".*(computer|internet|server) ?.*(down|slow|broken|broke|sucks|dead)",
            msg.content, re.IGNORECASE):
        s = random.randint(0, 1)
        if (s == 1):
            # Must have the bofh-excuses installed. For Ubuntu: sudo apt-get install fortune-bofh-excuses
            output = subprocess.Popen(
                "/usr/games/fortune bofh-excuses | sed -n 3p",
                stdin=subprocess.PIPE,
                shell=True,
                stdout=subprocess.PIPE)
            await client.send_message(
                botChan,
                prepend + output.communicate()[0].decode("utf-8").strip())
        return

    if ('enable' in bot.servers[msg.server.id].settings['markov']
            and bot.servers[msg.server.id].settings['markov']['enable'][0]
            and re.match("^bot be random", msg.content, re.IGNORECASE)):
        if (bot.servers[msg.server.id].markov.line_size <
                bot.servers[msg.server.id].settings['markov']['min'][0]):
            await client.send_message(botChan, prepend + "Not enough data.")
            return
        if bot.servers[msg.server.id].markov is not None:
            text = bot.servers[msg.server.id].markov.generate_markov_text(
                random.randint(15, 40))
        await client.send_message(botChan, prepend + text)
        return
    return