Example #1
0
    def __init__(self, bot):
        self._log_setup()

        self.bot = bot
        self.IRCconn = bot.IRCconn

        self.commands = {}

        # load commands from settings
        self._load_commands()

        # create command type
        # TODO: move to class
        self.Command = collections.namedtuple('Command', ['by', 'command', 'args'])

        # start command queue
        self._command_queue = Queue()
        self._command_thread = threading.Thread(target=self._command_queue_run)
        self._command_thread.daemon = True
        self._command_thread.start()

        # setting socketio sid var
        self._emit = None
        self._sid = None

        # setting moderators
        # TODO: Convert to class
        self.moderators = []
        self._load_moderators()

        # initiate giveaway class
        self.giveaway = Giveaway(self.logger)
Example #2
0
def main(irc):
    if AUTH is None:
        raise Exception('You didn\'t provide a TWITCH_AUTH key!')

    vote_bot = VoteBot()
    giveaway_bot = Giveaway()
    running = True
    while running:
        user, msg = irc.get_msg()

        response = None

        if msg == 'PING :tmi.twitch.tv':
            irc.ping()

        # This is for Ceaser_Gamming he is good people don't delete this
        elif msg.startswith('!crashcode'):
            response = f'You may not crash me {user[0]}!!'

        elif msg.startswith('!poll'):
            response = vote_bot.reducer(user[0], msg.split(' ', 1)[1])

        elif msg.startswith('!vote'):
            response = vote_bot.vote(user[0], msg.split(' ', 1)[1])

        elif msg.startswith('!giveaway'):
            response = giveaway_bot.add_user(user[0])
        elif msg.startswith('!pick_user'):
            response = giveaway_bot.pick_user(user[0])

        if response is not None:
            irc.send(response)
def get_likes(pipe, post_link):
    ig = Giveaway(LOGIN, PASSWORD, 0, post_link)
    ig.login()
    print("Logged in... (Likes Thread)")
    print('Getting people who liked post...')
    people_who_liked = ig.get_people_who_liked()
    time.sleep(1)
    pipe.send(people_who_liked)
    pipe.close()
    ig.close_browser()
Example #4
0
async def giveaway(ctx, *, text: str):
    """
    Summons a giveaway in the giveaway channel.

    Aliases:
        "create", "create_giv", "start", "start_giv", "giv", "create_giveaway", "start_giveaway"

    Attributes:
        *text: All attributes are taken directly from the message content using regexes. The arguments taken are:
            ... winners (str): The amount of winners of the giveaway. Will be transformed to int before creating the giveaway class.
            ... duration (str): The time before, or at which, the giveaway ends. See the help message for time formats.
            ... prize (str): The prize of the giveaway.
            ... description (str): [Optional] The description of the giveaway.

    Returns:
        None
    """

    other.is_admin(ctx.author)  # Check if the author is an admin.

    # Using a regex get all attributes
    pattern = r"(.+) ([0-9]+)w ([^>]+)( >(.+))?$"  # The pattern of the regex.
    try:
        duration, winners, prize, description = re.search(pattern, text).group(
            1, 2, 3, 5)  # Assign the values.
    except AttributeError:
        raise other.IncorrectUsageError  # If the regex doesn't match the str, raise an error.

    # Check if the description is None. If it is, convert it to an empty str.
    if description is None:
        description = ""
    else:
        description += "\n"  # Else add a newline to the end.

    giv = Giveaway(int(winners), duration[1:], prize, description,
                   ctx.author)  # Create giveaway object
    await giv.create_giv()  # Start giveaway
    giv.timer_id = delayed_execute(giv_end, [giv.id],
                                   giv.duration)  # Start the "timer"
    db_write_ids(giv.id, giv)  # Save the giveaway in the database
def get_comments(pipe, tags, post_link):
    ig = Giveaway(LOGIN, PASSWORD, tags, post_link)
    ig.login()
    print("Logged in... (Comments Thread)")
    print('Getting people who commented and tagged {} friends in the post'.
          format(tags))
    people_who_commented = ig.get_comments()
    time.sleep(1)
    pipe.send(people_who_commented)
    pipe.close()
    ig.close_browser()
Example #6
0
class Commands():
    def __init__(self, bot):
        self._log_setup()

        self.bot = bot
        self.IRCconn = bot.IRCconn

        self.commands = {}

        # load commands from settings
        self._load_commands()

        # create command type
        # TODO: move to class
        self.Command = collections.namedtuple('Command', ['by', 'command', 'args'])

        # start command queue
        self._command_queue = Queue()
        self._command_thread = threading.Thread(target=self._command_queue_run)
        self._command_thread.daemon = True
        self._command_thread.start()

        # setting socketio sid var
        self._emit = None
        self._sid = None

        # setting moderators
        # TODO: Convert to class
        self.moderators = []
        self._load_moderators()

        # initiate giveaway class
        self.giveaway = Giveaway(self.logger)

    def _log_setup(self):
        self.logger = logging.getLogger('bot.commands')
        log_f = logging.FileHandler(settings.COMMANDS_LOG_FILE)

        if (settings.DEBUG):
            self.logger.setLevel(logging.DEBUG)
            log_f.setLevel(logging.DEBUG)
        else:
            self.logger.setLevel(logging.INFO)

        formatter = logging.Formatter(settings.LOG_FORMATTER)
        log_f.setFormatter(formatter)

        self.logger.addHandler(log_f)

    def _load_commands(self):
        cmdlist = settings.COMMANDS_AVAILABLE
        # load debug commands if DEBUG is true
        if (settings.DEBUG):
            cmdlist = settings.COMMANDS_DEBUG

        for cmd in cmdlist:
            try:
                self.commands[cmd] = getattr(self, settings.COMMAND_PREFIX + cmd)
                self.logger.info("Loaded command <{0}>".format(cmd))
            except AttributeError:
                self.logger.warning("<{0}> not found".format(cmd))

    def _load_moderators(self):
        self.moderators = settings.MODERATORS


    # performs one command at a time
    def _command_queue_run(self):
        self.logger.info("Starting command queue")
        while (True):
            cmd = self._command_queue.get()
            self.logger.info("Executing <{0}>".format(cmd))
            self._perform(cmd)

    # Performs command with args
    def _perform(self, cmd):
        # find command key in the list
        if (cmd.command in self.commands.keys()):
            # call handling function
            resp = self.commands[cmd.command](cmd)
            # if response is a message, add it to the message queue
            if (isinstance(resp, self.bot.Message)):
                self.logger.info("Adding <{0}> to the message queue".format(resp))
                self.bot.add_to_message_queue(resp)
        else:
            self.logger.info(settings.COMMAND_NOT_FOUND.format(cmd))

    # puts command in the command queue
    def do(self, by, command, args):
        cmd = self.Command(by, command, args)
        self._add_to_command_queue(cmd)

    # Adds command to the command queue
    def _add_to_command_queue(self, cmd):
        self.logger.info("Adding <{0}> to the command queue".format(cmd))
        self._command_queue.put(cmd)

    # updates socket to new sid
    def set_socket(self, emit_func, sid):
        # self.logger.info("Socketio: {0} sid: {1}".format(socketio, sid))
        self._emit = emit_func
        self._sid = sid

    # Checks for a user moderator status
    # TODO: Twitch API
    def check_mod(self, username):
        if username in self.moderators:
            return True
        else:
            return False

    # Prints all available commands
    def command_help(self, cmd):
        msg = settings.COMMAND_HELP_TEMPLATE.format(', '
            .join(map(lambda x: '!' + x, settings.COMMANDS_AVAILABLE)))
        return self.bot.Message(cmd.by, msg)


    # Echoes text back to the chat
    def command_echo(self, cmd):
        return self.bot.Message(cmd.by, ' '.join(cmd.args))

    # Fowards text to the websocket
    def command_ask(self, cmd):
        self.logger.info("Starting {0} command".format(cmd.command))
        # check whether sid exists
        if (self._sid == None):
            self.logger.debug("No socket set up.")
            return self.bot.Message(cmd.by,
                                    settings.COMMAND_FORWARD_RESPONSE_FAIL)

        message = ' '.join(cmd.args)
        try:
            lang = TextBlob(message).detect_language()
            if 'ru' == lang:
                lang = 'ru'
            else:
                lang = 'en'
        except Exception as e:
            lang = 'none'

        data = {"message": message, "lang": lang}
        self._emit("ask", data, room=self._sid)
        return self.bot.Message(cmd.by,
                                settings.COMMAND_FORWARD_RESPONSE_SUCCESS.format(message))


    # givaway operations
    def command_giveaway(self, cmd):
        if len(cmd.args) == 0:
            arg = None
        else:
            arg = cmd.args[0]
        
        # Check whether command requires mod access
        if arg in settings.GIVEAWAY_MOD_ARGS:
            if self.check_mod(cmd.by):
                return self._cmd_giveaway_mods(cmd)      
        else:
            return self._cmd_giveaway(cmd)

    # Giveaway handler for moderators
    def _cmd_giveaway_mods(self, cmd):
        if len(cmd.args) == 0:
            arg = None
        else:
            arg = cmd.args[0]

        if arg == 'start':
            # check for arguments presence
            if len(cmd.args) < 3:
                return self.bot.Message(cmd.by, 
                    settings.GIVEAWAY_START_USAGE)
            # Get arguments from the command call
            name = cmd.args[1]
            description = cmd.args[2]
            # Execute command
            success, message = self.giveaway.start(name, description)

            # Send event success of giveaway start
            if success:
                data = {"message": 'Giveaway started', "lang": 'en'}
                self._emit("giveaway", data, room=self._sid)

            return self.bot.Message(cmd.by, message)
        elif arg == 'close':
            success, message = self.giveaway.close()

            # Send event success of giveaway close
            if success:
                data = {"message": 'Giveaway closed', "lang": 'en'}
                self._emit("giveaway", data, room=self._sid)

            return self.bot.Message(cmd.by, message)
        else:
            return self.bot.Message(cmd.by, 
                    settings.GIVEAWAY_NO_ARG)


    # Giveaway handler for non-mod users
    def _cmd_giveaway(self, cmd):
        if len(cmd.args) == 0:
            arg = None
        else:
            arg = cmd.args[0]
        
        # Check for requested argument
        if not arg:
            success, message = self.giveaway.enter(cmd.by)

            # Send event success of giveaway entry
            if success:
                data = {"message": '{0} entered giveaway'.format(cmd.by), 
                                "lang": 'en'}
                self._emit("giveaway", data, room=self._sid)

            return self.bot.Message(cmd.by, message)
        elif arg == 'stats':
            success, message = self.giveaway.statistics()
            return self.bot.Message(cmd.by, message)
        elif arg == 'info':
            success, message = self.giveaway.info()
            return self.bot.Message(cmd.by, message)
        else:
            return self.bot.Message(cmd.by, 
                settings.GIVEAWAY_NO_ARG)
def main(argv):

    post_link = ""

    allow_duplicates = False
    require_likes = False
    require_comments = False
    excluded_accounts = set()
    tag_ammount = 0
    winners_ammount = 1

    try:
        opts, args = getopt.getopt(
            argv, "hdt:lce:p:w:",
            ["tags=", "excluded=", "help", "post=", "winners="])
    except getopt.GetoptError:
        print('selectwinners.py -p <Post link> -e <Usernames excluded>')
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print('selectwinners.py -p <Link to post> -c -l')
            sys.exit()
        elif opt == "-d":
            allow_duplicates = True
        elif opt in ("-t", "--tags"):
            tag_ammount = int(arg)
        elif opt == "-l":
            require_likes = True
        elif opt == "-c":
            require_comments = True
        elif opt in ("-e", "--excluded"):
            for x in arg.split(','):
                excluded_accounts.add(x)
        elif opt in ("-p", "--post"):
            if arg[-1] == '/':
                arg = arg[0:-1]
            post_link = arg
        elif opt in ("-w", "--winners"):
            winners_ammount = int(arg)

    if (post_link == ""):
        print("Usage: selectwinners.py -p <Post Link>")
        sys.exit(2)
    if (not require_likes and not require_comments):
        print("You need to set -c or -l or both")
        sys.exit(2)

    likes_parent, likes_child = Pipe()
    comms_parent, comms_child = Pipe()

    likes = []
    comms = []

    people_to_chose = []
    comments_to_chose = []

    if (require_comments and require_likes):

        proc_like = Process(target=get_likes, args=(likes_child, post_link))
        proc_like.start()

        proc_comm = Process(target=get_comments,
                            args=(comms_child, tag_ammount, post_link))
        proc_comm.start()

        likes = likes_parent.recv()
        comms = comms_parent.recv()

        proc_like.join()
        proc_comm.join()

    else:
        ig = Giveaway(LOGIN, PASSWORD, tag_ammount, post_link)
        ig.login()
        print("Logged in...")

        if (require_comments):
            print('Getting people who commented and tagged {} friends'.format(
                tag_ammount))
            comms = ig.get_comments()
            likes = [x[0] for x in comms]

        elif (require_likes):
            print('Getting people who liked post...')
            likes = ig.get_people_who_liked()
            for x in list(likes):
                comms.append((x, x))

        ig.close_browser()

    print(comms)

    comments_with_both = [x for x in comms if x[0] in likes]

    if (not allow_duplicates):
        for comment in comments_with_both:
            if comment[0] in people_to_chose:
                excluded_accounts.add(comment[0])
                print("Excluding {} because of duplicate".format(comment[0]))
            else:
                people_to_chose.append(comment[0])

    comments_to_chose = [
        x for x in comments_with_both if x[0] not in excluded_accounts
    ]

    while (True):

        print(f"There are {len(comments_to_chose)} people to chose from...")
        winners = get_winners(winners_ammount, comments_to_chose)
        excluded_accounts.update(set([x[0] for x in winners]))
        comments_to_chose = [
            x for x in comments_to_chose if x[0] not in excluded_accounts
        ]

        if (len(comments_to_chose) == 0):
            sys.exit(0)

        winners_ammount = int(input("Select new winners: "))

        if winners_ammount == 0:
            sys.exit(0)