Exemple #1
0
def ctcp_req (user, request):
    reply, start, end = False, time.time(), time.time()
    
    # Check if the username is valid, so we don't waste our time.
    if not re.match("[a-zA-Z\[\]\\`_\^\{\|\}][a-zA-Z0-9\[\]\\`_\^\{\|\}]", user):
        return 1
    
    # Just for formality.
    request = request.upper()
    
    # Send the request.
    irc.msg(user, "\001{}\001".format(request))
    
    # Only listen for 20 seconds.
    while not reply and end - start < 20:
        irclist = [ x for x in irc.ircsock.recv(2048).split('\r\n') if x ]
        for msg in irclist:
            if request in msg and msg.startswith(":"+user) and " NOTICE " in msg:
                reply = msg.split(request, 1)[1].strip("\001").lstrip()
            else:
                commands.read(msg)
        end = time.time()
    
    # Return the reply, if it got one.
    if reply:
        return reply
    else:
        return ""
Exemple #2
0
def is_identified (user):
    
    # Check if --no-auth flag was used.
    if var.no_auth:
        return True
    
    # Determine auth command with services.
    if "ident.method" not in var.settings:
        set_auth_method()
    
    # Send set auth command.
    irc.msg("NickServ", "{} {}".format(var.settings["ident.method"], user), raw = True)
    response = ""
    
    while not response:
        for message in feed.s_out():
            if message.startswith(":NickServ"):
                response = message
            else:
                handler.read(message)
    
    # Checking with ident.method for NickServ auth.
    if var.settings["ident.method"] == "STATUS":
        return bool("STATUS {} 3".format(user) in response)
    elif var.settings["ident.method"] == "ACC":
        return bool("{} ACC 3".format(user) in response)
Exemple #3
0
    def on_players(self, mask, location, text):
        """ Simple 2 line broadcast of players.
            This is triggered by an IRC event. Note that the player
            data retreived here is from the last query of the server """

        #output the player list to the requester directly 
        #instead of the channel if the bot owner wishes it
        if self.private_players_display:
            recv = mask.nick
        else:
            recv = self.channel

        alist, blist, flist = self.get_teams()

        aout = [self.name_a, ': ']
        bout = [self.name_b, ': ']
        for ls, out in [(alist, aout), (blist, bout)]:
            if ls:
                for plr in ls:
                    s = '%s %dpts' % (plr.name, plr.score)
                    out.append(s)
                    out.append(', ')

                del out[-1]
            else:
                out.append(' <No players> ')
       
        aout = ''.join(aout)
        bout = ''.join(bout)

        irc.msg(recv, aout)
        irc.msg(recv, bout)
Exemple #4
0
def kick (user, channel, target, reason):
    if target == irc.botnick:
        irc.msg(irc.admin, "{} was kicked from {} by {}.".format(target, channel, user))
        irc.msg(irc.admin, "Reason: {}".format(reason) if reason
                else "No reason was given.")
        
        var.channels.remove(channel)
        ini.remove_from_list(channel, "channels.ini")
Exemple #5
0
 def check (user, channel, word):
     try:
         if word[1] in [] and not is_identified(user):
             irc.msg(channel, "{}: Identify with NickServ first.".format(user))
         else:
             f(user, channel, word)
     except IndexError:
         f(user, channel, word)
Exemple #6
0
 def check (user, channel, word):
     try:
         if word[1] in [
             "-a", "-add", "--add",
             "-rm", "-remove", "--remove",
             "-re", "-replace", "--replace"
         ] and not is_identified(user):
             irc.msg(channel, "{}: Identify with NickServ first.".format(user))
         else:
             f(user, channel, word)
     except IndexError:
         f(user, channel, word)
Exemple #7
0
 def mod_entry (user, channel, word):
     data = " ".join(word[2:])
     
     # Ignore case.
     for nick in string_dictionary:
         if user.lower() == nick.lower():
             user = nick
     
     string_dictionary[user] = data
     ini.add_to_ini(section = section_name, option = user, 
                     data = data, filename = filename)
     irc.msg(channel, "{}: Your {} was added successfully.".format(
                     user, dictionary_name))
Exemple #8
0
 def rm_entry (user, channel, word):
     # Ignore case.
     for nick in string_dictionary:
         if user.lower() == nick.lower():
             user = nick
     
     if user not in string_dictionary:
         irc.msg(channel, "{}: You have no {} saved.".format(user, dictionary_name))
     else:
         del string_dictionary[user]
         ini.remove_from_ini(section = section_name, option = user,
                                 filename = filename)
         irc.msg(channel, "{}: Your {} was removed successfully.".format(
                         user, dictionary_name))
Exemple #9
0
 def access_db (user, channel, word):
     target = user if len(word) == 1 else word[1]
     
     # Ignore case.
     for nick in string_dictionary:
         if target.lower() == nick.lower():
             target = nick
     
     if target not in string_dictionary:
         err_msg = "You don't" if target == user else "\x0f{} doesn't".format(target)
         irc.msg(channel, "{} have any {} saved.".format(err_msg,
                             dictionary_name))
     else:
         irc.msg(channel, "\x0f{} \x0f[{}]".format(
                     string_dictionary[target], target))
Exemple #10
0
def set_auth_method ():
    irc.msg("NickServ", "STATUS {}".format(irc.botnick), raw = True)
    response = ""
    
    while not response:
        for message in feed.s_out():
            if not response and message.startswith(":NickServ"):
                response = message
            else:
                handler.read(message)
    
    if "STATUS" in response:
        var.settings["ident.method"] = "STATUS"
        ini.add_to_ini("Settings", "ident.method", "STATUS", "settings.ini")
    else:
        var.settings["ident.method"] = "ACC"
        ini.add_to_ini("Settings", "ident.method", "ACC", "settings.ini")
Exemple #11
0
 def list_urls (user, channel, word):
     target, number = False, False
     
     if len(word) == 1:
         target = user
     elif len(word) == 2:
         target = word[1] if not is_number(word[1]) else user
         number = word[1] if is_number(word[1]) else False
     elif len(word) >= 3:
         target = word[1]
         number = word[2]
     
     for nick in url_dict:
         if target.lower() == nick.lower():
             target = nick
     
     # Throw a message if the target isn't in the URL database.
     if target not in url_dict:
         err_msg = "You don't" if target == user else "{} doesn't".format(target)
         irc.msg(channel, "{} have any {} saved.".format(err_msg, dict_name))
         return
     
     # Check if the received number is a valid integer.
     if (not is_number(number)) or ((int(number) if number else 1) < 1):
         irc.msg(channel, "{}: Invalid number.".format(user))
         return
         
     if number:
         # Turning number into a numeric value.
         number = int(number) - 1
         
         if number >= len(url_dict[target]):
             err_msg = "You don't" if target == user else "{} doesn't".format(target)
             irc.msg(channel, "{} have that many {}.".format(err_msg, dict_name))
         else:
             line = "[{}] ".format("\x034NSFW\x0f" if "!" in url_dict[target][number] else number+1)
             line += "{} [{}]".format(url_dict[target][number].strip("!"), target)
             irc.msg(channel, line)
     else:
         url_list = ["[{}] {}".format(ind+1, url) for ind, url in enumerate(url_dict[target])]
         
         # Looking for NSFW URLs. (as indicated by '!')
         url_list = map(nsfw_check, url_list)
         
         line = " ".join(url_list) + " [{}]".format(target)
         irc.msg(channel, line)
Exemple #12
0
def set_auth_method ():
    irc.msg("NickServ", "STATUS {}".format(irc.botnick))
    response = False
    
    while not response:
        irclist = [x for x in irc.ircsock.recv(2048).split("\r\n") if x]
        for msg in irclist:
            if msg.startswith(":NickServ"):
                response = msg
            else:
                commands.read(msg)
    
    if "STATUS" in response:
        var.settings["ident.method"] = "STATUS"
        ini.add_to_ini("Settings", "ident.method", "STATUS", "settings.ini")
    else:
        var.settings["ident.method"] = "ACC"
        ini.add_to_ini("Settings", "ident.method", "ACC", "settings.ini")
Exemple #13
0
 def delete_url (user, channel, word):
     del_list = [int(x) - 1 for x in word[2].split(',') if (is_number(x) and int(x) > 0)]
     
     for nick in url_dict:
         if user.lower() == nick.lower():
             user = nick
     
     # Wildcard removes everything saved for that user from the database.
     if word[2] == "*" and user in url_dict:
         del url_dict[user]
         ini.remove_from_ini(sect_name, user, file)
         irc.msg(channel, "{}: All of your {} were removed successfully.".format(user, dict_name))
         return
     
     # The list only needs numbers.
     if not del_list:
         irc.msg(channel, "{}: Invalid number(s).".format(user))
         return
     
     # The user must be in the database to be able to remove URLs.
     if user not in url_dict:
         irc.msg(channel, "{}: You don't have any {} saved.".format(user, dict_name))
         return
     
     # Copy contents of indexed list in database to deletion list.
     for index, number in enumerate(del_list):
         if len(url_dict[user]) > number:
             del_list[index] = url_dict[user][number]
     
     # Proceed to remove them one by one.
     for entry in del_list:
         if entry in url_dict[user]:
             url_dict[user].remove(entry)
     
     # Delete entry in database for an empty list and remove user from ini file.
     if not url_dict[user]:
         del url_dict[user]
         ini.remove_from_ini(sect_name, user, file)
         irc.msg(channel, "{}: All of your {} were removed successfully.".format(user, dict_name))
         return
     
     ini.add_to_ini(sect_name, user, '\n'.join(url_dict[user]), file)
     irc.msg(channel, "{}: {} deleted.".format(user, sect_name))
Exemple #14
0
 def add_url (user, channel, word):
     a_list = [url for url in word[2:] if url.startswith("http://") or url.startswith("https://")]
     
     if not a_list:
         irc.msg(channel, "{}: Links have to start with \"http://\" or \"https://\".".format(user))
         return
     
     for nick in url_dict:
         if user.lower() == nick.lower():
             user = nick
     
     # Create an empty list for a new user.
     if user not in url_dict:
         url_dict[user] = []
     
     # Or check if existing user already has max URLs saved.
     elif len(url_dict[user]) == max:
         irc.msg(channel, "{}: You already have {} {} saved.".format(user, max, dict_name))
         return
     
     # Fill saved list until it reaches max URLs.
     for url in a_list:
         if len(url_dict[user]) < max:
             url_dict[user].append(trim(url))
         else:
             break
     
     ini.add_to_ini(sect_name, user, '\n'.join(url_dict[user]), file)
     irc.msg(channel, "{}: {} added.".format(user, sect_name))
Exemple #15
0
def is_identified (user):
    # Determine auth command with services.
    if "ident.method" not in var.settings:
        set_auth_method()
    
    # Send set auth command.
    irc.msg("NickServ", "{} {}".format(var.settings["ident.method"], user))
    response = False
    
    while not response:
        irclist = [x for x in irc.ircsock.recv(2048).split("\r\n") if x]
        for msg in irclist:
            if msg.startswith(":NickServ"):
                response = msg
            else:
                commands.read(msg)
    
    # Checking with ident.method for NickServ auth.
    if var.settings["ident.method"] == "STATUS":
        return bool("STATUS {} 3".format(user) in response)
    elif var.settings["ident.method"] == "ACC":
        return bool("{} ACC 3".format(user) in response)
Exemple #16
0
def ctcp_req (user, request, *param):
    start = end = time.time()
    reply = ""
        
    # Check if the username is valid, so we don't waste our time.
    if not re.match("[a-zA-Z\[\]\\`_\^\{\|\}][a-zA-Z0-9\[\]\\`_\^\{\|\}]", user):
        return 1
    
    # Just for formality.
    request = request.upper()
    
    # Send the request.
    if param:
        irc.msg(user, "\001{} {}\001".format(request, param[0]), raw = True)
    else:
        irc.msg(user, "\001{}\001".format(request), raw = True)
    
    # Only listen for 20 seconds.
    while (not reply) and end - start < 20:
        for message in feed.s_out():
            if (
                (not reply) and
                request in message and
                message.startswith(":"+user) and
                " NOTICE " in message
            ):
                reply = message.split(request, 1)[1].strip("\001").lstrip()
            else:
                handler.read(message)
        
        end = time.time()
    
    # Return the reply, if it got one.
    if reply:
        return reply
    else:
        return ""
Exemple #17
0
    def broadcast_players(self):
        """ Print detailed player list to channel.
            This is only triggerable directly by the Fragmon user, as it can be slow. 
            Note that the player data retreived here is from the last query of the server"""

        alist, blist, flist = self.get_teams() 
      
        for ls, name in [(alist, self.name_a), (blist, self.name_b), (flist, 'specs/other')]:
            if ls:
                irc.msg(self.channel, 'Pts   Ping  Name (%s)' % name)
                irc.msg(self.channel, '----------------')
                for plr in ls:
                    irc.msg(self.channel, '%-5d %-5d %s' % (plr.score, plr.ping, plr.name))

      
        if not alist and not blist and not flist:
            irc.msg(self.channel, 'No players')
Exemple #18
0
    def broadcast(self):
        """ Print scores to channel using the broadcast format configured by user.
            This adds two new format specifiers, 'best_name' and 'best_score'.
            This also does team sum if the do_sum option is set. """ 
    
        alist, blist, flist = self.get_teams() 

        if self.do_sum:
            self.score_a = str(self.sum_score(alist))
            self.score_b = str(self.sum_score(blist))

        bestplayer = Player(name='...', score=-999)
        search = alist + blist
        for plr in search:
            if plr.score > bestplayer.score:
                bestplayer = plr
       
        v = [
            ('best_name', bestplayer.name),
            ('best_score', str(bestplayer.score)),
        ]

        out = self.sub_format(vars=v)
        irc.msg(self.channel, out)
Exemple #19
0
 def replace_url (user, channel, word):
     
     
     # This command receives two pieces of information.
     if len(word) < 4:
         irc.msg(channel, "{}: Wrong syntax. Check .help".format(user))
         return
     
     
     # The first must be a number.
     if not is_number(word[2]):
         irc.msg(channel, "{}: Invalid number.".format(user))
         return
     
     # The second must be a URL.
     if not (word[3].startswith("http://") or word[3].startswith("https://")):
         irc.msg(channel, "{}: Invalid URL.".format(user))
         return
     
     
     # Turn it into a numeric value.
     number = int(word[2]) - 1
     
     
     # Check if it's in the max range, and no negative indexes will be accepted.
     if number > max-1 or number < 0:
         irc.msg(channel, "{}: Invalid number.".format(user))
         return
     
     
     # Ignore case.
     for nick in url_dictionary:
         if user.lower() == nick.lower():
             user = nick
             break
     
     
     # Try to replace URL using received number.
     try:
         url_dictionary[user][number] = trim(word[3])
         ini.add_to_ini(section = section_name, option = user, 
                         data = '\n'.join(url_dictionary[user]), filename = filename)
         irc.msg(channel, "{}: {} replaced.".format(user, section_name.rstrip("s")))
     
     
     # It might not work, if the list isn't long enough.
     except IndexError:
         irc.msg(channel, "{}: Invalid number.".format(user))
     
     # And it won't work if the user isn't in the URL database.
     except KeyError:
         irc.msg(channel, "{}: You don't have any {} saved.".format(user, dictionary_name))
Exemple #20
0
 def list_urls (user, channel, word):
     
     
     target = False
     number = False
     
     # Grab values from message.
     if len(word) == 1:
         target = user
     elif len(word) == 2:
         target = word[1] if not is_number(word[1]) else user
         number = word[1] if is_number(word[1]) else False
     elif len(word) >= 3:
         target = word[1]
         number = word[2]
     
     
     # Check if it's a URL or a number.
     if target.startswith("http://") or target.startswith("https://"):
         irc.msg(channel, "Did you mean to use -a {}?".format(target))
         return
     elif number and target.isdigit():
         irc.msg(channel, "Did you mean to use -re {} {}?".format(target, number))
         return
     
     
     # Check if an action string was misused.
     if target.startswith("-"):
         
         # Grab tuple containing string.
         commands = ()
         
         for str_list in syntax:
             if target in str_list:
                 commands = str_list
                 break
         
         if commands in syntax:
             line = syntax[commands].format(word[0], target)
             irc.msg(channel, "Syntax for {}: {}".format(target, line))
         else:
             irc.msg(channel, "{}: Unknown command.".format(user))
         
         return
     
     
     # Case insensitive check.
     for nick in url_dictionary:
         if target.lower() == nick.lower():
             target = nick
             break
     
     
     # Throw a message if the target isn't in the URL database.
     if target not in url_dictionary:
         err_msg = "You don't" if target == user else "{} doesn't".format(target)
         irc.msg(channel, "{} have any {} saved.".format(err_msg, dictionary_name))
         return
     
     
     # Check if the received number is a valid integer.
     if (not is_number(number)) or ((int(number) if number else 1) < 1):
         irc.msg(channel, "{}: Invalid number.".format(user))
         return
     
     
     # Finally gather results and display them.
     if number:
         # Turning number into a numeric value.
         number = int(number) - 1
         
         if number >= len(url_dictionary[target]):
             err_msg = "You don't" if target == user else "{} doesn't".format(target)
             irc.msg(channel, "{} have that many {}.".format(err_msg, dictionary_name))
         else:
             
             # Looking for NSFW URLs. (as indicated by '!')
             if "!" in url_dictionary[target][number]:
                 line = "[\x034NSFW\x0f] "
             else:
                 line = "[{}] ".format(number + 1)
             
             line += "{} [{}]".format(url_dictionary[target][number].strip("!"), target)
             irc.msg(channel, line)
     
     else:
         url_list = ["[{}] {}".format(ind+1, url) for ind, url in \
                             enumerate(url_dictionary[target])]
         
         # Looking for NSFW URLs. (as indicated by '!')
         url_list = map(nsfw_check, url_list)
         
         line = " ".join(url_list) + " [{}]".format(target)
         irc.msg(channel, line)
Exemple #21
0
def invite (user, channel):
    irc.notice(user, "I'll let {} know you invited me to {}.".format(irc.admin, channel))
    irc.msg(irc.admin, "Invite to {} from {}.".format(channel, user))
Exemple #22
0
def invite (user, channel):
    irc.join(channel)
    irc.msg(channel, "{} invited me here.".format(user))
Exemple #23
0
def exec_python (channel, command):
    try:
        exec(command)
    except Exception as exc:
        irc.msg(channel, "Exception: {}".format(exc))