Exemplo n.º 1
0
def update_tips(ctb=None):
    """
    Update page listing all tips
    """

    if not ctb.conf.reddit.stats.enabled:
        return None

    # Start building stats page
    tip_list = "### 25 Most Recent Completed Tips\n\n"

    q = ctb.db.execute(ctb.conf.db.sql.tips.sql_set)
    tips = ctb.db.execute(ctb.conf.db.sql.tips.sql_list, (ctb.conf.db.sql.tips.limit))
    tip_list += ("|".join(tips.keys())) + "\n"
    tip_list += ("|".join([":---"] * len(tips.keys()))) + "\n"

    # Build tips table
    for t in tips:
        values = []
        for k in tips.keys():
            values.append(format_value(t, k, '', ctb, compact=True))
        tip_list += ("|".join(values)) + "\n"

    lg.debug("update_tips(): updating subreddit '%s', page '%s'" % (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page_tips))
    ctb_misc.praw_call(ctb.reddit.edit_wiki_page, ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page_tips, tip_list, "Update by potdealer bot")

    return True
Exemplo n.º 2
0
def update_tips(ctb=None):
    """
    Update page listing all tips
    """

    if not ctb.conf.reddit.stats.enabled:
        return None

    # Start building stats page
    tip_list = "### All Completed Tips\n\n"

    q = ctb.db.execute(ctb.conf.db.sql.tips.sql_set)
    tips = ctb.db.execute(ctb.conf.db.sql.tips.sql_list,
                          (ctb.conf.db.sql.tips.limit))
    tip_list += ("|".join(tips.keys())) + "\n"
    tip_list += ("|".join([":---"] * len(tips.keys()))) + "\n"

    # Build tips table
    for t in tips:
        values = []
        for k in tips.keys():
            values.append(format_value(t, k, '', ctb))
        tip_list += ("|".join(values)) + "\n"

    lg.debug(
        "update_tips(): updating subreddit '%s', page '%s'" %
        (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page_tips))
    ctb_misc.praw_call(ctb.reddit.edit_wiki_page,
                       ctb.conf.reddit.stats.subreddit,
                       ctb.conf.reddit.stats.page_tips, tip_list,
                       "Update by ALTcointip bot")

    return True
Exemplo n.º 3
0
    def gold(self):
        lg.debug('CTBAction:: gold() beginning: ')
        #prep to_user for stupid praw call
        #to_user_prawobj = ctb_misc.praw_call(self.ctb.reddit.get_redditor, self.u_to.name)

        if self.msg_type == 'gold_sent':
            #define the verify response for gilding
            lg.debug('access token found %s',
                     self.ctb.conf.reddit.access_token)

            msg = self.ctb.jenv.get_template('gold-confirm.tpl').render(
                title='wow ^such ^gold', a=self, ctb=self.ctb)

            #try to guild comment
            if self.msg:
                #have to manually call the stupid api
                #set up headers and requests shit for manual api call
                headers = {
                    "Authorization":
                    "bearer " + self.ctb.conf.reddit.access_token,
                    "User-Agent": self.ctb.conf.reddit.auth.user
                }
                parentcomment = ctb_misc.praw_call(self.ctb.reddit.get_info,
                                                   thing_id=self.msg.parent_id)
                while True:
                    lg.debug('trying to gild this fullname %s',
                             parentcomment.fullname)
                    gild_url = 'https://oauth.reddit.com/api/v1/gold/gild/' + parentcomment.fullname
                    lg.debug('CtbAction::gold trying to use this url : %s',
                             gild_url)

                    #api call to gild
                    response = requests.post(gild_url, headers=headers)
                    if response.status_code == 200:
                        lg.debug('CtbAction::gold sent successfully')
                        break
                    else:
                        lg.debug('Gild Api call failed retrying')
                        r_info = json.loads(response.content)
                        lg.debug('got this as result %s', r_info)
                        time.sleep(10)
                        pass

                ctb_misc.praw_call(self.msg.reply, msg)
                lg.info("Gold Verified")
            else:
                lg.info(
                    "CtbAction::gold(): error gilding to user %s no fullname found for message",
                    self.u_to.name)
        lg.debug("< CtbAction::gold() DONE")
        self.clear_queue()
        return True
Exemplo n.º 4
0
def update_stats(ctb=None):
    """
  Update stats wiki page
  """

    stats = ""

    if not ctb.conf.reddit.stats.enabled:
        return None

    for s in sorted(vars(ctb.conf.db.sql.globalstats)):
        lg.debug("update_stats(): getting stats for '%s'" % s)
        sql = ctb.conf.db.sql.globalstats[s].query
        stats += "\n\n### %s\n\n" % ctb.conf.db.sql.globalstats[s].name
        stats += "%s\n\n" % ctb.conf.db.sql.globalstats[s].desc

        mysqlexec = ctb.db.execute(sql)
        if mysqlexec.rowcount <= 0:
            lg.warning("update_stats(): query <%s> returned nothing" %
                       ctb.conf.db.sql.globalstats[s].query)
            continue

        if ctb.conf.db.sql.globalstats[s].type == "line":
            m = mysqlexec.fetchone()
            k = mysqlexec.keys()[0]
            value = format_value(m, k, '', ctb)
            stats += "%s = **%s**\n" % (k, value)

        elif ctb.conf.db.sql.globalstats[s].type == "table":
            stats += ("|".join(mysqlexec.keys())) + "\n"
            stats += ("|".join([":---"] * len(mysqlexec.keys()))) + "\n"
            for m in mysqlexec:
                values = []
                for k in mysqlexec.keys():
                    values.append(format_value(m, k, '', ctb))
                stats += ("|".join(values)) + "\n"

        else:
            lg.error("update_stats(): don't know what to do with type '%s'" %
                     ctb.conf.db.sql.globalstats[s].type)
            return False

        stats += "\n"

    lg.debug("update_stats(): updating subreddit '%s', page '%s'" %
             (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page))

    w = ctb_misc.praw_call(ctb.reddit.subreddit,
                           ctb.conf.reddit.stats.subreddit).wiki
    wp = ctb_misc.praw_call(w.__getitem__, ctb.conf.reddit.stats.page)

    return ctb_misc.praw_call(wp.edit, stats, "Update by ALTcointip bot")
Exemplo n.º 5
0
def update_stats(ctb=None):
    """
    Update stats wiki page
    """

    stats = ""

    if not ctb.conf.reddit.stats.enabled:
        return None

    for s in sorted(vars(ctb.conf.db.sql.globalstats)):
        lg.debug("update_stats(): getting stats for '%s'" % s)
        sql = ctb.conf.db.sql.globalstats[s].query
        stats += "\n\n### %s\n\n" % ctb.conf.db.sql.globalstats[s].name
        stats += "%s\n\n" % ctb.conf.db.sql.globalstats[s].desc

        mysqlexec = ctb.db.execute(sql)
        if mysqlexec.rowcount <= 0:
            lg.warning("update_stats(): query <%s> returned nothing" % ctb.conf.db.sql.globalstats[s].query)
            continue

        if ctb.conf.db.sql.globalstats[s].type == "line":
            m = mysqlexec.fetchone()
            k = mysqlexec.keys()[0]
            value = format_value(m, k, '', ctb)
            stats += "%s = **%s**\n" % (k, value)

        elif ctb.conf.db.sql.globalstats[s].type == "table":
            stats += ("|".join(mysqlexec.keys())) + "\n"
            stats += ("|".join([":---"] * len(mysqlexec.keys()))) + "\n"
            for m in mysqlexec:
                values = []
                for k in mysqlexec.keys():
                    values.append(format_value(m, k, '', ctb))
                stats += ("|".join(values)) + "\n"

        else:
            lg.error("update_stats(): don't know what to do with type '%s'" % ctb.conf.db.sql.globalstats[s].type)
            return False

        stats += "\n"

    lg.debug("update_stats(): updating subreddit '%s', page '%s'" % (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page))
    
    w = ctb_misc.praw_call(ctb.reddit.subreddit, ctb.conf.reddit.stats.subreddit).wiki
    wp = ctb_misc.praw_call(w.__getitem__, ctb.conf.reddit.stats.page)

    return ctb_misc.praw_call(wp.edit, stats, "Update by ALTcointip bot")
Exemplo n.º 6
0
    def is_on_reddit(self):
        """
        Return true if username exists Reddit. Also set prawobj pointer while at it.
        """
        lg.debug("> CtbUser::is_on_reddit(%s)", self.name)

        # Return true if prawobj is already set
        if bool(self.prawobj):
            lg.debug("< CtbUser::is_on_reddit(%s) DONE via OBJ SET (yes)",
                     self.name)
            return True

        self.prawobj = ctb_misc.praw_call(self.ctb.reddit.get_redditor,
                                          self.name)
        if self.prawobj:
            return True
        else:
            return False

        #except Exception as e:
        #lg.debug("< CtbUser::is_on_reddit(%s) DONE (no)", self.name)
        #return False

        lg.warning(
            "< CtbUser::is_on_reddit(%s): returning None (shouldn't happen)",
            self.name)
        return None
Exemplo n.º 7
0
def update_stats(ctb=None):
    """
    Update stats wiki page
    """

    stats = ""

    if not ctb.conf.reddit.stats.enabled:
        return None

    for s in sorted(vars(ctb.conf.db.sql.globalstats)):
        lg.debug("update_stats(): getting stats for '%s'" % s)
        sql = ctb.conf.db.sql.globalstats[s].query
        stats += "\n\n### %s\n\n" % ctb.conf.db.sql.globalstats[s].name
        stats += "%s\n\n" % ctb.conf.db.sql.globalstats[s].desc

        mysqlexec = ctb.db.execute(sql)
        if mysqlexec.rowcount <= 0:
            lg.warning("update_stats(): query <%s> returned nothing" % ctb.conf.db.sql.globalstats[s].query)
            continue

        if ctb.conf.db.sql.globalstats[s].type == "line":
            m = mysqlexec.fetchone()
            k = mysqlexec.keys()[0]
            if k.find("usd") > -1:
                stats += "%s = **$%.2f**\n" % (k, m[k])
            else:
                stats += "%s = **%s**\n" % (k, m[k])
        elif ctb.conf.db.sql.globalstats[s].type == "table":
            stats += ("|".join(mysqlexec.keys())) + "\n"
            stats += ("|".join([":---"] * len(mysqlexec.keys()))) + "\n"
            for m in mysqlexec:
                values = []
                for k in mysqlexec.keys():
                    if type(m[k]) == float and k.find("coin") > -1:
                        values.append("%.8g" % m[k])
                    elif type(m[k]) == float and k.find("fiat") > -1:
                        values.append("$%.2f" % m[k])
                    elif k.find("user") > -1:
                        if m[k] != None:
                            values.append("/u/%s ^[[stats]](/r/%s/wiki/%s_%s)" % (m[k], ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page, m[k]))
                        else:
                            values.append("None")
                    elif k.find("subreddit") > -1:
                        values.append("/r/" + str(m[k]))
                    elif k.find("link") > -1:
                        values.append("[link](%s)" % m[k])
                    else:
                        values.append(str(m[k]))
                stats += ("|".join(values)) + "\n"
        else:
            lg.error("update_stats(): don't know what to do with type '%s'" % ctb.conf.db.sql.globalstats[s].type)
            return False

        stats += "\n"

    lg.debug("update_stats(): updating subreddit '%s', page '%s'" % (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page))
    return ctb_misc.praw_call(ctb.reddit.edit_wiki_page, ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page, stats, "Update by ALTcointip bot")
Exemplo n.º 8
0
    def tell(self, subj=None, msg=None, msgobj=None):
        """
        Send a Reddit message to user
        """
        lg.debug("> CtbUser::tell(%s)", self.name)

        if not bool(subj) or not bool(msg):
            raise Exception("CtbUser::tell(%s): subj or msg not set", self.name)

        if not self.is_on_reddit():
            raise Exception("CtbUser::tell(%s): not a Reddit user", self.name)

        if bool(msgobj):
            lg.debug("CtbUser::tell(%s): replying to message", msgobj.id)
            ctb_misc.praw_call(msgobj.reply, msg)
        else:
            lg.debug("CtbUser::tell(%s): sending message", self.name)
            ctb_misc.praw_call(self.prawobj.message, subj, msg)

        lg.debug("< CtbUser::tell(%s) DONE", self.name)
        return True
Exemplo n.º 9
0
    def tell(self, subj=None, msg=None, msgobj=None):
        """
        Send a Reddit message to user
        """
        lg.debug("> CtbUser::tell(%s)", self.name)

        if not bool(subj) or not bool(msg):
            raise Exception("CtbUser::tell(%s): subj or msg not set", self.name)

        if not self.is_on_reddit():
            raise Exception("CtbUser::tell(%s): not a Reddit user", self.name)

        if bool(msgobj):
            lg.debug("CtbUser::tell(%s): replying to message", msgobj.id)
            ctb_misc.praw_call(msgobj.reply, msg)
        else:
            lg.debug("CtbUser::tell(%s): sending message", self.name)
            ctb_misc.praw_call(self.prawobj.send_message, subj, msg)

        lg.debug("< CtbUser::tell(%s) DONE", self.name)
        return True
Exemplo n.º 10
0
    def is_on_reddit(self):
        """
        Return true if username exists Reddit. Also set prawobj pointer while at it.
        """
        lg.debug("> CtbUser::is_on_reddit(%s)", self.name)

        # Return true if prawobj is already set
        if bool(self.prawobj):
            lg.debug("< CtbUser::is_on_reddit(%s) DONE (yes)", self.name)
            return True

        try:
            self.prawobj = ctb_misc.praw_call(self.ctb.reddit.get_redditor, self.name)
            if self.prawobj:
                return True

        except Exception as e:
            lg.debug("< CtbUser::is_on_reddit(%s) DONE (no)", self.name)
            return False

        lg.warning("< CtbUser::is_on_reddit(%s): returning None (shouldn't happen)", self.name)
        return None
Exemplo n.º 11
0
def update_user_stats(ctb=None, username=None):
    """
    Update individual user stats for given username
    """

    if not ctb.conf.reddit.stats.enabled:
        return None

    # List of coins
    coins_q = ctb.db.execute(ctb.conf.db.sql.userstats.coins)
    coins = []
    for c in coins_q:
        coins.append(c['coin'])

    # List of fiat
    fiat_q = ctb.db.execute(ctb.conf.db.sql.userstats.fiat)
    fiat = []
    for f in fiat_q:
        fiat.append(f['fiat'])

    # Start building stats page
    user_stats = "### Tipping Summary for /u/%s\n\n" % username
    page = ctb.conf.reddit.stats.page + '_' + username

    # Total Tipped
    user_stats += "#### Total Tipped (Fiat)\n\n"
    user_stats += "fiat|total\n:---|---:\n"
    total_tipped = []
    for f in fiat:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_fiat, (username, f))
        total_tipped_fiat = mysqlexec.fetchone()
        if total_tipped_fiat['total_fiat'] != None:
            user_stats += "**%s**|%s %.2f\n" % (f, ctb.conf.fiat[f].symbol, total_tipped_fiat['total_fiat'])
            total_tipped.append("%s%.2f" % (ctb.conf.fiat[f].symbol, total_tipped_fiat['total_fiat']))
    user_stats += "\n"

    user_stats += "#### Total Tipped (Coins)\n\n"
    user_stats += "coin|total\n:---|---:\n"
    for c in coins:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_coin, (username, c))
        total_tipped_coin = mysqlexec.fetchone()
        if total_tipped_coin['total_coin'] != None:
            user_stats += "**%s**|%s %.6f\n" % (c, ctb.conf.coins[c].symbol, total_tipped_coin['total_coin'])
    user_stats += "\n"

    # Total received
    user_stats += "#### Total Received (Fiat)\n\n"
    user_stats += "fiat|total\n:---|---:\n"
    total_received = []
    for f in fiat:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_received_fiat, (username, f))
        total_received_fiat = mysqlexec.fetchone()
        if total_received_fiat['total_fiat'] != None:
            user_stats += "**%s**|%s %.2f\n" % (f, ctb.conf.fiat[f].symbol, total_received_fiat['total_fiat'])
            total_received.append("%s%.2f" % (ctb.conf.fiat[f].symbol, total_received_fiat['total_fiat']))
    user_stats += "\n"

    user_stats += "#### Total Received (Coins)\n\n"
    user_stats += "coin|total\n:---|---:\n"
    for c in coins:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_received_coin, (username, c))
        total_received_coin = mysqlexec.fetchone()
        if total_received_coin['total_coin'] != None:
            user_stats += "**%s**|%s %.6f\n" % (c, ctb.conf.coins[c].symbol, total_received_coin['total_coin'])
    user_stats += "\n"

    # History
    user_stats += "#### History\n\n"
    history = ctb.db.execute(ctb.conf.db.sql.userstats.history, (username, username))
    user_stats += ("|".join(history.keys())) + "\n"
    user_stats += ("|".join([":---"] * len(history.keys()))) + "\n"

    # Build history table
    num_tipped = 0
    num_received = 0
    for m in history:
        if m['state'] == 'completed':
            if m['from_user'].lower() == username.lower():
                num_tipped += 1
            elif m['to_user'].lower() == username.lower():
                num_received += 1
        values = []
        for k in history.keys():
            values.append(format_value(m, k, username, ctb))
        user_stats += ("|".join(values)) + "\n"

    # Submit changes
    lg.debug("update_user_stats(): updating subreddit '%s', page '%s'" % (ctb.conf.reddit.stats.subreddit, page))
    ctb_misc.praw_call(ctb.reddit.edit_wiki_page, ctb.conf.reddit.stats.subreddit, page, user_stats, "Update by ALTcointip bot")

    # Update user flair on subreddit
    if ctb.conf.reddit.stats.userflair and ( len(total_tipped) > 0 or len(total_received) > 0 ):
        flair = ""
        if len(total_tipped) > 0:
            flair += "tipped[" + '|'.join(total_tipped) + "]"
            flair += " (%d)" % num_tipped
        if len(total_received) > 0:
            if len(total_tipped) > 0:
                flair += " / "
            flair += "received[" + '|'.join(total_received) + "]"
            flair += " (%d)" % num_received
        lg.debug("update_user_stats(): updating flair for %s (%s)", username, flair)
        r = ctb_misc.praw_call(ctb.reddit.get_subreddit, ctb.conf.reddit.stats.subreddit)
        res = ctb_misc.praw_call(r.set_flair, username, flair, '')
        lg.debug(res)

    return True
Exemplo n.º 12
0
def update_user_stats(ctb=None, username=None):
    """
    Update individual user stats for given username
    """

    if not ctb.conf.reddit.stats.enabled:
        return None

    # List of coins
    coins_q = ctb.db.execute(ctb.conf.db.sql.userstats.coins)
    coins = []
    for c in coins_q:
        coins.append(c['coin'])

    # List of fiat
    fiat_q = ctb.db.execute(ctb.conf.db.sql.userstats.fiat)
    fiat = []
    for f in fiat_q:
        fiat.append(f['fiat'])

    # Start building stats page
    user_stats = "### Tipping Summary for /u/%s\n\n" % username
    page = ctb.conf.reddit.stats.page + '_' + username

    # Total Tipped
    user_stats += "#### Total Tipped (Fiat)\n\n"
    user_stats += "fiat|total\n:---|---:\n"
    total_tipped = []
    for f in fiat:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_fiat,
                                   (username, f))
        total_tipped_fiat = mysqlexec.fetchone()
        if total_tipped_fiat['total_fiat'] != None:
            user_stats += "**%s**|%s %.2f\n" % (
                f, ctb.conf.fiat[f].symbol, total_tipped_fiat['total_fiat'])
            total_tipped.append(
                "%s%.2f" %
                (ctb.conf.fiat[f].symbol, total_tipped_fiat['total_fiat']))
    user_stats += "\n"

    user_stats += "#### Total Tipped (Coins)\n\n"
    user_stats += "coin|total\n:---|---:\n"
    for c in coins:
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_coin,
                                   (username, c))
        total_tipped_coin = mysqlexec.fetchone()
        if total_tipped_coin['total_coin'] != None:
            user_stats += "**%s**|%s %.6f\n" % (
                c, ctb.conf.coins[c].symbol, total_tipped_coin['total_coin'])
    user_stats += "\n"

    # Total received
    user_stats += "#### Total Received (Fiat)\n\n"
    user_stats += "fiat|total\n:---|---:\n"
    total_received = []
    for f in fiat:
        mysqlexec = ctb.db.execute(
            ctb.conf.db.sql.userstats.total_received_fiat, (username, f))
        total_received_fiat = mysqlexec.fetchone()
        if total_received_fiat['total_fiat'] != None:
            user_stats += "**%s**|%s %.2f\n" % (
                f, ctb.conf.fiat[f].symbol, total_received_fiat['total_fiat'])
            total_received.append(
                "%s%.2f" %
                (ctb.conf.fiat[f].symbol, total_received_fiat['total_fiat']))
    user_stats += "\n"

    user_stats += "#### Total Received (Coins)\n\n"
    user_stats += "coin|total\n:---|---:\n"
    for c in coins:
        mysqlexec = ctb.db.execute(
            ctb.conf.db.sql.userstats.total_received_coin, (username, c))
        total_received_coin = mysqlexec.fetchone()
        if total_received_coin['total_coin'] != None:
            user_stats += "**%s**|%s %.6f\n" % (
                c, ctb.conf.coins[c].symbol, total_received_coin['total_coin'])
    user_stats += "\n"

    # History
    user_stats += "#### History\n\n"
    history = ctb.db.execute(ctb.conf.db.sql.userstats.history,
                             (username, username))
    user_stats += ("|".join(history.keys())) + "\n"
    user_stats += ("|".join([":---"] * len(history.keys()))) + "\n"

    # Build history table
    num_tipped = 0
    num_received = 0
    for m in history:
        if m['state'] == 'completed':
            if m['from_user'].lower() == username.lower():
                num_tipped += 1
            elif m['to_user'].lower() == username.lower():
                num_received += 1
        values = []
        for k in history.keys():
            values.append(format_value(m, k, username, ctb))
        user_stats += ("|".join(values)) + "\n"

    # Submit changes
    lg.debug("update_user_stats(): updating subreddit '%s', page '%s'" %
             (ctb.conf.reddit.stats.subreddit, page))
    ctb_misc.praw_call(ctb.reddit.edit_wiki_page,
                       ctb.conf.reddit.stats.subreddit, page, user_stats,
                       "Update by ALTcointip bot")

    # Update user flair on subreddit
    if ctb.conf.reddit.stats.userflair and (len(total_tipped) > 0
                                            or len(total_received) > 0):
        flair = ""
        if len(total_tipped) > 0:
            flair += "tipped[" + '|'.join(total_tipped) + "]"
            flair += " (%d)" % num_tipped
        if len(total_received) > 0:
            if len(total_tipped) > 0:
                flair += " / "
            flair += "received[" + '|'.join(total_received) + "]"
            flair += " (%d)" % num_received
        lg.debug("update_user_stats(): updating flair for %s (%s)", username,
                 flair)
        r = ctb_misc.praw_call(ctb.reddit.get_subreddit,
                               ctb.conf.reddit.stats.subreddit)
        res = ctb_misc.praw_call(r.set_flair, username, flair, '')
        lg.debug(res)

    return True
Exemplo n.º 13
0
    def givetip(self):
        lg.debug('> CtbAction::givetip()')

        if self.msg_type == "tip_sent_sneaky":
            lg.debug(
                'CtbAction::givetip() withdraw/tip to address sneaky sent ')
            balance_avail = Decimal(self.balance)
            my_addr = self.addr_from
            msg = self.ctb.jenv.get_template(
                'withdraw-sneaky-from.tpl').render(addr=my_addr,
                                                   balance=balance_avail,
                                                   a=self,
                                                   ctb=self.ctb)
            lg.debug("CtbAction::givetip(): tip_sent_sneaky: " + msg)
            self.u_from.tell(subj="you got some dogecoins", msg=msg)

        if self.msg_type == "tip_received_sneaky":
            lg.debug(
                'CtbAction::givetip() withdraw/tip to address sneaky received '
            )
            balance_avail = Decimal(self.balance)
            my_addr = self.addr_to
            msg = self.ctb.jenv.get_template('withdraw-sneaky-to.tpl').render(
                addr=my_addr, balance=balance_avail, a=self, ctb=self.ctb)
            lg.debug("CtbAction::givetip(): tip_received_sneaky: " + msg)
            self.u_to.tell(subj="you withdrew some dogecoins", msg=msg)

        if self.msg_type == 'addr_invalid':
            lg.debug('CtbAction::givetip() Address Invalid ')
            msg = self.ctb.jenv.get_template('address-invalid.tpl').render(
                a=self, ctb=self.ctb)
            lg.debug("CtbAction::error(): addr_invalid: " + msg)
            self.u_from.tell(subj="+tip failed", msg=msg)

        if self.type == 'withdraw' and self.msg_type not in [
                'tip_received_sneaky', 'tip_sent_sneaky'
        ]:
            msg = self.ctb.jenv.get_template('confirmation.tpl').render(
                title='wow ^so ^verify', a=self, ctb=self.ctb)
            lg.debug("CtbAction::givetip(): ATTEMPTING-WITHDRAW" + msg)
            if (self.verify or self.coin_val >= 1000):
                #if not ctb_misc.praw_call(self.msg.reply, msg):
                self.u_from.tell(subj="+withdraw succeeded", msg=msg)
                lg.debug("< CtbAction::givetip() DONE")
                self.clear_queue()
                return True
            else:
                self.u_from.tell(subj="+withdraw succeeded", msg=msg)
                lg.debug("< CtbAction::givetip() DONE")
                self.clear_queue()
                return True

        if self.msg_type == 'tip_received':
            if self.is_new_shibe:
                balance_avail = Decimal(self.balance)
                my_addr = self.addr_to
                msg = self.ctb.jenv.get_template('tip-received.tpl').render(
                    addr=my_addr, balance=balance_avail, a=self, ctb=self.ctb)
                lg.debug("CtbAction::givetip(): " + msg)
                self.u_to.tell(subj="+tip received", msg=msg)
            else:
                lg.debug("CtbAction::givetip(): OLD SHIBE. NO MESSAGE.")

        # Send confirmation to u_from
        # note to change code to add withdrawal if not to_addr
        if self.msg_type == 'tip_sent':
            if self.is_new_shibe:
                balance_avail = Decimal(self.balance)
                my_addr = self.addr_from
                msg = self.ctb.jenv.get_template('tip-sent.tpl').render(
                    addr=my_addr, balance=balance_avail, a=self, ctb=self.ctb)
                lg.debug("CtbAction::givetip(): ATTMEPTING TIP-SENT" + msg)
                self.u_from.tell(subj="+tip sent", msg=msg)
            else:
                lg.debug("CtbAction::givetip(): OLD SHIBE. NO MESSAGE.")

            if self.verify or self.coin_val >= 1000:
                lg.debug("CtbAction::givetip(): action being verified: %s ",
                         self)
                msg = self.ctb.jenv.get_template(
                    'tip-confirmation.tpl').render(title='wow ^so ^verify',
                                                   a=self,
                                                   ctb=self.ctb)
                lg.debug("CtbAction::givetip(): " + msg)
                if self.msg:
                    if self.ctb.conf.reddit.messages.verified:

                        ctb_misc.praw_call(self.msg.reply, msg)

                        lg.info("-------------------VERIFIED!: %s",
                                self.verify)
                    else:
                        lg.info("NO FULLNAME CANT VERIFY for")
        lg.debug("< CtbAction::givetip() DONE")
        self.clear_queue()
        return True
Exemplo n.º 14
0
def eval_pull_message(msg, ctb):
    """
    Turn the Message from the pull queue into an action
    """
    lg.debug("> eval_pull_message()")
    queue_id = msg['id'] if 'id' in msg else ''
    reservation_id = msg['reservation_id'] if 'reservation_id' in msg else ''
    message = json.loads(msg['body'])
    lg.debug(">eval_pull_message() %s", message)
    service = message.get('service', None)
    if service != 'reddit' or service is None:
        lg.debug('eval_pull_message() SERVICE NOT REDDIT')
        return False

    is_new_shibe = message.get('is_new_shibe', None)
    verify = message.get('config5', None)
    fullname = message.get('config2', None)
    comment = None
    if fullname:
        comment = ctb_misc.praw_call(ctb.reddit.get_info, thing_id=fullname)
        #comment = ctb.reddit.get_info(thing_id=fullname)
        if comment:
            subreddit = comment.subreddit
        else:
            subreddit = None
    else:
        comment = None
        subreddit = None
    u_from = message.get('u_from', None)
    u_to = message.get('u_to', None)
    action = message.get('command', None)
    coin = 'dog'
    amount = message.get('coinval', None)
    to_addr = message.get('addr_to', None)
    msg_type = message.get('type', None)
    txid = message.get('txid', None)
    addr_from = message.get('addr_from', None)
    total_doge_sent = message.get('total_doge_sent', None)
    total_doge_received = message.get('total_doge_received', None)
    history = message.get('history', [])
    associated = message.get('associated', None)
    balance = message.get('balance', None)
    fiatval = message.get('fiatval', None)
    total_fiat_received = message.get('total_fiat_received', 0)
    total_fiat_sent = message.get('total_fiat_sent', 0)

    return CtbAction(atype=action,
                     from_user=u_from,
                     msg=comment,
                     to_user=u_to,
                     to_addr=to_addr,
                     coin=coin,
                     verify=verify,
                     coin_val=amount,
                     subr=subreddit,
                     is_pull_queue=True,
                     is_new_shibe=is_new_shibe,
                     msg_type=msg_type,
                     txid=txid,
                     addr_from=addr_from,
                     total_doge_sent=total_doge_sent,
                     total_doge_received=total_doge_received,
                     history_list=history,
                     associated=associated,
                     balance=balance,
                     fiat_val=fiatval,
                     queue_id=queue_id,
                     reservation_id=reservation_id,
                     total_fiat_received=total_fiat_received,
                     total_fiat_sent=total_fiat_sent,
                     ctb=ctb)
Exemplo n.º 15
0
def eval_comment(comment, ctb):
    """
    Evaluate comment body and  and insert into the pending_action
    database if successful
    """
    lg.debug("> eval_comment()")

    body = comment.body
    for r in ctb.runtime['regex']:
        # Skip non-public actions

        if not ctb.conf.regex.actions[r.action].public:
            continue

        # Attempt a match
        rg = re.compile(r.regex, re.IGNORECASE | re.DOTALL)
        lg.debug("eval_comment(): matching '%s' with <%s>", comment.body,
                 r.regex)
        m = rg.search(body)

        if m:
            # Match found
            lg.debug("eval_comment(): match found")

            # Extract matched fields into variables
            u_to = m.group(r.rg_to_user)[1:] if r.rg_to_user > 0 else None
            to_addr = m.group(r.rg_address) if r.rg_address > 0 else None
            amount = m.group(r.rg_amount) if r.rg_amount > 0 else None
            keyword = m.group(r.rg_keyword) if r.rg_keyword > 0 else None
            verify = m.group(r.rg_verify) if r.rg_verify > 0 else None
            if keyword is not None:
                keyword = keyword.lower()
                lg.debug("eval_message(): keyword %s", keyword)
                if keyword == 'all':
                    amount = 'all'
                else:
                    amount = ctb.conf.keywords[keyword].value
                    if type(amount) == str:
                        amount = eval(amount)
                    elif type(amount) == float:
                        amount = Decimal(amount)
            # If no destination mentioned, find parent submission's author
            if not u_to and not to_addr:
                # set u_to to author of parent comment
                parentcomment = ctb_misc.praw_call(ctb.reddit.get_info,
                                                   thing_id=comment.parent_id)
                #parentcomment = ctb.reddit.get_info(thing_id=comment.parent_id)
                u_to = parentcomment.author
                if u_to is not None:
                    u_to = parentcomment.author.name
                else:
                    # couldn't determine u_to, giving up
                    lg.warning("eval_comment(): couldn't find u_to")
                    return None

            # Check if from_user == to_user
            if u_to and comment.author.name.lower() == u_to.lower():
                lg.warning(
                    "eval_comment(): comment.author.name == u_to, ignoring comment"
                )
                return None

            # Check if subreddit == promos
            if comment.subreddit == 'promos':
                return None

            # Return CtbAction instance with given variables
            lg.debug(
                "eval_comment(): creating action %s: to_user=%s, to_addr=%s, amount=%s, coin=%s, fiat=%s"
                % (r.action, u_to, to_addr, amount, r.coin, r.fiat))
            #lg.debug("< eval_comment() DONE (yes)")
            if verify:
                lg.info("appending verify with this: %s", verify)
            return CtbAction(atype=r.action,
                             msg=comment,
                             to_user=u_to,
                             to_addr=to_addr,
                             coin=r.coin,
                             verify=verify,
                             coin_val=amount if not r.fiat else None,
                             fiat=r.fiat,
                             fiat_val=amount if r.fiat else None,
                             keyword=keyword,
                             subr=comment.subreddit,
                             ctb=ctb)

    # No match found
    lg.debug("< eval_comment() DONE (no match)")
    return None
Exemplo n.º 16
0
def update_user_stats(ctb=None, username=None):
    """
    Update individual user stats for given username
    """

    if not ctb.conf.reddit.stats.enabled:
        return None

    # Build a list of coins
    coins_q = ctb.db.execute(ctb.conf.db.sql.userstats.coins)
    coins = []

    for c in coins_q:
        coins.append(c['coin'])

        user_stats = "### Tipping Summary For /u/%s\n\n" % username
        page = ctb.conf.reddit.stats.page + '_' + username

        # Total Tipped
        user_stats += "#### Total Tipped (USD)\n\n"
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_fiat, (username))
        total_tipped_fiat = mysqlexec.fetchone()
        if total_tipped_fiat['total_fiat'] == None:
            user_stats += "**total_tipped_fiat = $%.2f**\n\n" % 0.0
        else:
            user_stats += "**total_tipped_fiat = $%.2f**\n\n" % total_tipped_fiat['total_fiat']

        user_stats += "#### Total Tipped (Coins)\n\n"
        user_stats += "coin|total\n:---|---:\n"
        for c in coins:
            mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_tipped_coin, (username, c))
            total_tipped_coin = mysqlexec.fetchone()
            if total_tipped_coin['total_coin'] == None:
                user_stats += "%s|%.8g\n" % (c, 0.0)
            else:
                user_stats += "%s|%.8g\n" % (c, total_tipped_coin['total_coin'])
        user_stats += "\n"

        # Total received
        user_stats += "#### Total Received (USD)\n\n"
        mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_received_fiat, (username))
        total_received_fiat = mysqlexec.fetchone()
        if total_received_fiat['total_fiat'] == None:
            user_stats += "**total_received_fiat = $%.2f**\n\n" % 0.0
        else:
            user_stats += "**total_received_fiat = $%.2f**\n\n" % total_received_fiat['total_fiat']

        user_stats += "#### Total Received (Coins)\n\n"
        user_stats += "coin|total\n:---|---:\n"
        for c in coins:
            mysqlexec = ctb.db.execute(ctb.conf.db.sql.userstats.total_received_coin, (username, c))
            total_received_coin = mysqlexec.fetchone()
            if total_received_coin['total_coin'] == None:
                user_stats += "%s|%.8g\n" % (c, 0.0)
            else:
                user_stats += "%s|%.8g\n" % (c, total_received_coin['total_coin'])
        user_stats += "\n"

        # History
        user_stats += "#### History\n\n"
        history = ctb.db.execute(ctb.conf.db.sql.userstats.history, (username, username))
        user_stats += ("|".join(history.keys())) + "\n"
        user_stats += ("|".join([":---"] * len(history.keys()))) + "\n"

        # Build history table
        for m in history:
            values = []
            for k in history.keys():
                # Format cryptocoin
                if type(m[k]) == float and k.find("coin") > -1:
                    coin_symbol = ctb.conf.coins[m['coin']].symbol
                    values.append("%s%.8g" % (coin_symbol, m[k]))
                # Format fiat
                elif type(m[k]) == float and k.find("fiat") > -1:
                    fiat_symbol = ctb.conf.fiat[m['fiat']].symbol
                    values.append("%s%.2f" % (fiat_symbol, m[k]))
                # Format username
                elif k.find("user") > -1:
                    if m[k] != None:
                        un = ("**%s**" % username) if m[k].lower() == username.lower() else m[k]
                        toappend = "[%s](/u/%s)" % (un, re.escape(m[k]))
                        if m[k].lower() != username.lower():
                            toappend += " ^[[stats]](/r/%s/wiki/%s_%s)" % (ctb.conf.reddit.stats.subreddit, ctb.conf.reddit.stats.page, m[k])
                        values.append(toappend)
                    else:
                        values.append("None")
                # Format address
                elif k.find("addr") > -1:
                    if m[k] != None:
                        displayaddr = m[k][:6] + "..." + m[k][-5:]
                        values.append("[%s](%s)" % (displayaddr, ctb.conf.coins[m['coin']].explorer.address + m[k]))
                    else:
                        values.append("None")
                # Format state
                elif k.find("state") > -1:
                    if m[k] == "completed":
                        values.append("**%s**" % m[k])
                    else:
                        values.append(m[k])
                # Format subreddit
                elif k.find("subreddit") > -1:
                    values.append("/r/" + str(m[k]))
                # Format link
                elif k.find("link") > -1:
                    values.append("[link](%s)" % m[k])
                # Format time
                elif k.find("utc") > -1:
                    values.append("%s" % time.strftime('%Y-%m-%d', time.localtime(m[k])))
                else:
                    values.append(str(m[k]))

            user_stats += ("|".join(values)) + "\n"

    lg.debug("update_user_stats(): updating subreddit '%s', page '%s'" % (ctb.conf.reddit.stats.subreddit, page))
    ctb_misc.praw_call(ctb.reddit.edit_wiki_page, ctb.conf.reddit.stats.subreddit, page, user_stats, "Update by ALTcointip bot")

    return True