Exemplo n.º 1
0
def cron(channel):
    import globals
    try:
        channel = channel.lstrip("#")
        from src.lib.twitch import get_stream_status, get_hosts
        from src.lib.channel_data import ChannelData
        from src.lib.queries import Database
        cd = ChannelData(channel)
        if get_stream_status():
            channel_id = cd.get_channel_id_from_db()[0]
            hosts = get_hosts(channel_id)
            unthanked_users = []
            for host in hosts:
                host_data = cd.get_channel_data_by_user(host["host_login"], "host")
                if not host_data:
                    cd.insert_channel_data(host["host_login"], "host")
                    db = Database()
                    db.add_user([host["host_login"]], channel)
                    db.modify_points(host["host_login"], channel, 100)
                    unthanked_users.append(host["host_login"])
            if len(unthanked_users) == 1:
                user = unthanked_users[0]
                resp = "Thank you {0} for the host! Here's 100 cash!".format(user)
                globals.irc.send_message("#" + channel, resp)
            elif len(unthanked_users) > 1:
                resp = "The following users are receiving 100 cash for hosting: " + ", ".join(unthanked_users) + "!"
                globals.irc.send_message("#" + channel, resp)
            elif len(unthanked_users) > 10:
                resp = "Thanks to the {0} people hosting! Each of you get 100 cash!".format(
                    len(unthanked_users))
                globals.irc.send_message("#" + channel, resp)
        else:
            cd.remove_channel_data("host")
    except Exception as error:
        print error
Exemplo n.º 2
0
def trigger_clear_bets(chan):
    db = Database()
    bets_data = db.get_all_bets_data()

    try:
        #Get the oldest date
        oldest_date = datetime.strptime(bets_data[0][5], "%Y %m %d %H %M %S")
        now = datetime.utcnow()
        if now - oldest_date >= timedelta(30):
            if not os.path.exists(os.path.join('dump')):
                os.makedirs(os.path.join('dump'))
            path = os.path.join(
                "dump", "bets_data_" +
                datetime.strftime(now, "%Y_%m_%d_%H_%M_%S") + ".csv")
            with open(path, 'wb') as outfile:
                wr = csv.writer(outfile)
                header = ("id", "channel", "username", "amount", "outcome",
                          "date")
                wr.writerow(header)
                for row in bets_data:
                    wr.writerow(row)
            db.clear_bets()

    except Exception as error:
        print error
Exemplo n.º 3
0
def cron(channel):
    try:
        from datetime import datetime
        from src.bot import ECHOERS, BOT_USER
        from src.lib.queries import Database
        chan = channel.lstrip("#")
        now = datetime.today()
        db = Database()
        timers = db.get_timer_command(channel=chan)
        if timers:
            # channel, command, response, user_level, timer, timer_tripped, created_at
            for timer in timers:
                command = timer[1]
                resp = str(timer[2])
                minutes = timer[4]
                timer_tripped = timer[5]
                created_at = datetime.strptime(str(timer[6]), '%Y-%m-%d %H:%M:%S')
                difference = (created_at - now).seconds / 60
                if timer_tripped == 0 and difference % minutes == 0:
                    db.update_timer_command(channel=chan, command=command)
                    sender = "{user}!{user}@{user}.tmi.twitch.tv".format(
                        user=BOT_USER)
                    line = ":%s PRIVMSG %s :%s" % (sender, channel, resp)
                    echoer = ECHOERS["chat"]  # chat reactor instance
                    echoer.sendLine(line)
    except:
        pass
Exemplo n.º 4
0
def add(args, **kwargs):
    db = Database()
    command = "!" + args[0].lower().lstrip("!")
    user_level = args[1]
    response = " ".join(args[2:])
    creator = kwargs.get("username", "testuser")
    channel = kwargs.get("channel", "testchannel")
    if command not in command_headers.commands:
        if user_level == "reg" or user_level == "mod":
            db.add_command(
                user=creator, command=command, response=response,
                user_level=user_level, channel=channel)
            return "{0} added to nano_machina's custom commands!".format(
                command)
        else:
            try:
                timer = int(user_level)
                db.add_command(
                    user=creator, command=command, response=response,
                    user_level="timer", channel=channel, timer=timer)
                return "{0} added to nano_machina's custom commands!".format(
                    command)
            except Exception as error:
                print error
                return "User level must be \'reg\', \'mod\', or a number"
    else:
        return "{0} already built in to nano_machina.".format(command)
Exemplo n.º 5
0
def trigger_less_than_200_for_all(chan):
    try:
        db = Database()
        channel = chan.lstrip("#")
        str_last_time = db.get_last_time_points_reset(channel)[0]
        if str_last_time:
            now = datetime.utcnow()
            last_time = datetime.strptime(str_last_time, "%Y %m %d %H %M %S")
            if now - last_time >= timedelta(1):
                usernames = db.get_all_usernames()
                
                for username in usernames:
                    points = db.get_points(username)[0]
                    if points < 200:
                        db.set_points(username, 200)
                
                strnow = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
                db.set_last_time_points_reset(channel, strnow)
                return "Points have been reloaded for users who have less than 200!"
                   
        else:
            strnow = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
            db.set_last_time_points_reset(channel, strnow)
    
    except Exception as error:
        print error
Exemplo n.º 6
0
 def __init__(self):
     self.irc = globals.irc
     self.channel = globals.CURRENT_CHANNEL
     self.chan = "#" + self.channel
     self.db = Database()
     #self.bets_started = datetime.strptime(self.db.get_bets_started(self.channel)[0], "%Y %m %d %H %M %S")
     #Generates list of tuples(username, amount, outcome, date) that only consists of bidders that bet after the bets have started
     self.bets_data = [x for x in self.db.get_bets_data(self.channel) if datetime.strptime(x[3], "%Y %m %d %H %M %S") > datetime.strptime(self.db.get_bets_started(self.channel)[0], "%Y %m %d %H %M %S")]
Exemplo n.º 7
0
def top10():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    rank_data = db.get_top10(channel)
    # [(1, u'singlerider', 441, u'ravenbot007'), (2, u'nano_machina', 129, u'ravenbot007')]
    candidates = ", ".join([str(i + 1) + ") " + x[1] + ": " + str(x[2]) for i, x in enumerate(rank_data)])
    resp = "The top 10 cash holders are... " + candidates
    return resp
Exemplo n.º 8
0
class Bets:

    def __init__(self):
        self.irc = globals.irc
        self.channel = globals.CURRENT_CHANNEL
        self.chan = "#" + self.channel
        self.db = Database()
        #self.bets_started = datetime.strptime(self.db.get_bets_started(self.channel)[0], "%Y %m %d %H %M %S")
        #Generates list of tuples(username, amount, outcome, date) that only consists of bidders that bet after the bets have started
        self.bets_data = [x for x in self.db.get_bets_data(self.channel) if datetime.strptime(x[3], "%Y %m %d %H %M %S") > datetime.strptime(self.db.get_bets_started(self.channel)[0], "%Y %m %d %H %M %S")]
        
    def calculate_total_points(self):
        total_points = 0
        for bidder in self.bets_data:
            total_points += bidder[1]
            
        return total_points
        
    def calculate_winning_points(self, outcome):
        winning_points = 0
        for bidder in self.bets_data:
            if bidder[2] == outcome:
                winning_points += bidder[1]
            
        return winning_points
    
    #Called from outcome.py
    def distribute_profit(self, outcome):
        bets_total = self.calculate_total_points()
        bets_winning = self.calculate_winning_points(outcome)
        
        try:
            profit = float(bets_total)/bets_winning
        except ZeroDivisionError:
            msg = "Sorry, there are no winners"
            self.irc.send_message(self.chan, msg)
            return
        
        try:
            for bidder in self.bets_data:
                if bidder[2] == outcome:
                    winnings = int(profit*bidder[1])
                    self.db.modify_points(bidder[0], winnings)
                    msg = "/w {0} Congrats! You won {1} points!".format(bidder[0], winnings)
                    self.irc.send_message(self.chan, msg)
                else:
                    msg = "/w {0} Feelsbadman, maybe you will win next time".format(bidder[0])
                    self.irc.send_message(self.chan, msg)
                
        except Exception as error:
            print error
            msg = "Sorry, there was an error distributing profit"
            self.irc.send_message(self.chan, msg)
            return
        
        msg = "Winnings have been released!"
        self.irc.send_message(self.chan, msg)
Exemplo n.º 9
0
 def __init__(self, irc, chan, delay):
     Thread.__init__(self, target=self.main)
     self.daemon = True
     self.delay = delay
     self.now = time.time()
     self.chan = chan
     self.channel = self.chan.lstrip("#")
     self.irc = irc
     self.db = Database()
Exemplo n.º 10
0
def points():
    username = globals.CURRENT_USER
    db = Database()
    try:
        points = int(db.get_points(username)[0])
    except Exception as error:
        print error
        return "Couldn't show your points, sorry!"
    return "You have {0} points!".format(points)
Exemplo n.º 11
0
def points():
    username = globals.CURRENT_USER
    db = Database()
    try:
        points = int(db.get_points(username)[0])
    except Exception as error:
        print error
        return "Couldn't show your points, sorry!"
    return "You have {0} points!".format(points)
Exemplo n.º 12
0
def addquote(args):
    db = Database()
    user = globals.CURRENT_USER
    channel = globals.CURRENT_CHANNEL
    quote = unicode(args[0].strip().strip("\"").strip("\'"), 'utf-8')
    if len(quote) > 300:
        return "Let's keep it below 300 characters?"
    game = get_stream_game(channel)
    db.add_quote(channel, user, quote, game)
    return "{0} added!".format(quote)
Exemplo n.º 13
0
def addquote(args, **kwargs):
    db = Database()
    user = kwargs.get("username", "testuser")
    channel = kwargs.get("channel", "testchannel")
    quote = unicode(args[0].strip().strip("\"").strip("\'"), 'utf-8')
    if len(quote) > 300:
        return "Let's keep it below 300 characters?"
    game = get_stream_game(channel)
    db.add_quote(channel, user, quote, game)
    return "{0} added!".format(quote)
Exemplo n.º 14
0
        def check_for_sub(channel, username, message):
            # >> :[email protected] PRIVMSG #curvyllama :KiefyWonder subscribed for 5 months in a row!
            # >> :[email protected] PRIVMSG #curvyllama :KiefyWonder just subscribed!
            # Photo_phocus just subscribed to jonsandman!
            # HermanNugent subscribed to JonSandman for 7 months in a row!
            # first sub points = 1000
            # resub = 250
            db = Database()
            try:
                channel = channel.lstrip("#")
                message_split = message.rstrip("!").split()
                subbed_user = message_split[0].lower()
                if message_split[1] == "just" and len(message_split) < 4:
                    points = 1000
                    db.add_user([subbed_user], channel)
                    db.modify_points(subbed_user, channel, points)
                    resp = "/me {0} just subscribed for the first time!\
 {1} cash for you!".format(subbed_user, points)
                    self.irc.send_message("#" + channel, resp)
                elif message_split[1] == "subscribed" and len(message_split) < 9:
                    months_subbed = message_split[3]
                    points = 250
                    db.add_user([subbed_user], channel)
                    db.modify_points(subbed_user, channel, points)
                    resp = "/me {0} has just resubscribed for {1} months \
straight and is getting {2} cash!".format(subbed_user, months_subbed, points)
                    self.irc.send_message("#" + channel, resp)
            except Exception as error:
                print error
Exemplo n.º 15
0
 def __init__(self, config):
     self.db = Database()
     self.db.initiate()
     self.config = config
     self.crons = crons
     src.lib.command_headers.initalizeCommands(config)
     self.irc = irc_.irc(config)
     # start threads for channels that have cron messages to run
     cron.initialize_crons(self.irc, self.crons.crons.get("crons", {}))
     cron.initialize_channel_id_check(self.config)
     globals.irc = self.irc
Exemplo n.º 16
0
def rem(args, **kwargs):
    db = Database()
    command = args[0].lower()
    channel = kwargs.get("channel", "testchannel")
    command_data = db.get_command(command, channel)
    if command_data:
        db.remove_command(command, channel)
        return "{0} removed!".format(
            command)
    else:
        return "{0} not found.".format(command)
Exemplo n.º 17
0
def top10():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    rank_data = db.get_top10(channel)
    # [(1, u'singlerider', 441, u'ravenbot007'), (2, u'nano_machina', 129, u'ravenbot007')]
    candidates = ", ".join([
        str(i + 1) + ") " + x[1] + ": " + str(x[2])
        for i, x in enumerate(rank_data)
    ])
    resp = "The top 10 cash holders are... " + candidates
    return resp
Exemplo n.º 18
0
def result():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    
    try:
        outcome = db.get_last_result(channel)[0]
        return "Last outcome was: {0}".format(outcome)

    except:
        print error
        return "There were no bets yet"
Exemplo n.º 19
0
def result():
    db = Database()
    channel = globals.CURRENT_CHANNEL

    try:
        outcome = db.get_last_result(channel)[0]
        return "Last outcome was: {0}".format(outcome)

    except:
        print error
        return "There were no bets yet"
Exemplo n.º 20
0
def rem(args):
    db = Database()
    command = args[0].lower()
    channel = globals.CURRENT_CHANNEL
    command_data = db.get_command(command, channel)
    if command_data:
        db.remove_command(command, channel)
        return "{0} removed from Ravenbot007's custom commands!".format(
            command)
    else:
        return "{0} not found.".format(command)
Exemplo n.º 21
0
def deactivate(args, **kwargs):
    channel = kwargs.get("channel", "testchannel")
    command = "!" + args[0].lstrip("!")
    command_data = commands.commands.get(command, None)
    if command == "!activate" or command == "!deactivate":
        return "You can't do that."
    if command_data:
        db = Database()
        db.modify_active_command(channel=channel, command=command, active=0)
        return command + " deactivated!"
    else:
        return command + " not found."
Exemplo n.º 22
0
class Gamble:

    def __init__(self, channel="testchannel", user="******", points=0):
        self.db = Database()
        self.channel = channel
        self.user = user
        self.points = points

    def initiate_gamble(self):
        if self.channel not in globals.channel_info:
            globals.channel_info[self.channel]["gamble"] = {
                "time": None, "users": {}, "points": 0}
        globals.channel_info[self.channel]['gamble'] = {
            "time": time.time(), "users": {
                self.user: True}, "points": self.points}

    def terminate_gamble(self):
        globals.channel_info[self.channel]['gamble']["time"] = None

    def check_gamble(self):
        if self.channel not in globals.channel_info:
            globals.channel_info[self.channel]["gamble"] = {
                "time": None, "users": {}}
        if globals.channel_info[self.channel]['gamble']["time"]:
            return globals.channel_info[self.channel]['gamble']["time"]
        else:
            return None

    def get_gamble_user(self, user):
        user_value = globals.channel_info[globals.CURRENT_CHANNEL]['gamble'][
            "users"].get(user)
        if user_value:
            return True
        else:
            return False

    def rob_yield(self, multiplier=1):
        points_yield = random.choice(range(1, 11))
        points = 0
        if points_yield > 9:
            points = random.choice(range(1, 301)) * multiplier
        elif points_yield <= 9 and points_yield > 5:
            points = random.choice(range(1, 21)) * multiplier
        elif points_yield <= 5 and points_yield > 1:
            points = random.choice(range(1, 11)) * multiplier
        else:
            points = self.points
        if bool(random.getrandbits(1)):
            points *= -1
        return points

    def apply_yield(self, channel, user, points):
        self.db.modify_points(user, channel, points)
Exemplo n.º 23
0
def quote():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    # (1, u'testchannel', u'testuser', u'quote', 1, u'testgame')
    quote_data = db.get_quote(channel)
    if quote_data is None:
        return "No quotes found. Why not add one with '!addquote [quote]'?"
    else:
        quote = str(quote_data[3])
        quote_number = quote_data[4]
        game = quote_data[5]
        resp = "Quote #{0}: \"{1}\" [{2}]".format(quote_number, quote, game)
        return resp
Exemplo n.º 24
0
def stop():
    channel = globals.CURRENT_CHANNEL
    chan = "#" + channel
    db = Database()
    bets = db.are_bets(channel)[0]
    if bets:
        delay = 30
        initialize(chan, delay)
        
    else:
        return "You haven't started a bet yet!"
    
    return "You have started the countdown"
Exemplo n.º 25
0
def stop():
    channel = globals.CURRENT_CHANNEL
    chan = "#" + channel
    db = Database()
    bets = db.are_bets(channel)[0]
    if bets:
        delay = 30
        initialize(chan, delay)

    else:
        return "You haven't started a bet yet!"

    return "You have started the countdown"
Exemplo n.º 26
0
def chance():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    user = globals.CURRENT_USER
    g = Gamble(channel)
    points = abs(g.rob_yield(multiplier=1))
    db.add_user([user], channel)
    db.modify_points(user, channel, points)
    print user, points, channel
    if points ==  0:
        resp = "Nothing this time! Try again in a half hour?"
    else:
        resp = "You got {0} cash!".format(points)
    return resp
Exemplo n.º 27
0
 def __init__(self, irc, chan, delay):
     Thread.__init__(self, target=self.main)
     self.daemon = True
     self.delay = delay
     self.now = time.time()
     self.chan = chan
     self.channel = self.chan.lstrip("#")
     self.irc = irc
     self.db = Database()
Exemplo n.º 28
0
def add(args):
    db = Database()
    command = args[0].lower()
    user_level = args[1]
    response = " ".join(args[2:])
    creator = globals.CURRENT_USER
    channel = globals.CURRENT_CHANNEL
    if command[0] is "!":
        if command not in command_headers.commands:
            if user_level == "reg" or user_level == "mod":
                db.add_command(creator, command, response, user_level, channel)
                return "{0} added to Ravenbot007's custom commands!".format(
                    command)
            else:
                return "User level must be 'reg' or 'mod'"
        else:
            return "{0} already built in to Ravenbot007.".format(command)
    else:
        return "Command must begin with '!'"
Exemplo n.º 29
0
 def __init__(self, config):
     self.db = Database()
     self.db.initiate()
     self.config = config
     self.crons = crons
     src.lib.command_headers.initalizeCommands(config)
     self.irc = irc_.irc(config)
     # start threads for channels that have cron messages to run
     cron.initialize_crons(self.irc, self.crons.crons.get("crons", {}))
     cron.initialize_channel_id_check(self.config)
     globals.irc = self.irc
Exemplo n.º 30
0
def edit(args, **kwargs):
    db = Database()
    command = "!" + args[0].lower().lstrip("!")
    user_level = args[1]
    response = " ".join(args[2:])
    channel = kwargs.get("channel", "testchannel")
    if command not in command_headers.commands:
        command_data = db.get_command(command, channel)
        if command_data:
            if user_level == "reg" or user_level == "mod":
                db.modify_command(
                    command=command, response=response,
                    user_level=user_level, channel=channel, timer=None)
                return "{0} added to nano_machina's custom commands!".format(
                    command)
            else:
                try:
                    timer = int(user_level)
                    db.modify_command(
                        command=command, response=response,
                        user_level=user_level, channel=channel, timer=timer)
                    return "{0} edited to {1}!".format(
                        command, response)
                except Exception as error:
                    print error
                    return "User level must be \'reg\', \'mod\', or a number"
        else:
            return "{0} not found!".format(command)
    else:
        return "{0} already built in to nano_machina.".format(command)
Exemplo n.º 31
0
def join():
    channel = globals.CURRENT_CHANNEL
    user = globals.CURRENT_USER
    db = Database()
    g = Gamble(channel)
    if g.check_gamble() is not None:
        user_is_already_gambling = g.get_gamble_user(user)
        if user_is_already_gambling:
            return "You're already gambling. Perhaps you need a 12 step program?"
        points = globals.channel_info[
            globals.CURRENT_CHANNEL]['gamble']["points"]
        if db.get_user(user, channel):
            if db.get_user(user, channel)[2] < points:
                return "You don't have enough cash!"
        else:
            return "You've got no cash!"
        globals.channel_info[
            globals.CURRENT_CHANNEL]['gamble']["users"][user] = True
        return "{0} has joined the action and is on the hook for {1} cash!".format(
            user, points)
    else:
        return "There's no gamble to join. Start one with '!gamble [amount]'!"
Exemplo n.º 32
0
 def custom_command(channel, message, username, elements):
     db = Database()
     command = elements[3]
     chan = channel.lstrip("#")
     replacement_user = username
     if len(message) > 1:
         replacement_user = message[1]
     if elements[6] == "mod":
         user_dict, __ = get_dict_for_users()
         if username in user_dict["chatters"]["moderators"]:
             resp = elements[4].replace("{}", replacement_user).replace(
                 "[]", str(elements[5]))
             self.irc.send_message(channel, resp)
             db.increment_command(command, chan)
         else:
             resp = "This is a moderator-only command"
             self.irc.send_message(channel, resp)
     elif elements[6] == "reg":
         resp = elements[4].replace("{}", replacement_user).replace(
             "[]", str(elements[5]))
         self.irc.send_message(channel, resp)
         db.increment_command(command, chan)
Exemplo n.º 33
0
def join():
    channel = globals.CURRENT_CHANNEL
    user = globals.CURRENT_USER
    db = Database()
    g = Gamble(channel)
    if g.check_gamble() is not None:
        user_is_already_gambling = g.get_gamble_user(user)
        if user_is_already_gambling:
            return "You're already gambling. Perhaps you need a 12 step program?"
        points = globals.channel_info[globals.CURRENT_CHANNEL][
            'gamble']["points"]
        if db.get_user(user, channel):
            if db.get_user(user, channel)[2] < points:
                return "You don't have enough cash!"
        else:
            return "You've got no cash!"
        globals.channel_info[globals.CURRENT_CHANNEL]['gamble'][
            "users"][user] = True
        return "{0} has joined the action and is on the hook for {1} cash!".format(
            user, points)
    else:
        return "There's no gamble to join. Start one with '!gamble [amount]'!"
Exemplo n.º 34
0
def edit(args):
    db = Database()
    command = args[0].lower()
    user_level = args[1]
    response = " ".join(args[2:])
    creator = globals.CURRENT_USER
    channel = globals.CURRENT_CHANNEL
    if command[0] is "!":
        if command not in command_headers.commands:
            command_data = db.get_command(command, channel)
            if command_data:
                if user_level == "reg" or user_level == "mod":
                    db.modify_command(command, response, channel, user_level)
                    return "{0} has been changed!".format(command)
                else:
                    return "User level must be 'reg' or 'mod'"
            else:
                return "{0} not found.".format(command)
        else:
            return "{0} already built in to Ravenbot007.".format(command)
    else:
        return "Command must begin with '!'"
Exemplo n.º 35
0
def trigger_clear_bets(chan):
    db = Database()
    bets_data = db.get_all_bets_data()
    
    try:
        #Get the oldest date
        oldest_date = datetime.strptime(bets_data[0][5], "%Y %m %d %H %M %S")
        now = datetime.utcnow()
        if now - oldest_date >= timedelta(30):
            if not os.path.exists(os.path.join('dump')):
                os.makedirs(os.path.join('dump'))
            path = os.path.join("dump", "bets_data_" + datetime.strftime(now, "%Y_%m_%d_%H_%M_%S") + ".csv")
            with open(path, 'wb') as outfile:
                wr = csv.writer(outfile)
                header = ("id", "channel", "username", "amount", "outcome", "date")
                wr.writerow(header)
                for row in bets_data:
                    wr.writerow(row)
            db.clear_bets()
            
    except Exception as error:
        print error
Exemplo n.º 36
0
class BetsThread(Thread):
    def __init__(self, irc, chan, delay):
        Thread.__init__(self, target=self.main)
        self.daemon = True
        self.delay = delay
        self.now = time.time()
        self.chan = chan
        self.channel = self.chan.lstrip("#")
        self.irc = irc
        self.db = Database()

    def main(self):
        begin_resp = "Bets will close in {0} seconds!".format(self.delay)
        end_resp = "Bets are now closed!"
        time_left = "{0} seconds of betting remains!".format(self.delay / 2)
        self.irc.send_message(self.chan, begin_resp)
        time.sleep(float(self.delay / 2))
        self.irc.send_message(self.chan, time_left)
        time.sleep(float(self.delay / 2))
        self.irc.send_message(self.chan, end_resp)
        self.db.set_bets(self.channel, 0)

        sys.exit()
Exemplo n.º 37
0
def gamble(args):
    db = Database()
    try:
        points = int(args[0])
    except:
        return "The points you gamble have to be a number!"
    if points < 10:
        return "The minimum buy-in amount is 10 cash!"
    channel = globals.CURRENT_CHANNEL
    user = globals.CURRENT_USER
    delay = 60
    if db.get_user(user, channel):
        if db.get_user(user, channel)[2] < points:
            return "You don't have enough cash!"
    else:
        return "You've got no cash!"
    g = Gamble(channel)
    if g.check_gamble() is None:
        globals.channel_info[channel]['gamble']["users"][
            user] = points
        initialize(channel, user, delay, points)
    else:
        return "There is already a gamble in progress!"
Exemplo n.º 38
0
class BetsThread(Thread):

    def __init__(self, irc, chan, delay):
        Thread.__init__(self, target=self.main)
        self.daemon = True
        self.delay = delay
        self.now = time.time()
        self.chan = chan
        self.channel = self.chan.lstrip("#")
        self.irc = irc
        self.db = Database()

    def main(self):
        begin_resp = "Bets will close in {0} seconds!".format(self.delay)
        end_resp = "Bets are now closed!"
        time_left = "{0} seconds of betting remains!".format(self.delay / 2)
        self.irc.send_message(self.chan, begin_resp)
        time.sleep(float(self.delay / 2))
        self.irc.send_message(self.chan, time_left)
        time.sleep(float(self.delay / 2))
        self.irc.send_message(self.chan, end_resp)
        self.db.set_bets(self.channel, 0)
        
        sys.exit()
Exemplo n.º 39
0
def chance():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    user = globals.CURRENT_USER
    g = Gamble(channel)
    points = abs(g.rob_yield(multiplier=1))
    db.add_user([user], channel)
    db.modify_points(user, channel, points)
    print user, points, channel
    if points == 0:
        resp = "Nothing this time! Try again in a half hour?"
    else:
        resp = "You got {0} cash!".format(points)
    return resp
Exemplo n.º 40
0
def start():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    bets = db.are_bets(channel)[0]
    if not bets:
        chan = "#" + channel
        irc = globals.irc

        db.set_bets(channel, 1)
        date = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
        db.set_bets_started(channel, date)

        msg = "Bets are open! Type !win or !lose with the amount of points you want to bet, example: !win 200"
        irc.send_message(chan, msg)
        return "You have opened the bets"

    else:
        return "First, resolve current bets"
Exemplo n.º 41
0
def claim():
    username = globals.CURRENT_USER
    channel = globals.CURRENT_CHANNEL
    db = Database()
    points = db.get_points(channel, username)[0]
    if points < 200:
        now = datetime.utcnow()
        str = db.get_last_changed_below_200(channel, username)[0]
        last_changed = datetime.strptime(str, "%Y %m %d %H %M %S")

        if now - last_changed >= timedelta(1):
            db.set_points(channel, username, 200)
            strnow = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
            db.set_last_changed_below_200(channel, username, strnow)
            return "Your points have been reloaded from {0} to 200 points. Points reload once every 24h".format(
                points)

        else:
            return "Sorry, but 24h have not yet passed"

    else:
        return "Sorry, but you have more than 200 points"
Exemplo n.º 42
0
def outcome(args):
    result = args[0]

    if result != "win" and result != "lose":
        return "Sorry, but you didn't specified the outcome. You should write !outcome win/lose"

    else:
        db = Database()
        channel = globals.CURRENT_CHANNEL
        bets = db.are_bets(channel)[0]
        if not bets:
            bts = Bets()
            bts.distribute_profit(result)
            db.set_last_result(channel, result)
            date = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
            #So the outcome won't be used twice for same bets
            db.set_bets_started(channel, date)
        else:
            return "The bets are still going on!"

    return "You have distributed the profit"
Exemplo n.º 43
0
def claim():
    username = globals.CURRENT_USER
    channel = globals.CURRENT_CHANNEL
    db = Database()
    points = db.get_points(channel, username)[0]
    if points < 200:
        now = datetime.utcnow()
        str = db.get_last_changed_below_200(channel, username)[0]
        last_changed = datetime.strptime(str, "%Y %m %d %H %M %S")
        
        if now - last_changed >= timedelta(1):
            db.set_points(channel, username, 200)
            strnow = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
            db.set_last_changed_below_200(channel, username, strnow)
            return "Your points have been reloaded from {0} to 200 points. Points reload once every 24h".format(points)
            
        else:
            return "Sorry, but 24h have not yet passed"
            
    else:
        return "Sorry, but you have more than 200 points"
Exemplo n.º 44
0
def start():
    db = Database()
    channel = globals.CURRENT_CHANNEL
    bets = db.are_bets(channel)[0]
    if not bets:
        chan = "#" + channel
        irc = globals.irc
        
        db.set_bets(channel, 1)
        date = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
        db.set_bets_started(channel, date)
        
        msg = "Bets are open! Type !win or !lose with the amount of points you want to bet, example: !win 200"
        irc.send_message(chan, msg)
        return "You have opened the bets"
        
    else:
        return "First, resolve current bets"
Exemplo n.º 45
0
def gift(args):
    user = globals.CURRENT_USER
    recipient = args[0].lower().lstrip("@")
    channel = globals.CURRENT_CHANNEL
    try:
        amount = abs(int(args[1]))
    except:
        return "Amount has to be a number!"
    if recipient == user:
        return "You can't gift yourself cash!"
    db = Database()
    if db.get_user(user, channel):
        if db.get_user(user, channel)[2] >= amount and db.get_user(
                recipient, channel):
            db.modify_points(recipient, channel, amount)
            db.modify_points(user, channel, amount * -1)
            return "{0} cash has been debited to {1}!".format(
                amount, recipient)
        else:
            return "Those numbers just don't add up. Check your spelling!"
    else:
        return "You don't even have any cash!"
Exemplo n.º 46
0
def cron(channel):
    try:
        channel = channel.lstrip("#")
        from src.lib.twitch import get_stream_status, get_hosts
        from src.lib.channel_data import ChannelData
        from src.lib.queries import Database
        cd = ChannelData(channel)
        if get_stream_status():
            channel_id = cd.get_channel_id_from_db()[0]
            hosts = get_hosts(channel_id)
            unthanked_users = []
            for host in hosts:
                host_data = cd.get_channel_data_by_user(
                    host["host_login"], "host")
                if not host_data:
                    cd.insert_channel_data(host["host_login"], "host")
                    db = Database()
                    db.add_user([host["host_login"]], channel)
                    db.modify_points(host["host_login"], channel, 100)
                    unthanked_users.append(host["host_login"])
            if len(unthanked_users) == 1:
                user = unthanked_users[0]
                resp = "Thank you {0} for the host! Here's 100 cash!".format(
                    user)
                globals.irc.send_message("#" + channel, resp)
            elif len(unthanked_users) > 1:
                import globals
                resp = "The following users are receiving 100 cash for hosting: " + ", ".join(
                    unthanked_users) + "!"
                globals.irc.send_message("#" + channel, resp)
            elif len(unthanked_users) > 10:
                resp = "Thanks to the {0} people hosting! Each of you get 100 cash!".format(
                    len(unthanked_users))
                globals.irc.send_message("#" + channel, resp)
        else:
            cd.remove_channel_data("host")
    except Exception as error:
        print error
Exemplo n.º 47
0
 def __init__(self, channel):
     self.channel = channel
     self.db = Database()
Exemplo n.º 48
0
class ChannelData:
    def __init__(self, channel):
        self.channel = channel
        self.db = Database()

    def get_channel_id_from_twitch(self):
        channel_id = twitch.get_channel_id(self.channel)
        return channel_id

    def get_stream_id_from_twitch(self):
        stream_id = twitch.get_stream_id(self.channel)
        return stream_id

    def get_channel_id_from_db(self):
        channel_id = self.db.get_channel_id(self.channel)
        return channel_id

    def get_stream_id_from_db(self):
        stream_id = self.db.get_stream_id(self.channel)
        return stream_id

    def add_channel_id(self, channel_id):
        self.db.add_channel_id(channel_id, self.channel)

    def update_stream_id(self, stream_id):
        self.db.update_stream_id(self.channel, stream_id)

    def get_channel_data_by_user(self, user, data_type):
        channel_data = self.db.get_channel_data_by_user(
            user, self.channel, data_type)
        return channel_data

    def get_channel_data_by_data_type(self, data_type):
        channel_data = self.db.get_channel_data_by_data_type(
            self.channel, data_type)
        return channel_data

    def insert_channel_data(self, user, data_type):
        self.db.insert_channel_data(user, self.channel, data_type)

    def remove_channel_data(self, data_type):
        self.db.remove_channel_data(self.channel, data_type)
Exemplo n.º 49
0
class Cash:
    def __init__(self, channel):
        self.db = Database()
        self.channel = channel

    def add_all(self, points):
        user_dict, all_users = get_dict_for_users(self.channel)
        self.db.add_user(all_users, self.channel)
        for user in all_users:
            self.db.modify_points([user], self.channel, points)
        return {"users": all_users, "channel": self.channel, "points": points}

    def add(self, users, points):
        self.db.add_user(users, self.channel)
        self.db.modify_points(users[0], self.channel, points)
        return {"user": users[0], "channel": self.channel, "points": points}

    def modify(self, users, points):
        self.db.add_user(users, self.channel)
        self.db.modify_points(users[0], self.channel, points)
        return {"user": users[0], "channel": self.channel, "points": points}

    def get(self, user):
        # (3, u'testuser', 5, u'mod')
        user_data = self.db.get_user(user, self.channel)
        if user_data:
            return {
                "user": user_data[1],
                "channel": self.channel,
                "points": user_data[2]
            }
        else:
            return {"user": user, "channel": self.channel, "points": 0}

    def rank(self, user):
        user_data = self.db.get_cash_rank(user, self.channel)
        if user_data:
            return {
                "user": user_data[0],
                "channel": self.channel,
                "points": user_data[1],
                "rank": user_data[3]
            }
        else:
            return {
                "user": user,
                "channel": self.channel,
                "points": 0,
                "rank": None
            }
Exemplo n.º 50
0
 def __init__(self, channel="testchannel", user="******", points=0):
     self.db = Database()
     self.channel = channel
     self.user = user
     self.points = points
Exemplo n.º 51
0
def trigger_less_than_200_for_all(chan):
    try:
        db = Database()
        channel = chan.lstrip("#")
        str_last_time = db.get_last_time_points_reset(channel)[0]
        if str_last_time:
            now = datetime.utcnow()
            last_time = datetime.strptime(str_last_time, "%Y %m %d %H %M %S")
            if now - last_time >= timedelta(1):
                usernames = db.get_all_usernames()

                for username in usernames:
                    points = db.get_points(username)[0]
                    if points < 200:
                        db.set_points(username, 200)

                strnow = datetime.strftime(datetime.utcnow(),
                                           "%Y %m %d %H %M %S")
                db.set_last_time_points_reset(channel, strnow)
                return "Points have been reloaded for users who have less than 200!"

        else:
            strnow = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
            db.set_last_time_points_reset(channel, strnow)

    except Exception as error:
        print error
Exemplo n.º 52
0
def win(args):
    db = Database()
    channel = globals.CURRENT_CHANNEL
    bets = db.are_bets(channel)[0]

    if bets:
        username = globals.CURRENT_USER

        if db.get_user(username) == None:
            db.add_user([username])
            db.modify_points(username, 1000)

        current_points = db.get_points(username)[0]

        if (args[0][-1] == "%"):
            try:
                percentage = int(args[0].strip("%"))
            except Exception as error:
                print error
                return "Sorry, but your betting amount should be a number or a percentage"
            if percentage > 100:
                return "Sorry, but you can't bet more than a 100%"
            else:
                multiply = float(percentage) / 100
                amount = int(current_points * multiply)

        else:
            try:
                amount = int(args[0])
            except Exception as error:
                print error
                return "Sorry, but your betting amount should be a number or a percentage"
            if amount > current_points:
                return "You currently have {0} points, use them wisely.".format(
                    current_points)

        date = datetime.strftime(datetime.utcnow(), "%Y %m %d %H %M %S")
        db.add_bidder(channel, username, amount, "win", date)
        db.modify_points(username, -amount)
        return "Bet successfully placed! You bet {0} that {1} will win".format(
            amount, channel)

    else:
        return "Sorry, bets were not started yet"