Exemplo n.º 1
0
async def check():
    global client
    loop = client.loop
    streamers = config.get("picarto.streamers")
    dl_channel = client.get_channel(config.get("main.alert_id"))
    online = []

    while True:
        for streamer in streamers:
            if await is_online(streamers[streamer]):
                if streamer in online:
                    continue
                else:
                    link = "http://picarto.tv/" + streamers[streamer]
                    message = config.get("picarto.announcement") % streamer \
                        + '\n' + link
                    asyncio.ensure_future(client.send_message(
                        dl_channel, message),
                                          loop=loop)
                    #await client.send_message(chan,
                    #    config.get("picarto.announcement") % streamer + '\n' + link)
                    online.append(streamer)
            elif streamer in online:
                online.remove(streamer)
        await asyncio.sleep(config.get("picarto.delay"), loop=loop)
Exemplo n.º 2
0
 def reward(self):
     self.poll_users()
     for user in self.users:
         score.add(user, config.get('random-points'))
     c.say("Random giveaway of points! " +
           str(config.get('random-points')) + " points given to:")
     c.say(" ".join(self.users))
Exemplo n.º 3
0
def create_loggers():
    loggers = [
        'receive',
        'send',
        'action'
        ]
        
    for l in loggers:
        if config.get('chat-log'):
            logging.basicConfig(filename='chat_log.txt')

        # create logger
        logger = logging.getLogger(l)
        logger.setLevel(logging.DEBUG)
        
        # create console handler and set level to debug
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        
        if config.get('mode').lower() == 'debug':
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
        
        # create formatter
        formatter = logging.Formatter(fmt=config.get('console-format'),datefmt=Back.BLUE + config.get(l + '-format') + Back.RESET)
        
        # add formatter to console
        console.setFormatter(formatter)
        
        # add console to logger
        logger.addHandler(console)
            
        logger.debug(l + ' logger initiated.')
Exemplo n.º 4
0
def create_loggers():
    loggers = ['receive', 'send', 'action']

    for l in loggers:
        if config.get('chat-log'):
            logging.basicConfig(filename='chat_log.txt')

        # create logger
        logger = logging.getLogger(l)
        logger.setLevel(logging.DEBUG)

        # create console handler and set level to debug
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)

        if config.get('mode').lower() == 'debug':
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)

        # create formatter
        formatter = logging.Formatter(fmt=config.get('console-format'),
                                      datefmt=Back.BLUE +
                                      config.get(l + '-format') + Back.RESET)

        # add formatter to console
        console.setFormatter(formatter)

        # add console to logger
        logger.addHandler(console)

        logger.debug(l + ' logger initiated.')
Exemplo n.º 5
0
def join(nick):
    """Actions to perform on user join"""
    rank = v.getrank(nick)    
    if not v.listvar(nick) and config.get('auto-add'):
        v.makevarfile(nick)
        
    c.raw("WHOIS " + nick)
    ACC_CHECKED = False
    
    if config.get('join-message'):
        c.msg(f.LIGHTBLUE + "Welcome to the Rapid IRC, " + f.PURPLE + nick + f.LIGHTBLUE + ".", nick)
    
    if rank == 0 and config.get('auto-kick'):
        c.kick(nick, "NotWhitelisted")
        
    elif rank >= 3:
        if config.get('auto-op'):
            c.mode(["+o", nick])
            c.msg("You have been opped by Oracle", nick)
        else:
            c.msg("Oracle auto-op is disabled. Identify with NickServ to receive op.", nick)
            
    else:
        c.mode(["+v", nick])
       
    if config.get('check-mail'):
        if not m.check(nick):
            c.msg("You have no new mail.", nick)
        else:
            c.msg("You have mail! Use '?mail check' to see.", nick)
            
    log(nick + " joined. Rank: " + str(rank), m_type='JOIN', colour=Fore.MAGENTA)
Exemplo n.º 6
0
 def reward(self):
     self.poll_users()
     for user in self.users:
         score.add(user, config.get('random-points'))
     c.say("Random giveaway of points! "
         + str(config.get('random-points'))
         + " points given to:")
     c.say(" ".join(self.users))
Exemplo n.º 7
0
async def on_member_join(member):
    await client.send_message(member.server.default_channel, 
        'Welcome <@{}>! '.format(member.id) +
        'Make sure to check the rules in the ' +
        'pinned messages or <#{}>; '.format(config.get("main.welcome_id")) + 
        'tell us if you accept them and we\'ll make you '
        'a member! This will grant you ' +
        'access to all chat and discussion channels ' +
        'on the server. <@&{}>'.format(config.get("main.staff_id")))
Exemplo n.º 8
0
 def guess(self, guess, nick):
     if self.check(guess):
         c.say(f.GREEN + self.f + nick + f.WHITE + " got the answer! "
             + f.ORANGE + "+" + str(config.get('trivia-points')) + " points!")
         self.current = ""
         score.add(nick, config.get('trivia-points'))
         
     else:
         c.msg(self.f + "Incorrect!", nick)
     return True
Exemplo n.º 9
0
    def handle(self, nick, val):
        if val > config.get("kick"):
            connect.kick(nick, "Spamming")
            connect.say(f.YELLOW + "User " + f.RED + nick + f.YELLOW + " was kicked for spamming.")
            log("User: "******" was kicked for spamming", m_type="SPAMHANDLR", reset=False)
            # ACTION_LOG.info(Fore.RED + 'KCK' + Fore.RESET + ' User: '******' was kicked for spamming')
            del self.FLOOD[nick]

        elif val > config.get("warn"):
            connect.msg(f.YELLOW + "Please slow down with your messages, or else you'll be kicked.", nick)
Exemplo n.º 10
0
    def guess(self, guess, nick):
        if self.check(guess):
            c.say(f.GREEN + self.f + nick + f.WHITE + " got the answer! " +
                  f.ORANGE + "+" + str(config.get('trivia-points')) +
                  " points!")
            self.current = ""
            score.add(nick, config.get('trivia-points'))

        else:
            c.msg(self.f + "Incorrect!", nick)
        return True
Exemplo n.º 11
0
def registerExecution(jobid,
                      config,
                      conffiles,
                      job,
                      params,
                      paths,
                      status,
                      ellapsed=0.0):
    """ Register the execution of the rvt2 in a file with a timestamp.

    Attrs:
        :config: The configuration object. morgue, casename and source will be get from the DEFAULT section.
            The filename is in "rvt2:register". If filename is empty, do not register.
            If "jobname:register" is False, do not register
        :conffiles: List of extra configuration files
        :job: The name of the job
        :params: Any extra params
        :paths: The list of paths
        :status: either 'start', 'end', 'interrupted' or 'error'
        :ellapsed (float): elapsed time (in hours)
    """
    filename = config.get('rvt2', 'register', default=None)
    data = dict(_id=jobid,
                date=datetime.datetime.utcnow().isoformat(),
                cwd=os.getcwd(),
                rvthome=config.get('DEFAULT', 'rvthome'),
                conffiles=conffiles,
                morgue=config.get('DEFAULT', 'morgue'),
                casename=config.get('DEFAULT', 'casename'),
                source=config.get('DEFAULT', 'source'),
                job=job,
                params=params,
                paths=paths,
                status=status,
                logfile=base.utils.relative_path(
                    config.get('logging', 'file.logfile', None),
                    config.get('DEFAULT', 'casedir')),
                outfile=base.utils.relative_path(
                    config.get(job, 'outfile', None),
                    config.get('DEFAULT', 'casedir')),
                ellapsed=0.0)
    if status == 'start':
        data['date_start'] = data['date']
    if config.get(job, 'register', 'True') != 'False' and filename:
        # errors are ignored
        try:
            with open(filename, 'a') as f:
                f.write(json.dumps(data))
                f.write('\n')
        except Exception:
            pass
Exemplo n.º 12
0
    def __init__(self):
        if not isinstance(client, discord.Client):
            raise TypeError("provided object is not discord.Client")
        self.is_playing = False
        self.qlist = config.get("music.query")
        self.player = None
        self.voice = None
        self.state = States.STOPPED
        self.channel = client.get_channel(config.get("music.voice"))

        @client.event
        async def on_voice_state_update(before, after):
            await asyncio.sleep(1)
            await self.update()
Exemplo n.º 13
0
    def result(self):
        points = config.get('rps-points')
        strp = str(points)
        if self.g1 == "rock":
            if self.g2 == "rock":
                return "Tie!"
            elif self.g2 == "paper":
                score.add(self.p2, points)
                return self.p2 + " wins! +" + strp
            elif self.g2 == "scissors":
                score.add(self.p1, points)
                return self.p1 + " wins! +" + strp

        elif self.g1 == "paper":
            if self.g2 == "rock":
                score.add(self.p1, points)
                return self.p1 + " wins! +" + strp
            elif self.g2 == "paper":
                return "Tie!"
            elif self.g2 == "scissors":
                score.add(self.p2, points)
                return self.p2 + " wins! +" + strp

        elif self.g1 == "scissors":
            if self.g2 == "rock":
                score.add(self.p2, points)
                return self.p2 + " wins! +" + strp
            elif self.g2 == "paper":
                score.add(self.p1, points)
                return self.p1 + " wins! +" + strp
            elif self.g2 == "scissors":
                return "Tie!"

        self.done = True
        return "Somebody didn't decide!"
Exemplo n.º 14
0
 def getinfo(self):
     n = 0
     for k in self.questions:
         n += 1
     int = config.get('trivia-interval')
     return (self.f + "Time interval: " + str(int) + " seconds (" +
             str(int / 60) + " minutes), " + str(n) + " questions listed.")
Exemplo n.º 15
0
    def handle(self, nick, val):
        if val > config.get('kick'):
            connect.kick(nick, "Spamming")
            connect.say(f.YELLOW + 'User ' + f.RED + nick + f.YELLOW +
                        ' was kicked for spamming.')
            log('User: '******' was kicked for spamming',
                m_type='SPAMHANDLR',
                reset=False)
            #ACTION_LOG.info(Fore.RED + 'KCK' + Fore.RESET + ' User: '******' was kicked for spamming')
            del self.FLOOD[nick]

        elif val > config.get('warn'):
            connect.msg(
                f.YELLOW +
                'Please slow down with your messages, or else you\'ll be kicked.',
                nick)
Exemplo n.º 16
0
async def leaderboards(ctx):
    """
    Show the people who have the most karma
    """

    query = """
        SELECT receiver, SUM(delta) AS net FROM karma
        GROUP BY receiver
        ORDER BY net DESC
        LIMIT 10
        """

    if "no-anyreact" in config.get("karma"):
        query = """
            SELECT receiver, SUM(delta) AS net FROM karma
            WHERE kind != 2
            GROUP BY receiver
            ORDER BY net DESC
            LIMIT 10
            """

    top = sql.query(query)
    embed = discord.Embed(title="Top karma")
    for idx, row in enumerate(top):
        user = await resolver.fetch_user_maybe(row[0])
        if not user:
            user = f"<user id {row[0]}>"
        embed.add_field(name=f"{idx+1}. {user}", value=f"{row[1]}$")

    await ctx.send(embed=embed, delete_after=60)
Exemplo n.º 17
0
def load_plugin(pluginpath, config):
    """ Load a plugin from a path.

    Load all cfg files inside the path.
    if configuration section 'pluginame.pythonpath exists, load the python path in this section
    If funcion plugin.load_plugin() exists, run it.

    Attrs:
        :pluginpath: The absolute path to the plugin
        :config: The configuration object
    """
    name = os.path.basename(pluginpath)
    logging.debug('Loading plugin: %s from %s', name, pluginpath)
    # Add the parent path to the python path
    sys.path.insert(0, os.path.dirname(pluginpath))
    # Add any configuration file inside this directory
    config.read(pluginpath, pattern='*.cfg')
    # Set the special configuration: 'plugin:plugindir'
    config.set(name, 'plugindir', pluginpath)
    # Add any additional path defined in 'plugin:pythonpath'
    pythonpaths = base.config.parse_conf_array(
        config.get(name, 'pythonpath', ''))
    for pythonpath in pythonpaths:
        if pythonpath not in sys.path:
            logging.debug('Adding pythonpath: %s', pythonpath)
            sys.path.insert(0, pythonpath)
    # Run the function in 'plugin.load_plugin', if any
    try:
        mod = __import__(name, globals(), locals())
        if hasattr(mod, 'load_plugin'):
            mod.load_plugin(config)
    except Exception as exc:
        logging.warning('Exception loading module: %s', exc)
Exemplo n.º 18
0
async def get_karma(ctx, who: commands.UserConverter = None):
    """
    Get the amount of karma a person has.

    Karma is given by upvoting messages. This is done through reacting with
    :small_red_triangle:.
    """
    if who is None:
        who = ctx.author

    query = """
        SELECT ifnull(SUM(delta), 0) FROM karma
        WHERE receiver=?
        """

    if "no-anyreact" in config.get("karma"):
        query = """
            SELECT ifnull(SUM(delta), 0) FROM karma
            WHERE receiver=? AND kind != 2
            """

    karma = sql.query(query, who.id)
    karma = (karma[0][0] or 0) if karma else 0

    await ctx.send(f"🔶 {who} is at {karma}$", delete_after=60)
Exemplo n.º 19
0
 def result(self):
     points = config.get('rps-points')
     strp = str(points)
     if self.g1 == "rock":
         if self.g2 == "rock":
             return "Tie!"
         elif self.g2 == "paper":
             score.add(self.p2, points)
             return self.p2 + " wins! +" + strp
         elif self.g2 == "scissors":
             score.add(self.p1, points)
             return self.p1 + " wins! +" + strp
             
     elif self.g1 == "paper":
         if self.g2 == "rock":
             score.add(self.p1, points)
             return self.p1 + " wins! +" + strp
         elif self.g2 == "paper":
             return "Tie!"
         elif self.g2 == "scissors":
             score.add(self.p2, points)
             return self.p2 + " wins! +" + strp
             
     elif self.g1 == "scissors":
         if self.g2 == "rock":
             score.add(self.p2, points)
             return self.p2 + " wins! +" + strp
         elif self.g2 == "paper":
             score.add(self.p1, points)
             return self.p1 + " wins! +" + strp
         elif self.g2 == "scissors":
             return "Tie!"
             
     self.done = True        
     return "Somebody didn't decide!"
Exemplo n.º 20
0
 def __init__(self):
     self.questions = self.load_trivia()
     self.current = ""
     self.trivia_time = LoopTimeThread(config.get('trivia-interval'), self)
     self.trivia_time.start()
     self.f = f.WHITE + "[" + f.PURPLE + "Trivia" + f.WHITE + "] "
     self.disabled = False
     log("Trivia initialized.", m_type="STARTUP", colour=Fore.CYAN)
Exemplo n.º 21
0
 def __init__(self):
     self.questions = self.load_trivia()
     self.current = ""
     self.trivia_time = LoopTimeThread(config.get('trivia-interval'), self)
     self.trivia_time.start()
     self.f = f.WHITE + "[" + f.PURPLE + "Trivia" + f.WHITE + "] "
     self.disabled = False
     log("Trivia initialized.", m_type="STARTUP", colour=Fore.CYAN)
Exemplo n.º 22
0
def confirm_account(nick):
    ACC_CHECKED = True
    if config.get('use-json-whitelist'):
        if not is_white_listed(nick):
            c.say("Kicking user: "******". Reason: Not on the whitelist.")
            #c.kick(nick, "NotWhitelisted")
        else:
            c.say(nick + " is whitelisted.")
Exemplo n.º 23
0
 def getinfo(self):
     n = 0
     for k in self.questions:
         n += 1
     int = config.get('trivia-interval')
     return (self.f
             + "Time interval: " + str(int)
             + " seconds (" + str(int/60) + " minutes), "
             + str(n) + " questions listed.")
Exemplo n.º 24
0
def get():
    try:
        xmldoc = minidom.parse(urllib.urlopen(config.get('events-list')))
        dname = xmldoc.getElementsByTagName('name')[0]
        dtime = xmldoc.getElementsByTagName('timestamp')[0]
        u_time = getText(dtime.childNodes)
        p_name = getText(dname.childNodes)
        utc_time = time.ctime(int(u_time))
        return p_name, str(utc_time)
        
    except Exception:
        return False
Exemplo n.º 25
0
 def _runnable(self):
     nick = 'Oracle'
     while True:
         msg = replace(raw_input())
         cmd = False
         for char in config.get('command-chars'):
                 if msg.startswith(char):
                     # make sure to only get rid of one '?'
                     msg = msg.split(char, 1)[1]
                     oracle.process_cmd(nick, msg)
                     cmd = True
         if not cmd:
             say(msg)
Exemplo n.º 26
0
 def _runnable(self):
     nick = "Oracle"
     while True:
         msg = replace(raw_input())
         cmd = False
         for char in config.get("command-chars"):
             if msg.startswith(char):
                 # make sure to only get rid of one '?'
                 msg = msg.split(char, 1)[1]
                 oracle.process_cmd(nick, msg)
                 cmd = True
         if not cmd:
             say(msg)
Exemplo n.º 27
0
 async def play(self):
     opts = {"buffersize": "16k", "format": "bestaudio/worst"}
     self.player = await self.voice.create_ytdl_player(self.qlist[0],
                                                       ytdl_options=opts)
     self.player.after = self.next
     self.player.start()
     self.is_playing = True
     self.state = States.PLAYING
     chan = client.get_channel(config.get("music.channel"))
     await util.send_message(
         chan,
         "Now playing: " + self.player.title + "\n <%s>" % self.player.url)
     config.set("music.query", self.qlist)
Exemplo n.º 28
0
async def do():
    global force, client
    # global counter
    
    while True:
        for y in range(len(config.get("rss.feeds"))):
            # get current link
            x = config.get("rss.feeds")[y]
            #print(x)
            d = feedparser.parse(x["url"])
            try:
                d.entries[0]
            except IndexError:
                print("Index Error with entries reached.\n")
                return
            try:
                d.entries[0].links[0]
            except IndexError:
                print("Index Error with links reached.\n")
                return
            post = d.entries[0].links[0].href
            summary = d.entries[0].summary
            image_link = urllib.parse.quote(summary[summary.find("src")+5:summary.find("\"", summary.find("src")+5)], [47, 58])
            # check and post the update
            if (x["last"] != post) or force:
                image = discord.Embed().set_image(url=image_link)
                message = x['message'] + "\n" + post
                dl_channel = client.get_channel(config.get("main.alert_id"))
                await client.send_message(dl_channel, message, embed=image)
            # update config file
            config.set("rss.feeds.%s.last" % y, post)
            force = 0
        # print("%d"%counter)
        # counter += 1
        for _ in range(config.get("rss.delay")):
            await asyncio.sleep(1, loop=client.loop)
            if force:
                break
Exemplo n.º 29
0
def cb(ask, nick):
    """Asks cleverbot a question, and logs
    and says the response (broken).
    
    Cleverbot API has been discontinued
    and so this will probably no longer work.
    """
    if config.get('cleverbot'):
        cbot = cleverbot.Session()
        response = cbot.Ask(" ".join(ask))
        ACTION_LOG.info(Fore.CYAN + "CBT" + Fore.RESET + " " + response)
        c.say(nick + ": " + response)
    else:
        c.msg("Cleverbot is currently disabled.", nick)
Exemplo n.º 30
0
def is_white_listed(nick):
    """Check if a user is whitelisted through
    Jake's MetisWeb database
    """
    try:
        content = urllib.urlopen(config.get('whitelist-location'))
        data = json.load(content)
        #print data
        for name in data:
            ACTION_LOG.info(name)
            if name == nick:
                return True
        return False
    except:
        traceback.print_exc()
        return False
Exemplo n.º 31
0
def configure_logging(config, verbose=False, jobname=None):
    """ Configure the logging subsystem.

    Attrs:
        verbose (boolean): If true, set the logging to verbose regardless what the configuration says.
        jobname (String): The name of the job to be run. If None, use basic configuration.
            If the job defines in its section `register: False`, use basic configuration.
    """
    if verbose:
        config.config['logging']['console.level'] = 'DEBUG'
    if jobname is None or config.get(jobname, 'register',
                                     'True').upper() == 'FALSE':
        base.config.configure_logging(config, basic=True)
    else:
        try:
            base.config.configure_logging(config)
        except Exception as exc:
            # after an exception, configure the basic logging system
            base.config.configure_logging(config, basic=True)
            logging.error('Couldn\'t configure the logging system: %s', exc)
Exemplo n.º 32
0
def start():    
    try:
        global s
        s = socket.socket()
        s.connect((config.get('host'), config.get('port')))
        _send_irc("NICK "
                + config.get('nick')
                + "\r\n")
        _send_irc("USER "
                + config.get('ident') + " " + config.get('host')
                + " bla :" + config.get('realname')
                + "\r\n")
        return s
    except Exception:
        traceback.print_exc()
        log("Could not connect to server.", m_type="WARNING", colour=Fore.RED, reset=False)
        return False
Exemplo n.º 33
0
async def on_message(message):
    if message.channel.id != config.get("music.channel"):
        return
    if len(message.embeds) > 0:
        await check(message)
        for embed in message.embeds:
            await query.add(embed["url"])
        return
    urls = []
    for url in message.clean_content.split(" "):
        if is_valid(url):
            urls.append(url)
    print(message.clean_content)
    print(message.content)
    if len(urls) > 0:
        await check(message)
        for url in urls:
            await query.add(url)
        return
    if len(message.attachments) > 0:
        await check(message)
        for attach in message.attachments:
            await query.add(attach["url"])
        return
Exemplo n.º 34
0
def process_cmd(nick, msg):    
    """Splits the message, processes the
    commands and does all the relevant
    functions required.
    
    Should reverse the 'rank' if 
    statements but it's not much of
    a problem.
    """
    cmd = msg.split(" ")
    rank = v.getrank(nick)
    if len(cmd) == 1:
        log("*" + cmd[0].capitalize() + "* | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | nick: " + nick)
    else:
        log("*" + cmd[0].capitalize() + "* | args: " + " ".join(cmd[1:]) + " | nick: " + nick, m_type="COMMAND", colour=Fore.CYAN)
        #ACTION_LOG.info(Fore.MAGENTA + "COMMAND " + Fore.RESET + " " + cmd[0] + " | args: " + " ".join(cmd[1:]) + " | nick: " + nick)
    
    try:
        # regular user
        # rank = 1
        if rank >= 1:
            #! emotes !#
            if cmd[0] == "fliptable": c.say("(╯°□°)╯︵ ┻━┻")
            elif cmd[0] == "puttableback": c.say("┬─┬ ノ( ゜-゜ノ)")
            elif cmd[0] == "ohyou": c.say("¯_(ツ)_/¯")
            elif cmd[0] == "FLIPTABLE": c.say("(ノಠ益ಠ)ノ彡┻━┻")
            elif cmd[0] == "fff": c.say("ლ(ಠ益ಠლ)")
            elif cmd[0] == "disapprove": c.say("ಠ_ಠ")
            elif cmd[0] == "crie": c.say("ಥ_ಥ")
            elif cmd[0] == "lenny": c.say("( ͡° ͜ʖ ͡°)")
            elif cmd[0] == "dongers": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "raise": c.say("ヽ༼ຈل͜ຈ༽ノ")
            elif cmd[0] == "butterfly": c.say("Ƹ̵̡Ӝ̵̨̄Ʒ")
            elif cmd[0] == "partytime": c.say("┏(-_-)┛┗(-_- )┓┗(-_-)┛┏(-_-)┓")
            elif cmd[0] == "fliptables": c.say("┻━┻︵ \(°□°)/ ︵ ┻━┻")
            elif cmd[0] == "polarbear": c.say("ˁ˚ᴥ˚ˀ")
            elif cmd[0] == "gun": c.say("︻╦╤─")
            elif cmd[0] == "pirate": c.say("✌(◕‿-)✌")
            elif cmd[0] == "happybirthday": c.say("¸¸♬·¯·♩¸¸♪·¯·♫¸¸Happy Birthday To You¸¸♬·¯·♩¸¸♪·¯·♫¸¸")
            elif cmd[0] == "sunglasses": c.say("( •_•) ( •_•)>⌐■-■ (⌐■_■)")
            elif cmd[0] == "rage": c.say("t(ಠ益ಠt)")
            elif cmd[0] == "cards": c.say("[♥]]] [♦]]] [♣]]] [♠]]]")
            elif cmd[0] == "gimme": c.say("༼ つ ◕_◕ ༽つ")
            elif cmd[0] == "monocle": c.say("ಠ_ರೃ")
            elif cmd[0] == "ghost": c.say("‹’’›(Ͼ˳Ͽ)‹’’›")
            elif cmd[0] == "why": c.say("ლ(`◉◞౪◟◉‵ლ)")
            elif cmd[0] == "praise": c.say("し(*・∀・)/♡\(・∀・*)ノ")
            elif cmd[0] == "lennyy": c.say(" ̿̿ ̿̿ ̿̿ ̿'̿'\̵͇̿̿\з=( ͡° ͜ʖ ͡°)=ε/̵͇̿̿/’̿’̿ ̿ ̿̿ ̿̿ ̿̿ ")
            # tears can be potentially dangerous, limited to admin +
            elif cmd[0] == "tears" and rank >= 3: c.say(" Ỏ̷͖͈̞̩͎̻̫̫̜͉̠̫͕̭̭̫̫̹̗̹͈̼̠̖͍͚̥͈̮̼͕̠̤̯̻̥̬̗̼̳̤̳̬̪̹͚̞̼̠͕̼̠̦͚̫͔̯̹͉͉̘͎͕̼̣̝͙̱̟̹̩̟̳̦̭͉̮̖̭̣̣̞̙̗̜̺̭̻̥͚͙̝̦̲̱͉͖͉̰̦͎̫̣̼͎͍̠̮͓̹̹͉̤̰̗̙͕͇͔̱͕̭͈̳̗̭͔̘̖̺̮̜̠͖̘͓̳͕̟̠̱̫̤͓͔̘̰̲͙͍͇̙͎̣̼̗̖͙̯͉̠̟͈͍͕̪͓̝̩̦̖̹̼̠̘̮͚̟͉̺̜͍͓̯̳̱̻͕̣̳͉̻̭̭̱͍̪̩̭̺͕̺̼̥̪͖̦̟͎̻̰_á»")
            
            #! other !#
            elif cmd[0] == "rps":
                target = cmd[1]
                global rps
                rps = games.RockPaperScissors(nick, target)
                c.msg(nick + " has challenged you to a game of rock, paper scissors.", target)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", target)
                c.msg("You have 30 seconds.", target)
                c.msg("You have challenged " + target + " to a game of rock, paper scissors.", nick)
                c.msg("To participate, use " + f.BLUE + "/msg Oracle ?[rock/paper/scissors] (use /imsg if you're in-game)", nick)
                c.msg("You have 30 seconds.", nick)
                
            
            elif cmd[0] == "rock" or cmd[0] == "paper" or cmd[0] == "scissors":
                if rps != None:
                    if rps.guess(cmd[0], nick):
                        c.msg("Decision accepted", nick)
                        c.msg("Your opponent has made a decision", rps.get_opponent(nick))
                    else:
                        c.msg("You're not in this RPS game!", nick)
                else:
                    c.msg("There is no RPS game at the moment.", nick)
                    
            elif cmd[0] == "a":
                global trivia
                trivia.guess(cmd[1:], nick)
            
            elif cmd[0] == "help" or cmd[0] == "what":
                if(len(cmd) < 2): help_(nick, "no")
                else: help_(nick, cmd[1])
                
            elif cmd[0] == "cb": cb(cmd[1:], nick)
            
            elif cmd[0] == "pick":
                c.say(nick + ": " + misc.pick(cmd[1:]))
                
            elif cmd[0] == "diamonds":
                if config.get('rick-roll'):
                    gags.rick_roll(nick, cmd[1])
                else:
                    c.msg(f.WHITE + "64 diamonds have been credited to the Minecraft account " + f.RED + nick + f.WHITE + ".", nick)
                    time.sleep(5)
                    c.msg("Just kidding.", nick)
                    c.msg("This command has been disabled in the config.", nick)
                    
            elif cmd[0] == "ayylmao":
                c.say("http://puu.sh/6wo5D.png")
                
            elif cmd[0] == "score":
                if cmd[1] == "check":
                    if len(cmd) > 2 and rank >= 3:
                        c.msg(cmd[2] + " has " + str(score.get(cmd[2])) + " points.", nick)
                    else:
                        c.msg("Your have " + str(score.get(nick)) + " points.", nick)
                elif cmd[1] == "top":                        
                    list = score.get_leader_boards()
                    amount = int(cmd[2]) if len(cmd) > 2 else 5
                    i = 1
                    for line in list:
                        c.msg(str(i) + ". " + line[0] + " - " + str(line[1]), nick)
                        i += 1
                        if i > amount:
                            break
                            
            elif cmd[0] == "resolve":
                data = socket.gethostbyname_ex(" ".join(cmd[1:]))
                c.say(" ".join(cmd[1:]) + " resolved to " + repr(data[2]))
                
            #! server !#
            elif cmd[0] == "events":
                results = e.get()
                
                if results:
                    c.say(f.BOLD + "Event: " + results[0] + " || " + f.BOLD + "Time" + f.BOLD + ": " + results[1] + " UTC")
                else:
                    c.say(f.BOLD + "No events found" + f.BOLD + " - there may be none planned.")
                    
            elif cmd[0] == "utc":
                c.say(e.utc() + " UTC")
                
            elif cmd[0] == "nether":
                c.msg(misc.netherposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
                
            elif cmd[0] == "overworld":
                c.msg(misc.overworldposition(int(cmd[1]), int(cmd[2]), int(cmd[3])), nick)
      
            #! personal !#
            elif cmd[0] == "mail":
                try:
                    if cmd[1].lower() == "check":
                        if not m.check(nick):
                            c.msg("You have no mail.", nick)
                        else:
                            c.msg("Use ?mail read [mail]: "+ ", ".join(m.check(nick)), nick)
                            
                    elif cmd[1].lower() == "send":
                        text = " ".join(cmd[4:])
                        if m.send(nick, cmd[2], cmd[3], text):
                            c.msg("Message sent.", nick)
                        else:
                            c.msg("Message failed to send.", nick)
                            
                    elif cmd[1].lower() == "read":
                        c.msg(m.read(nick, cmd[2]), nick)
                        
                    elif cmd[1].lower() == "delete" or cmd[1].lower() == "del":
                        if m.delete(nick, cmd[2]):
                            c.msg("Message deleted.", nick)
                        else:
                            c.msg("Message not deleted.", nick)
                            
                    else:
                        c.msg("Usage: ?mail [check|send|read|delete]", nick)
                        
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?mail [check|send|read|delete]", nick)
                    
            elif cmd[0] == "notes":
                try:
                    if cmd[1].lower() == "new":
                        text = " ".join(cmd[3:])
                        if n.new(cmd[2], text):
                            c.msg("Note successfully created.", nick)
                        else:
                            c.msg("Note already exists with that file name", nick)
                            
                    elif cmd[1].lower() == "delete":
                        if n.delete(cmd[2]):
                            c.msg("Note successfully deleted.", nick)
                        else:
                            c.msg("Deletion failed", nick)
                            
                    elif cmd[1].lower() == "edit":
                        text = " ".join(cmd[3:])
                        n.edit(cmd[2], text[1])
                        
                    elif cmd[1].lower() == "listall":
                        c.msg(" ".join(n.listall()), nick)
                        
                    elif cmd[1].lower() == "search" or cmd[1].lower() == "list":
                        c.msg(" ".join(n.find(cmd[2])), nick)
                        
                    elif cmd[1].lower() == "get":
                        c.msg(nick + ": " + n.get(cmd[2]), nick)
                        
                    else:
                        c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                except:
                    traceback.print_exc()
                    c.msg("Usage: ?notes [new|delete|edit|listall|search|get]", nick)
                    
            elif cmd[0] == "eval":
                try:
                    sm = " ".join(cmd[1:])
                    c.say(sm + " = " + str(eval(sm)))
                except:
                    traceback.print_exc()
        else:
            c.msg("Seems like you don't have access to these commands. Message an admin for help.", nick)
            
        #! moderator !#
        # rank = 2
        if rank >= 2:
            if cmd[0] == "say":
                c.say(format.replace(" ".join(cmd[1:])))
            
            elif cmd[0] == "ATTENTION":
                global ATTENTION
                ATTENTION = True
                c.getusers()
                
            elif cmd[0] == "ban" :
                v.setvar(nick, cmd[1], "rank", 0)
                c.msg("User: "******" has been banned.", nick)
                
            elif cmd[0] == "kick":
                if len(cmd) < 3:
                    c.kick(cmd[1], "")
                    c.msg("User kicked.", nick)
                else:
                    c.kick(cmd[1], " ".join(cmd[2:]))
                    c.msg("User kicked for " + " ".join(cmd[2:]) + ".", nick)
        
        #! admin !#
        # rank = 3
        if rank >= 3:
            if cmd[0] == "close":
                c.stop(nick)
                EXIT = True
                
            elif cmd[0] == "restart" :
                c.restart(nick)
                
            elif cmd[0] == "reload":
                log("Reload issued by " + nick, m_type="RELOAD", colour=Fore.YELLOW, reset=False)
                reload_()
                c.say(f.YELLOW + "Reload complete.")
                
            elif cmd[0] == "sreload":
                reload_()
                c.msg(f.YELLOW + "Silent reload complete.", nick)
                
            elif cmd[0] == "setrank":
                v.setvar(cmd[1], "rank", int(cmd[2]))
                c.msg(cmd[1] + "'s rank set to " + cmd[2] + ".", nick)
                
            elif cmd[0] == "mode":
                c.mode(cmd[1:])
                
            elif cmd[0] == "getrank":
                c.msg(cmd[1] + "'s rank is " + str(v.getvar(cmd[1], "rank")) + ".", nick)
                
            elif cmd[0] == "flood":
                if cmd[1] == "reset":
                    spam.clear()
                    c.msg("Cleared FLOOD dictionary", nick)
                elif cmd[1] == "decrement":
                    spam.decrement()
                    c.msg("FLOOD decrement performed", nick)
                    
            elif cmd[0] == "randompoints":
                if cmd[1] == "run":
                    randompoints.poll_users()
                    time.sleep(1)
                    randompoints.reward()
                
            elif cmd[0] == "trivia":
                if cmd[1] == "new":
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] New round started by " + f.BLUE + nick)
                    trivia._runnable()
                elif cmd[1] == "off":
                    trivia.disable()
                    c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Disabled by " + f.BLUE + nick)
                elif cmd[1] == "on":
                    if trivia._getdisabled():  
                        del trivia
                        trivia = games.trivia()
                        c.say("[" + f.PURPLE + "Trivia" + f.WHITE + "] Re-enabled by " + f.BLUE + nick)
                elif cmd[1] == "info":
                    c.msg(trivia.getinfo(), nick)
                    
            elif cmd[0] == "score":
                if cmd[1] == "reset":
                    if score.reset(cmd[2]):
                        c.msg("Successfully reset " + cmd[2] + "'s score.", nick)
                    else:
                        c.msg("Reset failed.", nick)
                elif cmd[1] == "add":
                    points = score.add(cmd[2], cmd[3])
                    if not points:
                        c.msg("Points failed to add.", nick)
                    else:
                        c.msg("Sucessfully added points, " + cmd[2] + " now has " + str(points) + " points.", nick)
                        
            elif cmd[0] == "ignore":
                try:
                    IGNORE_LIST.append(cmd[1])
                    c.msg("Successfuly added " + cmd[1] + " to ignore list.", nick)
                except:
                    c.msg("Ignore unsuccessful.", nick)
                
            elif cmd[0] == "pardon":
                try:
                    del ingore_list[cmd[1]]
                    c.msg("Successfully pardoned " + cmd[1] + ".", nick)
                except:
                    c.msg("Pardon unsuccessful. Perhaps " + cmd[1] + " is not currently being ignored.", nick)
                        
        #! developer !#
        # rank = 4
        if rank >= 4:
            if cmd[0] == "makevar":
                target = cmd[1]
                
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "getvar":
                response = v.getvar( cmd[1], cmd[2])
                c.msg("VAR: %s = %s" % (cmd[2], response),nick)
                    
            elif cmd[0] == "listvar":
                response = v.listvar(cmd[1])
                c.msg(response, nick)
                
            elif cmd[0] == "setvar":
                if(v.setvar(cmd[1], cmd[2], int(cmd[3]))):
                    c.msg("VAR: %s set to %s for %s" % (cmd[2], cmd[3], cmd[1]), nick)
                else:
                    c.msg("Setting of variable failed.", nick)
                    
            elif cmd[0] == "deletevar":
                if(v.deletevarfile(cmd[1])):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.", nick)
                
            elif cmd[0] == "resetvar":
                target = cmd[1]
                
                if(v.deletevarfile(target)):
                    c.msg("VAR file successfully deleted.", nick)
                else:
                    c.msg("VAR file deletion failed.")
                    
                if(v.makevarfile(target)):
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - New var file created for " + target + " by " + nick)
                    c.msg("VAR file successfully created for " + target, nick)
                else:
                    ACTION_LOG.info(Fore.RED + "!!!" + Fore.RESET + " - Var file creation failed - " + nick)
                    c.msg("VAR file failed to create for " + target, nick)
                    
            elif cmd[0] == "formats" :
                c.say(vars(f))
                    
            elif cmd[0] == "cls":
                os.system("cls")
                
            elif cmd[0] == "join":
                join(nick)
                
            elif cmd[0] == "joinn":
                join(cmd[1])
                
            elif cmd[0] == "raw":
                c.raw(cmd[1:])
                
            elif cmd[0] == "config":
                if cmd[1] == "reload":
                    try:
                        config.reload()
                        c.msg("Config reloaded.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error reloading config", nick)
                elif cmd[1] == "set":
                    try:
                        config.set(cmd[2], cmd[3:])
                        c.msg("Config set.", nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error setting config", nick)
                elif cmd[1] == "get":
                    try:
                        c.msg(config.get(cmd[2]), nick)
                    except:
                        traceback.print_exc()
                        c.msg("Error getting config", nick)
                        
            elif cmd[0] == "testlog":
                log("No string test")
                log("Action test", l_type='action', m_type="TESTLOG", colour=Fore.GREEN)
                if len(cmd) > 1:
                    log(' '.join(cmd[1:]), colour=Fore.GREEN, m_type="TESTLOG")
                    
            elif cmd[0] == "exec":
                try:
                    exec " ".join(cmd[1:])
                except:
                    c.say(traceback.print_exc())
                        
    except SystemExit:
        return
        
    except:
        # any and every error will throw this
        traceback.print_exc()
        c.msg("Oops! Something went wrong. Please contact an admin for help.",nick)
Exemplo n.º 35
0
def getusers():
    return _send_irc("NAMES "
                    + config.get('channel')
                    + "\r\n")
Exemplo n.º 36
0
from base.backend import mailer
from base.utils import to_unicode, today
from base import config

from . import accounting

"""
There four notify method:

    - `DEBUG`: 所有通知邮件将会以同步执行的方式,发送至
               `DEFAULT_DEBUG_NOTIFY_RECEIVER` 所指定的收件人。
    - `SYNC`: 通过同步执行的方式发送邮件。
    - `MOCK`: 不会发送任何邮件,但会产生一条邮件发送记录。
    - ``
"""
__ = config.get("mailing.default_notify_method", "MOCK").upper()
if __ not in ("DEBUG", "SYNC", "MOCK"):
    __ = "MOCK"
DEFAULT_NOTIFY_METHOD = __
DEFAULT_DEBUG_NOTIFY_RECEIVER = config.get("mailing.debug_notify_receiver", "*****@*****.**")


def check_health():
    statuses = []
    # 发信方式检查
    if mailer.DEFAULT_MAILER == "simple_smtp":
        statuses.append({
            "heading": "不可控的发信方式",
            "body": "当前所用的邮件发送方式并不能保证用户能够正常收取邮件!",
            "code": "unstable_mailer",
            "html_class": "alert alert-block",
Exemplo n.º 37
0
def kick(nick, reason):
    return _send_irc("KICK "
                    + config.get('channel') + nick + reason
                    + "\r\n")
Exemplo n.º 38
0
def say(msg):
    return _send_irc("PRIVMSG "
                    + str(config.get('channel')) + " :" + str(msg)
                    + "\r\n")
Exemplo n.º 39
0
 def sleep(self):
     interval = random.randint(  config.get('random-min-interval'),
                                 config.get('random-max-interval'))
     time.sleep(interval)
Exemplo n.º 40
0
def identify():
    return _send_irc("nickserv IDENTIFY Oracle "
                    + config.get('pass')
                    + "\r\n")
Exemplo n.º 41
0
 def __init__(self):
     self.FLOOD = {}
     self.last_msg = ""
     self.thread = LoopTimeThread(config.get("interval"), self)
     self.thread.start()
     self.disabled = False
Exemplo n.º 42
0
# coding=UTF-8


# from mongokit import Document, CustomType
from mongokit import *
from bson.objectid import InvalidId

import datetime

from base import config

from base.backend.model import datamanager

MongoDB_Default_Database = config.get('mongodb.database')

#try:
#    from apps.data_layer.settings import MongoDB_Default_Database
#except Exception, e:
#    from settings import MongoDB_Default_Database


def object_id(obj_id):
    if type(obj_id) is ObjectId:
        return obj_id
    try:
        return ObjectId(obj_id)
    except InvalidId:
        return None


class ModelBase(Document):
Exemplo n.º 43
0
def join():
    return _send_irc("JOIN "
                    + config.get('channel')
                    + "\r\n")
Exemplo n.º 44
0
def main(params=sys.argv[1:]):
    """ The entry point of the system. Run from the command line and get help using --help.

    Read configuration files and run jobs.

    Attrs:
        :params: The parameters to configure the system
    """
    aparser = argparse.ArgumentParser(description='Script para...')
    aparser.add_argument(
        '-c',
        '--config',
        help=
        'Configuration file. Can be provided multiple times and configuration is appended',
        action='append')
    aparser.add_argument('-v',
                         '--verbose',
                         help='Outputs debug messages to the standard output',
                         action='store_true',
                         default=False)
    aparser.add_argument('-p',
                         '--print',
                         help='Print the results of the job as JSON',
                         action='store_true',
                         default=False)
    aparser.add_argument(
        '--params',
        help="Additional parameters to the job, as PARAM=VALUE",
        action=StoreDict,
        nargs='*',
        default={})
    aparser.add_argument(
        '-j',
        '--job',
        help='Section name in the configuration file for the main job.',
        default=None)
    aparser.add_argument(
        '--morgue',
        help=
        'If provided, ovewrite the value of the morgue variable in the DEFAULT section of the configuration',
        default=None)
    aparser.add_argument(
        '--casename',
        help=
        'If provided, ovewrite the value of the casename variable in the DEFAULT section of the configuration',
        default=None)
    aparser.add_argument(
        '--source',
        help=
        'If provided, ovewrite the value of the source variable in the DEFAULT section of the configuration',
        default=None)
    aparser.add_argument('paths',
                         type=str,
                         nargs='*',
                         help='Filename or directories to parse')
    args = aparser.parse_args(params)

    jobid = str(base.utils.generate_id())

    # read configuration from one or more -c options
    config = base.config.Config()
    load_configpaths(config, args.config)
    load_default_vars(config, args.morgue, args.casename, args.source, jobid)

    # configure the logging subsystem using a generic configuration
    configure_logging(config, args.verbose, None)
    # NOW we can log the configuration files, since the logging system is already up
    logging.debug('Configuration files: %s', args.config)

    # Load additional pythonpath
    for pythonpath in base.config.parse_conf_array(
            config.get('rvt2', 'pythonpath', '')):
        logging.debug('Loading pythonpath: %s', pythonpath)
        sys.path.insert(0, pythonpath)
    logging.debug('Pythonpath: %s', sys.path)
    # Load additional plugins directories
    for pluginspath in base.config.parse_conf_array(
            config.get('rvt2', 'plugins', '')):
        load_plugin(pluginspath, config)

    # read again configuration from one or more -c options. They MUST overwrite the configuration of the plugins
    load_configpaths(config, args.config)
    # configure default variables again. They MUST overwrite the configuration of the conf files
    load_default_vars(config, args.morgue, args.casename, args.source, jobid)

    # configure the job: if there is a Main section, use it. Else, get the default job from configuration rvt2.default_job
    if args.job is None:
        if config.has_section('Main'):
            args.job = 'Main'
        else:
            args.job = config.get('rvt2', 'default_job')

    # reload the logging system, using the configuration specific for the job
    configure_logging(config, args.verbose, args.job)

    # run job
    jobstarted = datetime.datetime.now()
    registerExecution(jobid, config, args.config, args.job, args.params,
                      args.paths, 'start')
    try:
        for results in base.job.run_job(config,
                                        args.job,
                                        args.paths,
                                        extra_config=args.params):
            if args.print:
                print(json.dumps(results))
        registerExecution(jobid, config, args.config, args.job, args.params,
                          args.paths, 'end',
                          (datetime.datetime.now() - jobstarted) / 3600)
    except KeyboardInterrupt:
        registerExecution(jobid, config, args.config, args.job, args.params,
                          args.paths, 'interrupted',
                          (datetime.datetime.now() - jobstarted) / 3600)
    except Exception:
        registerExecution(jobid, config, args.config, args.job, args.params,
                          args.paths, 'error',
                          (datetime.datetime.now() - jobstarted) / 3600)
        raise
Exemplo n.º 45
0
def main(socket):
    """Main loop, everything happens through this loop
    Data received from s is placed in the readbuffer,
    which is then split into lines that are iterated
    over as incoming messages.
    
    Returning false will close Oracle, and true will
    reload oracle.py
    """   
    readbuffer = ""
    
    global RELOAD
    global EXIT
    RELOAD = EXIT = False
    
    if config.get('trivia'):
        global trivia
        trivia = games.Trivia()
        
    if config.get('command-line'):
        global commandline
        commandline = input.CommandLine()
        
    if config.get('random-points'):
        global randompoints
        randompoints = games.RandomPoints()
        
    
    while True:
        try:
            # get messages from the server
            readbuffer = readbuffer + socket.recv(1024)
        except Exception:
            # this only happens when the server throttles the connection
            log("Cannot connect, throttled by server.", m_type="WARNING", colour=Fore.RED, reset=False)
            log("Will try again in 20 seconds...", m_type="WARNING", colour=Fore.RED, reset=False)
            time.sleep(20)
            # reloads the bot, rather than exit
            return True
            
        temp = string.split(readbuffer, "\n")
        readbuffer = temp.pop()

        for line in temp:
            line = string.split(string.rstrip(line))
            message = " ".join(line)
                 
            # reply to every periodic PING event
            if(line[0] == "PING"): 
                c.ping(line[1])
                
            # join the channel
            elif(line[1] == "376" and line[2] == config.get('ident')): 
                c.join()
                
            # identify with nickserv after being prompted
            elif("NickServ!" in line[0] and line[4] == "nickname"):
                c.identify()
                log("Identified with NickServ", m_type="NICKSERV", colour=Fore.GREEN)
                #ACTION_LOG.info(Style.BRIGHT + Fore.CYAN + "IDENTIFY " + Fore.WHITE + "Identified")
                
            # return of NAMES list
            elif(line[1] == "353"): 
                nicks = "".join(message.split(":")[2].replace("@","").replace("+","").replace("Oracle ",""))
                global ATTENTION
                if ATTENTION:
                    c.say(nicks)
                    ATTENTION = False
                users = nicks.replace(config.get('server-bots')[0],"").replace(config.get('server-bots')[1],"")
                if config.get('random-points'):
                    randompoints.add_users(users)
                
            # realise that Orace just joined, say welcome
            elif("JOIN" in line) and ("Oracle" in message):
                # if welcome-message == false
                if not config.get('welcome-message'):
                    pass
                else:
                    c.say(format.replace(config.get('welcome-message')))
                
            # throw nick to join() after they join
            elif ("JOIN" in line or ":JOIN" in line) and not ("Oracle" in message):
                join(line[0].split(":",1)[1].split("!",1)[0])
            
            # possible 'line(s)'
            # ':[email protected]', 'PRIVMSG', '#rapid', ': [message]'
            # ':[email protected]', 'PRIVMSG', 'Oracle', ': [message]'
            # ':nova.esper.net', 'NOTICE', '*' ':***', 'foo', 'is', 'bar'
            # 'PING', ':nova.esper.net'
            # ':[email protected]', 'MODE', '#rapid', '+o', 'Oracle'
            # ':nova.esper.net', '001', 'Oracle', '[thing]'
            
            if (len(line) > 2):     
                # grab nick from first string in line
                # grab message from fourth string onwards
                try:
                    nick = line[0].replace(":","").split("!",1)[0]
                    msg = " ".join(line[3:]).replace(":","",1)
                except:
                    nick = "null"
                    break
					
                id = None
                if nick.endswith('.esper.net'):
                    id = "ESPERNET"
                elif nick.lower() == ('nickserv'):
                    id = "NICKSERV"
                elif nick.lower() == ('chanserv'):
                    id = "CHANSERV"
                
                if id is not None:
                    log(msg, m_type=id, colour=Fore.GREEN, lg='receive')
                    #RECEIVE_LOG.info(Style.BRIGHT + Fore.GREEN + id + " " + Fore.RESET + msg)
                elif nick.lower() is not 'oracle':
                    log("<" + nick + "> " + msg, m_type="MESSAGE", colour=Fore.MAGENTA, lg='receive')
                    #RECEIVE_LOG.info(Style.BRIGHT + Fore.MAGENTA + "MESSAGE " + Fore.RESET + " <" + nick + "> " + msg)
            else:
                # the message is bad
                break
                
            # reply from WHOIS
            if "is logged in as" in msg and ".esper.net" in nick:
                confirm_account(msg.split(" ",2)[1])
                
            # reset variable that tells connect if it is a
            # message from a server bot
            if c.getactive():
                c.set_inactive()
            
            # throw msg and nick to spamhandler
            if config.get('spam-handler'):
                global spam
                if spam == None:
                    spam = spamhandler.Handler()
                sh = True
                for bot in config.get('server-bots'):
                    if nick == bot:
                        sh = False
                if nick == config.get('nick'):
                    sh = False
                elif nick.lower() == 'nickserv' or nick.lower() == 'chanserv':
                    sh = False
                if sh:
                    spam.increment(nick, msg) 
                
            # ignore list doesn't work properly, but meh
            if not nick in IGNORE_LIST or nick == 'Toofifty':
                # check if the nick is one of the RapidIRC bots
                # change nick and msg accordingly
                for bot in config.get('server-bots'):
                    if nick == bot:
                        try:
                            if msg.startswith("<"):
                                nick, msg = msg.split("<",1)[1].split("> ",1)
                                c.set_active(bot)
                                
                            elif msg.split(" ")[1] == "whispers":
                                nick, msg = msg.split(" whispers ", 1)
                                c.set_active(bot)
                                
                            elif msg.startswith("Online Players:"):
                                users = msg.replace("Online Players:", "")
                                if not users == "":
                                    randompoints.add_users(users)
                        except IndexError:
                            pass
                                    
                # handle sudo commands
                if msg.startswith(str(config.get('sudo-char'))) and v.getrank(nick) >= 4:
                    msg = msg.replace(config.get('sudo-char'),"")
                    nick, msg = msg.split(" ",1)

                # identify commands from msg
                for char in config.get('command-chars'):
                    if msg.startswith(char):
                        # make sure to only get rid of one '?'
                        msg = msg.split(char, 1)[1]
                        process_cmd(nick, msg)

                # throw msg to translator
                if config.get('translate'):
                    if translate.requires_translate(msg):
                        ACTION_LOG.info("TRN Translating...")
                        c.say("I think you mean: " + translate.translate_result(msg))

                # throw msg and nick to gags
                if config.get('say-responses'):
                    gags.get_response(nick, msg)
      
                # check and handle youtube links
                if config.get('youtube-links'):
                    if(msg.startswith("http://www.youtube.com/")):
                        try:
                            author, title = youtube.processlink(msg)
                            c.say(f.BOLD + f.RED + "YouTube Video" + f.BOLD + f.WHITE + " - " + title + " by " + author)
                        except:
                            c.say(f.BOLD + f.RED + "Youtube video failed" + f.BOLD + f.WHITE + " - 404 Not Found")
            
            # tell run.py to reload or exit
            if RELOAD:
                return True
            if EXIT:
                return False
Exemplo n.º 46
0
def is_root(member):
    return member.id == config.get("main.root_id")
Exemplo n.º 47
0
def mode(args):
    return _send_irc("MODE "
                    + config.get('channel') + " " + " ".join(args)
                    + "\r\n")