Ejemplo n.º 1
0
def check_registered_by_address(address):
    address = address.split("_")[1]

    if shared.CURRENCY == "Nano":
        sql = "SELECT username FROM accounts WHERE address=%s"
        val = ("nano_" + address,)
        MYCURSOR.execute(sql, val)
        result = MYCURSOR.fetchall()
        if len(result) > 0:
            return result[0][0]

        sql = "SELECT username FROM accounts WHERE address=%s"
        val = ("xrb_" + address,)
        MYCURSOR.execute(sql, val)
        result = MYCURSOR.fetchall()
        if len(result) > 0:
            return result[0][0]
    elif shared.CURRENCY == "Banano":
        sql = "SELECT username FROM accounts WHERE address=%s"
        val = ("ban_" + address,)
        MYCURSOR.execute(sql, val)
        result = MYCURSOR.fetchall()
        if len(result) > 0:
            return result[0][0]
    return None
Ejemplo n.º 2
0
def messages():
    MYCURSOR.execute("SHOW COLUMNS FROM messages")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)

    MYCURSOR.execute("SELECT * FROM messages")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)
Ejemplo n.º 3
0
def list_columns():
    MYCURSOR.execute("SHOW COLUMNS FROM history")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)
    print("*****")
    MYCURSOR.execute("SHOW COLUMNS FROM accounts")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)
Ejemplo n.º 4
0
def subreddits():
    MYCURSOR.execute("SHOW COLUMNS FROM subreddits")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)

    MYCURSOR.execute("SELECT * FROM subreddits")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)
Ejemplo n.º 5
0
def handle_projects(message):
    """
    Handles creation and updates of crowdfunding (NanoCenter) projects
    """
    parsed_text = parse_text(str(message.body))
    response = text.CROWD_FUNDING["projects"]
    if (str(message.author).lower()
            in DONATION_ADMINS + TIPBOT_OWNER) and len(parsed_text) > 2:
        sql = "INSERT INTO projects (project, address) VALUES(%s, %s) ON DUPLICATE KEY UPDATE address=%s"
        val = (parsed_text[1], parsed_text[2], parsed_text[2])
        MYCURSOR.execute(sql, val)
        MYDB.commit()
    add_history_record(
        username=str(message.author),
        action="project",
        comment_text=str(message.body)[:255],
        comment_or_message="message",
        comment_id=message.name,
    )

    sql = "SELECT project, address FROM projects"
    MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    for result in results:
        response += "%s %s  \n" % (result[0], result[1])
    return response
Ejemplo n.º 6
0
def handle_create(message):
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    add_history_record(
        username=str(message.author),
        comment_or_message="message",
        reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
        action="create",
        comment_id=message.name,
        comment_text=str(message.body)[:255],
    )

    username = str(message.author)
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) is 0:
        address = tipper_functions.add_new_account(username)["address"]
        response = WELCOME_CREATE % (address, address)
        message_recipient = TIP_BOT_USERNAME
        subject = "send"
        message_text = "send 0.001 %s" % username
        sql = "INSERT INTO messages (username, subject, message) VALUES (%s, %s, %s)"
        val = (message_recipient, subject, message_text)
        MYCURSOR.execute(sql, val)
        MYDB.commit()

        # reddit.redditor(message_recipient).message(subject, message_text)

    else:
        response = text.ALREADY_EXISTS % (result[0][0], result[0][0])
    return response
Ejemplo n.º 7
0
def auto_receive():
    count = 0
    MYCURSOR.execute("SELECT username, address, private_key FROM accounts")
    myresult = MYCURSOR.fetchall()

    addresses = [str(result[1]) for result in myresult]
    private_keys = [str(result[2]) for result in myresult]
    MYDB.commit()
    pendings = get_pendings(addresses, threshold=nano_to_raw(PROGRAM_MINIMUM))
    # get any pending blocks from our address
    for address, private_key in zip(addresses, private_keys):
        # allow 5 transactions to be received per cycle. If the bot gets transaction spammed, at least it won't be
        # locked up receiving.
        if count >= 5:
            break
        try:
            if pendings["blocks"][address]:
                for sent_hash in pendings["blocks"][address]:
                    # address, private_key, dictionary where the blocks are the keys
                    open_or_receive_block(address, private_key, sent_hash)
                    count += 1
                    if count >= 2:
                        break

        except KeyError:
            pass
        except Exception as e:
            print(e)
Ejemplo n.º 8
0
def get_user_settings(recipient_username, recipient_address=""):
    """

    :param recipient_username: str
    :param recipient_address: str
    :return: 3 items to unpack - int, str, bool
    """
    user_minimum = -1
    silence = False
    if recipient_username:
        sql = "SELECT minimum, address, silence FROM accounts WHERE username = %s"
        val = (recipient_username,)
        MYCURSOR.execute(sql, val)
        myresult = MYCURSOR.fetchall()
        if len(myresult) > 0:
            user_minimum = int(myresult[0][0])
            silence = myresult[0][2]
            if not recipient_address:
                recipient_address = myresult[0][1]
    return {
        "name": recipient_username,
        "minimum": user_minimum,
        "address": recipient_address,
        "silence": silence,
    }
Ejemplo n.º 9
0
def handle_balance(message):
    username = str(message.author)
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    add_history_record(
        username=str(message.author),
        comment_or_message="message",
        reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
        action="balance",
        comment_id=message.name,
        comment_text=str(message.body)[:255],
    )
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        results = check_balance(result[0][0])

        response = (
            "At address %s:\n\nAvailable: %s Nano\n\nUnpocketed: %s Nano\n\nNano "
            "will be pocketed automatically unless the transaction is below "
            "0.0001 Nano."
            "\n\nhttps://nanocrawler.cc/explorer/account/%s" %
            (result[0][0], results[0] / 10**30, results[1] / 10**30,
             result[0][0]))

        return response
    return "You do not have an open account yet"
Ejemplo n.º 10
0
def handle_balance(message):
    username = str(message.author)
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    add_history_record(
        username=str(message.author),
        comment_or_message="message",
        reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
        action="balance",
        comment_id=message.name,
        comment_text=str(message.body)[:255],
    )
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        results = check_balance(result[0][0])

        response = text.BALANCE % (
            result[0][0],
            from_raw(results[0]),
            from_raw(results[1]),
            result[0][0],
        )

        return response
    return text.NOT_OPEN
Ejemplo n.º 11
0
def list_messages():
    MYCURSOR.execute("SELECT * FROM messages")
    myresult = MYCURSOR.fetchall()
    MYDB.commit()
    for res in myresult:
        print(res)
    return myresult
Ejemplo n.º 12
0
def history(num_records, username=None):
    MYCURSOR.execute("SHOW COLUMNS FROM history")
    myresult = MYCURSOR.fetchall()
    for result in myresult:
        print(result)
    if username:
        MYCURSOR.execute(
            "SELECT * FROM history WHERE username = '******' ORDER BY id DESC limit %s"
            % (username, num_records)
        )
    else:
        MYCURSOR.execute(
            "SELECT * FROM history ORDER BY id DESC limit %s" % num_records
        )
    myresult = MYCURSOR.fetchall()
    for result in reversed(myresult):
        print(result)
Ejemplo n.º 13
0
def backup_keys():
    sql = "SELECT username, address, private_key FROM accounts"
    MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    MYDB.commit()
    with open("../backup", "w") as f:
        for result in results:
            f.write(result[0] + "," + result[1] + "," + result[2] + "\n")
Ejemplo n.º 14
0
def query_sql(sql, val=None):
    if val:
        MYCURSOR.execute(sql, val)
    else:
        MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    MYDB.commit()
    return results
Ejemplo n.º 15
0
def backup_history():
    sql = "SELECT * FROM history"
    MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    MYDB.commit()
    with open("../backup_history", "w") as f:
        for result in results:
            for r in result:
                f.write(str(r) + ";")
            f.write("\n")
Ejemplo n.º 16
0
def list_returns(status=None):
    if status:
        MYCURSOR.execute("SELECT * FROM returns WHERE return_status=%s", (status,))
    else:
        MYCURSOR.execute("SELECT * FROM returns")
    myresult = MYCURSOR.fetchall()
    MYDB.commit()
    for res in myresult:
        print(res)
    return myresult
Ejemplo n.º 17
0
def message_in_database(message):
    sql = "SELECT * FROM history WHERE comment_id = %s"
    val = (message.name,)
    MYCURSOR.execute(sql, val)
    results = MYCURSOR.fetchall()
    if len(results) > 0:
        LOGGER.info("Found previous messages for %s: " % message.name)
        for result in results:
            LOGGER.info(result)
        return True
    return False
Ejemplo n.º 18
0
def all_pendings(threshold):
    threshold = float(threshold)
    MYCURSOR.execute("SELECT username, address FROM accounts")
    myresult = MYCURSOR.fetchall()
    usernames = [str(result[0]) for result in myresult]
    addresses = [str(result[1]) for result in myresult]

    MYDB.commit()
    pendings = tipper_rpc.get_pendings(addresses, threshold=to_raw(threshold))
    for username, address in zip(usernames, addresses):
        if pendings["blocks"][address]:
            print(username, address, pendings["blocks"][address])
Ejemplo n.º 19
0
def send_pm(recipient, subject, body, bypass_opt_out=False):
    opt_in = True
    # If there is not a bypass to opt in, check the status
    if not bypass_opt_out:
        sql = "SELECT opt_in FROM accounts WHERE username=%s"
        MYCURSOR.execute(sql, (recipient,))
        opt_in = MYCURSOR.fetchall()[0][0]
        MYDB.commit()

    # if the user has opted in, or if there is an override to send the PM even if they have not
    if opt_in or not bypass_opt_out:
        sql = "INSERT INTO messages (username, subject, message) VALUES (%s, %s, %s)"
        val = (recipient, subject, body)
        MYCURSOR.execute(sql, val)
        MYDB.commit()
Ejemplo n.º 20
0
def total_funds():
    MYCURSOR.execute("SELECT username, address FROM accounts")
    myresult = MYCURSOR.fetchall()
    usernames = [str(result[0]) for result in myresult]
    addresses = [str(result[1]) for result in myresult]
    MYDB.commit()
    balance = 0
    for username, address in zip(usernames, addresses):
        balance
        new_balance = tipper_rpc.check_balance(address)
        temp_balance = new_balance[0] / 10**30 + new_balance[1] / 10**30
        if temp_balance >= 50:
            print(username, temp_balance, address)
        balance += temp_balance
    print("Total Nano: ", balance)
Ejemplo n.º 21
0
def handle_delete_project(message):
    parsed_text = parse_text(str(message.body))
    if ((str(message.author) == TIPBOT_OWNER) or
        (str(message.author).lower()
         == "rockmsockmjesus")) and len(parsed_text) > 1:
        sql = "DELETE FROM projects WHERE project=%s"
        val = (parsed_text[1], )
        MYCURSOR.execute(sql, val)
        MYDB.commit()
    response = text.CROWD_FUNDING["projects"]
    sql = "SELECT project, address FROM projects"
    MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    for result in results:
        response += "%s %s  \n" % (result[0], result[1])
    return response
Ejemplo n.º 22
0
def allowed_request(username, seconds=30, num_requests=5):
    """Spam prevention
    :param username: str (username)
    :param seconds: int (time period to allow the num_requests)
    :param num_requests: int (number of allowed requests)
    :return:
    """
    sql = "SELECT sql_time FROM history WHERE username=%s"
    val = (str(username), )
    MYCURSOR.execute(sql, val)
    myresults = MYCURSOR.fetchall()
    if len(myresults) < num_requests:
        return True
    else:
        return (datetime.fromtimestamp(time.time()) -
                myresults[-5][0]).total_seconds() > seconds
Ejemplo n.º 23
0
def handle_receive(message):
    """

    :param message:
    :return:
    """
    message_time = datetime.utcfromtimestamp(message.created_utc)
    username = str(message.author)
    # find any accounts associated with the redditor
    sql = "SELECT address, private_key FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        address = result[0][0]
        open_or_receive(address, result[0][1])
        balance = check_balance(address)
        add_history_record(
            username=username,
            action="receive",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            address=address,
            comment_id=message.name,
            comment_or_message="message",
        )
        response = (
            "At address %s, you currently have %s Nano available, and %s Nano "
            "unpocketed. If you have any unpocketed, create a new "
            "message containing the word "
            "'receive'\n\nhttps://nanocrawler.cc/explorer/account/%s" %
            (address, balance[0] / 10**30, balance[1] / 10**30, address))
        return response
    else:
        add_history_record(
            username=username,
            action="receive",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            comment_id=message.name,
            comment_or_message="message",
        )
        response = (
            "You do not currently have an account open. To create one, "
            "respond with the text 'create' in the message body.")
        return response
Ejemplo n.º 24
0
def handle_receive(message):
    """

    :param message:
    :return:
    """
    message_time = datetime.utcfromtimestamp(message.created_utc)
    username = str(message.author)
    # find any accounts associated with the redditor
    sql = "SELECT address, private_key FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        address = result[0][0]
        open_or_receive(address, result[0][1])
        balance = check_balance(address)
        add_history_record(
            username=username,
            action="receive",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            address=address,
            comment_id=message.name,
            comment_or_message="message",
        )
        response = text.RECEIVE["balance"] % (
            address,
            from_raw(balance[0]),
            from_raw(balance[1]),
            address,
        )
        return response
    else:
        add_history_record(
            username=username,
            action="receive",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            comment_id=message.name,
            comment_or_message="message",
        )
        response = text.NOT_OPEN
        return response
Ejemplo n.º 25
0
def handle_create(message):
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    add_history_record(
        username=str(message.author),
        comment_or_message="message",
        reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
        action="create",
        comment_id=message.name,
        comment_text=str(message.body)[:255],
    )

    username = str(message.author)
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) is 0:
        address = tipper_functions.add_new_account(username)
        response = WELCOME_CREATE % (address, address)
        message_recipient = TIP_BOT_USERNAME
        subject = "send"
        message_text = "send 0.001 %s" % username
        sql = "INSERT INTO messages (username, subject, message) VALUES (%s, %s, %s)"
        val = (message_recipient, subject, message_text)
        MYCURSOR.execute(sql, val)
        MYDB.commit()

        # reddit.redditor(message_recipient).message(subject, message_text)

    else:
        response = (
            "It looks like you already have an account. In any case it is now "
            "**active**. Your Nano address is %s."
            "\n\nhttps://nanocrawler.cc/explorer/account/%s" %
            (result[0][0], result[0][0]))
    return response
Ejemplo n.º 26
0
from time import sleep
from shared import MYDB, MYCURSOR, REDDIT, LOGGER

while True:
    sql = "SELECT * FROM messages"
    MYCURSOR.execute(sql)
    results = MYCURSOR.fetchall()
    MYDB.commit()

    for result in results:
        LOGGER.info("%s %s %s %s" %
                    (result[1], result[2], result[4], repr(result[3])[:50]))

        try:
            # find the message to reply to it.
            if result[4] is not None:
                msg = REDDIT.inbox.message(result[4].replace("t4_", ""))
                msg.reply(str(result[3]))
            # if it was a comment, create a new message
            else:
                REDDIT.redditor(str(result[1])).message(
                    str(result[2]), str(result[3]))
        except:
            pass
        sql = "DELETE FROM messages WHERE id = %s"
        val = (result[0], )
        MYCURSOR.execute(sql, val)
        MYDB.commit()

    sleep(6)
Ejemplo n.º 27
0
def handle_minimum(message):
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    # user may select a minimum tip amount to avoid spamming. Tipbot minimum is 0.001
    username = str(message.author)
    # find any accounts associated with the redditor
    parsed_text = parse_text(str(message.body))

    # there should be at least 2 words, a minimum and an amount.
    if len(parsed_text) < 2:
        response = ("I couldn't parse your command. I was expecting 'minimum "
                    "<amount>'. Be sure to check your spacing.")
        return response
    # check that the minimum is a number

    if parsed_text[1].lower() == "nan" or ("inf" in parsed_text[1].lower()):
        response = ("'%s' didn't look like a number to me. If it is blank, "
                    "there might be extra spaces in the command.")
        return response
    try:
        amount = float(parsed_text[1])
    except:
        response = ("'%s' didn't look like a number to me. If it is blank, "
                    "there might be extra spaces in the command.")
        return response

    # check that it's greater than 0.01
    if nano_to_raw(amount) < nano_to_raw(PROGRAM_MINIMUM):
        response = (
            "Did not update. The amount you specified is below the program minimum "
            "of %s Nano." % PROGRAM_MINIMUM)
        return response

    # check if the user is in the database
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        # open_or_receive(result[0][0], result[0][1])
        # balance = check_balance(result[0][0])
        add_history_record(
            username=username,
            action="minimum",
            amount=nano_to_raw(amount),
            address=result[0][0],
            comment_or_message="message",
            comment_id=message.name,
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            comment_text=str(message.body)[:255],
        )
        sql = "UPDATE accounts SET minimum = %s WHERE username = %s"
        val = (str(nano_to_raw(amount)), username)
        MYCURSOR.execute(sql, val)
        MYDB.commit()
        response = "Updating tip minimum to %s" % amount
        return response
    else:
        add_history_record(
            username=username,
            action="minimum",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            amount=nano_to_raw(amount),
            comment_id=message.name,
            comment_text=str(message.body)[:255],
        )
        response = (
            "You do not currently have an account open. To create one, "
            "respond with the text 'create' in the message body.")
        return response
Ejemplo n.º 28
0
def handle_message(message):
    response = "not activated"
    parsed_text = parse_text(str(message.body))
    command = parsed_text[0].lower()
    # only activate if it's not an opt-out command
    if command != "opt-out":
        activate(message.author)

    # normal commands
    if command in ["help", "!help"]:
        LOGGER.info("Helping")
        subject = "Nano Tipper - Help"
        response = handle_help(message)
    elif command in ["balance", "address"]:
        LOGGER.info("balance")
        subject = "Nano Tipper - Account Balance"
        response = handle_balance(message)
    elif command == "minimum":
        LOGGER.info("Setting Minimum")
        subject = "Nano Tipper - Tip Minimum"
        response = handle_minimum(message)
    elif command in ["percentage", "percent"]:
        LOGGER.info("Setting Percentage")
        subject = "Nano Tipper - Returned Tip Percentage for Donation"
        response = handle_percentage(message)
    elif command in ["create", "register"]:
        LOGGER.info("Creating")
        subject = "Nano Tipper - Create"
        response = handle_create(message)
    elif command in ["send", "withdraw"]:
        subject = "Nano Tipper - Send"
        LOGGER.info("send via PM")
        response = handle_send(message)
        response = text.make_response_text(message, response)
    elif command == "history":
        LOGGER.info("history")
        subject = "Nano Tipper - History"
        response = handle_history(message)
    elif command == "silence":
        LOGGER.info("silencing")
        subject = "Nano Tipper - Silence"
        response = handle_silence(message)
    elif command == "subreddit":
        LOGGER.info("subredditing")
        subject = "Nano Tipper - Subreddit"
        response = handle_subreddit(message)
    elif command == "opt-out":
        LOGGER.info("opting out")
        response = handle_opt_out(message)
        subject = "Nano Tipper - Opt Out"
    elif command == "opt-in":
        LOGGER.info("opting in")
        subject = "Nano Tipper - Opt In"
        response = handle_opt_in(message)

    # nanocenter donation commands
    elif command in ("project", "projects"):
        if (str(message.author).lower()
                in DONATION_ADMINS + TIPBOT_OWNER) and len(parsed_text) > 2:
            sql = "INSERT INTO projects (project, address) VALUES(%s, %s) ON DUPLICATE KEY UPDATE address=%s"
            val = (parsed_text[1], parsed_text[2], parsed_text[2])
            MYCURSOR.execute(sql, val)
            MYDB.commit()
        add_history_record(
            username=str(message.author),
            action="project",
            comment_text=str(message.body)[:255],
            comment_or_message="message",
            comment_id=message.name,
        )

        response = "Current NanoCenter Donation Projects: \n\n"
        subject = "Nanocenter Projects"
        sql = "SELECT project, address FROM projects"
        MYCURSOR.execute(sql)
        results = MYCURSOR.fetchall()
        for result in results:
            response += "%s %s  \n" % (result[0], result[1])
    elif command == "delete_project":
        if ((str(message.author) == TIPBOT_OWNER) or
            (str(message.author).lower()
             == "rockmsockmjesus")) and len(parsed_text) > 1:
            sql = "DELETE FROM projects WHERE project=%s"
            val = (parsed_text[1], )
            MYCURSOR.execute(sql, val)
            MYDB.commit()
        response = "Current NanoCenter Donation Projects: \n\n"
        subject = "Nanocenter Projects"
        sql = "SELECT project, address FROM projects"
        MYCURSOR.execute(sql)
        results = MYCURSOR.fetchall()
        for result in results:
            response += "%s %s  \n" % (result[0], result[1])
    # a few administrative tasks
    elif command in ["restart", "stop", "disable", "deactivate"]:
        if str(message.author).lower() in [
                TIPBOT_OWNER,
                "rockmsockmjesus",
        ]:  # "joohansson"]:
            add_history_record(
                username=str(message.author),
                action="restart",
                comment_text=str(message.body)[:255],
                comment_or_message="message",
                comment_id=message.name,
            )
            sys.exit()
    elif command == "test_welcome_tipped":
        subject = "Nano Tipper - Welcome By Tip"
        response = WELCOME_TIP % (
            0.01,
            "xrb_3jy9954gncxbhuieujc3pg5t1h36e7tyqfapw1y6zukn9y1g6dj5xr7r6pij",
            "xrb_3jy9954gncxbhuieujc3pg5t1h36e7tyqfapw1y6zukn9y1g6dj5xr7r6pij",
        )
    elif command == "test_welcome_create":
        subject = "Nano Tipper - Create"
        response = WELCOME_CREATE % (
            "xrb_3jy9954gncxbhuieujc3pg5t1h36e7tyqfapw1y6zukn9y1g6dj5xr7r6pij",
            "xrb_3jy9954gncxbhuieujc3pg5t1h36e7tyqfapw1y6zukn9y1g6dj5xr7r6pij",
        )

    else:
        add_history_record(
            username=str(message.author),
            comment_text=str(message.body)[:255],
            comment_or_message="message",
            comment_id=message.name,
        )
        return None
    message_recipient = str(message.author)
    message_text = response + COMMENT_FOOTER
    send_pm(message_recipient, subject, message_text, bypass_opt_out=True)
Ejemplo n.º 29
0
def handle_history(message):
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    username = str(message.author)
    parsed_text = parse_text(str(message.body))
    num_records = 10
    # if there are more than 2 words, one of the words is a number for the number of records
    if len(parsed_text) >= 2:
        if parsed_text[1].lower() == "nan" or ("inf"
                                               in parsed_text[1].lower()):
            response = (
                "'%s' didn't look like a number to me. If it is blank, "
                "there might be extra spaces in the command.")
            return response
        try:
            num_records = int(parsed_text[1])
        except:
            response = (
                "'%s' didn't look like a number to me. If it is blank, "
                "there might be extra spaces in the command.")
            return response

    # check that it's greater than 50
    if num_records > 50:
        num_records = 50

    # check if the user is in the database
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        # open_or_receive(result[0][0], result[0][1])
        # balance = check_balance(result[0][0])
        add_history_record(
            username=username,
            action="history",
            amount=num_records,
            address=result[0][0],
            comment_or_message="message",
            comment_id=message.name,
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            comment_text=str(message.body)[:255],
        )
        response = "Here are your last %s historical records:\n\n" % num_records
        sql = (
            "SELECT reddit_time, action, amount, comment_id, notes, recipient_"
            "username, recipient_address FROM history WHERE username=%s ORDER BY "
            "id DESC limit %s")
        val = (username, num_records)
        MYCURSOR.execute(sql, val)
        results = MYCURSOR.fetchall()
        for result in results:
            try:
                amount = result[2]
                if (result[1] == "send") and amount:
                    amount = int(result[2]) / 10**30
                    if (result[4] == "sent to registered redditor"
                            or result[4] == "new user created"):
                        response += (
                            "%s: %s | %s Nano to %s | reddit object: %s | %s\n\n"
                            % (
                                result[0],
                                result[1],
                                amount,
                                result[5],
                                result[3],
                                result[4],
                            ))
                    elif (result[4] == "sent to registered address"
                          or result[4] == "sent to unregistered address"):
                        response += (
                            "%s: %s | %s Nano to %s | reddit object: %s | %s\n\n"
                            % (
                                result[0],
                                result[1],
                                amount,
                                result[6],
                                result[3],
                                result[4],
                            ))
                elif result[1] == "send":
                    response += "%s: %s | reddit object: %s | %s\n\n" % (
                        result[0],
                        result[1],
                        result[3],
                        result[4],
                    )
                elif (result[1] == "minimum") and amount:
                    amount = int(result[2]) / 10**30
                    response += "%s: %s | %s | %s | %s\n\n" % (
                        result[0],
                        result[1],
                        amount,
                        result[3],
                        result[4],
                    )
                else:
                    response += "%s: %s | %s | %s | %s\n\n" % (
                        result[0],
                        result[1],
                        amount,
                        result[3],
                        result[4],
                    )
            except:
                response += (
                    "Unparsed Record: Nothing is wrong, I just didn't "
                    "parse this record properly.\n\n")

        return response
    else:
        add_history_record(
            username=username,
            action="history",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            amount=num_records,
            comment_id=message.name,
            comment_text=str(message.body)[:255],
        )
        response = (
            "You do not currently have an account open. To create one, "
            "respond with the text 'create' in the message body.")
        return response
Ejemplo n.º 30
0
def handle_percentage(message):
    message_time = datetime.utcfromtimestamp(
        message.created_utc)  # time the reddit message was created
    # user may select a minimum tip amount to avoid spamming. Tipbot minimum is 0.001
    username = str(message.author)
    # find any accounts associated with the redditor
    parsed_text = parse_text(str(message.body))

    # there should be at least 2 words, a minimum and an amount.
    if len(parsed_text) < 2:
        response = "I couldn't parse your command. I was expecting 'percentage <amount>'. Be sure to check your spacing."
        return response
    # check that the minimum is a number

    if parsed_text[1].lower() == "nan" or ("inf" in parsed_text[1].lower()):
        response = "'%s' didn't look like a number to me. If it is blank, there might be extra spaces in the command."
        return response
    try:
        amount = float(parsed_text[1])
    except:
        response = "'%s' didn't look like a number to me. If it is blank, there might be extra spaces in the command."
        return response

    # check that it's greater than 0.01
    if round(amount, 2) < 0:
        response = "Did not update. Your percentage cannot be negative."
        return response

    if round(amount, 2) > 100:
        response = "Did not update. Your percentage must be 100 or lower."
        return response

    # check if the user is in the database
    sql = "SELECT address FROM accounts WHERE username=%s"
    val = (username, )
    MYCURSOR.execute(sql, val)
    result = MYCURSOR.fetchall()
    if len(result) > 0:
        # open_or_receive(result[0][0], result[0][1])
        # balance = check_balance(result[0][0])
        add_history_record(
            username=username,
            action="percentage",
            amount=round(amount, 2),
            address=result[0][0],
            comment_or_message="message",
            comment_id=message.name,
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            comment_text=str(message.body)[:255],
        )
        sql = "UPDATE accounts SET percentage = %s WHERE username = %s"
        val = (round(amount, 2), username)
        MYCURSOR.execute(sql, val)
        MYDB.commit()
        response = "Updating donation percentage to %s" % round(amount, 2)
        return response
    else:
        add_history_record(
            username=username,
            action="percentage",
            reddit_time=message_time.strftime("%Y-%m-%d %H:%M:%S"),
            amount=round(amount, 2),
            comment_id=message.name,
            comment_text=str(message.body)[:255],
        )
        response = (
            "You do not currently have an account open. To create one, "
            "respond with the text 'create' in the message body.")
        return response