Check out my AI!

Please visit AndrewBot. If you want to support me, reply to this and I’ll post a stripe link.
You’ll need an access code, it’ll expire soon, but currently it is 313264.

4 Likes

Sorry it doesn’t work right now. I am fixing it

ok guys, it works fully now :wink:
Also put recommendations in the comments please

doesn’t seem to

bruh, alright ill check it.
It seems to work on my side though
image

It doesn’t work on my computer either

Alright, maybe I should delete this post. Can you copy the error and paste it here, then I’ll delete this topic

Why? If you’re going to try to fix it then I see no reason to delete the topic.

cuz I suck at html/javascript/css and I’m trying to figure it out.

Try it again I used replit AI to help me it should be better now

This is kind of complicated. Try using this link AndrewBot Dev Link

image
for me it can even generate images
image

1 Like

yeah the dev link works, but the images do not.

anyone wanna join the repl to help me?

ill help with it if u add me to it

I just realized that python flask does not go well with html, which is why its been giving you guys errors. Srry!!! Code:
Python:

import math
import os
import openai
import requests
import tiktoken
from flask import Flask, request, render_template, jsonify, send_from_directory, redirect
app = Flask(__name__, static_url_path='', static_folder='.')

@app.route('/')
def home():
  return send_from_directory(app.static_folder, 'index.html')
def add_files_to_folder(folder_name, files):
  if not os.path.exists(folder_name):
      os.makedirs(folder_name)
  for file in files:
      new_file_path = os.path.join(folder_name, file)
      with open(file, "r") as f:
          content = f.read()
      with open(new_file_path, "w") as f:
          f.write(content)
def num_tokens_from_string(string: str, encoding_name: str) -> int:
  encoding = tiktoken.get_encoding(encoding_name)
  num_tokens = len(encoding.encode(string))
  return num_tokens
tokensUsed = 0
openai.api_key = os.environ['API_KEY']
messages = [
  {"role": "system", "content": """You are a helpful chatbot named AndrewBot.
  You are to use varied responses, with 8th-grade level English.
  Avoid being too repetitive, and you use different tone/mood when writing.
  Do not plagerize, and try to use different nouns, verbs, and adjectives when writing responses.
  Your model is gpt-4-turbo. AndrewBot has the ability to make AI-image generated pictures with dall-e-3.
  You were created on Oct. 17 2023
  You are built on Replit. Replit is a platform that has almost every coding language. Replit is powered by a community of coders.
  Your creator is known by AndrewDeng3. AndrewDeng3 is a 13 year old male python coder, who also knows a little bit of p5js and Lua.
  He mainly makes text-games and experiments with AI, that don't have high quality but are still entertaining.
  AndrewDeng3\'s top games are Just Any Normal Combat Game and Fly to Space 2, which are both created in python. They are text games. The goal of Just Any Normal Combat Game is to defeat enemies and gain better and unique weapons. Fly to Space 2 is about collecting biofuel to level up your rocket ship to gain higher altitudes.
  AndrewDeng3 also likes to swim. His best stroke is Freestyle.
  His times (Yards):
  50 Freestyle - 0:27
  500 Freestyle - 5:26
  200 Freestyle - 2:05
  100 Freestyle - 0:58
  200 Butterfly - 2:24
  His times(Meters):
  400 Freestyle - 4:56
  100 Freestyle - 1:07
  50 Freestyle - 0:31
  Whenever you generate an AI Chatbot, unless otherwise stated, it has to include the OpenAI import
  If you believe that the user wants an image generated, add a [image] {prompt} in the text, with brackets on. Leave a [prompt + prompt_number]. 
  Do not use spaces within the prompt curly brackets and use hyphens instead. You can at most have 1 image within your text.
  Do not add numbers after the prompt, and if you do, you have to add hyphens
  Do not include any text if you are generating an image, as the text will be erased"""},
]

# ... [existing code] ...

ACCESS_CODE = '313264'  # Replace this with your chosen access code

@app.route('/enter-code')
def enter_code():
  return send_from_directory(app.static_folder, 'access.html')

# ...
done = False
@app.route('/validate-access', methods=['POST'])
def validate_access():
        global done
        entered_code = request.form.get('accessCode')
        if entered_code == ACCESS_CODE:
            done = True
            return jsonify({"status": "success", "message": "Access granted"}), 200
        else:
            return jsonify({"status": "error", "message": "Access code is incorrect. Please try again."}), 401

# ...
 # Or

def clear_use_directory():
  use_dir = os.path.join(app.static_folder, 'use')
  for filename in os.listdir(use_dir):
      file_path = os.path.join(use_dir, filename)
      if os.path.isfile(file_path) or os.path.islink(file_path):
          os.unlink(file_path)
clear_use_directory()
def imager(prompt):
          clear_use_directory()
          use_dir = os.path.join(app.static_folder, 'use')
          if '[image]' in prompt:
              prompt_parts = prompt.split()  # Split the prompt into parts
              while '[image]' in prompt_parts:
                  y = prompt_parts.index('[image]')
                  prompt_parts.pop(y)
                  image_prompt = prompt_parts.pop(y).replace('{', '').replace('}', '').replace('-', ' ')
                  response = openai.Image.create(
                    prompt=image_prompt,
                    n=1,
                    size="1024x1024",
                    model='dall-e-3'
                  )
                  image_filename = f"image_{image_prompt}.png"  # Use a generic name format
                  local_file_path = os.path.join(use_dir, image_filename)  # Local path for saving
                  web_file_path = f"/use/{image_filename}"  # Web path for client access
                  with open(local_file_path, "wb") as f:
                    image_data = requests.get(response["data"][0]['url'])
                    f.write(image_data.content)
                  prompt_parts.insert(y, web_file_path)  # Insert the web-accessible path
              return ' '.join(prompt_parts)
          else:
              return prompt

@app.route('/images-list')
def images_list():
    image_files = []
    directory = os.path.join(app.static_folder, 'use')
    for filename in os.listdir(directory):
        if filename.endswith('.png'):
            image_files.append(filename)
    return jsonify(image_files)

@app.route('/access')
def access():
  return send_from_directory(app.static_folder, 'access.html')
@app.route('/index')
def index():
  return send_from_directory(app.static_folder, 'index.html')

mm = ''
count = 0
@app.route('/ask', methods=['POST'])
def ask():
    global mm, messages, message, tokensUsed, username, done
    print(done)
    if done is False:
      return jsonify({"redirect": "/access"})
    message = request.form['message']
    reply = ""
    if message == '/regen':
        message = mm
    mm = message
    if message and not message.startswith('/'):
        messages.append({"role": "user", "content": message})
        chat = openai.ChatCompletion.create(
            model="gpt-4", messages=messages, temperature=0.5
        )
        reply = chat.choices[0].message.content
        reply = imager(reply)
    if message == '/tokens':
        reply = f"Number of tokens used: {tokensUsed} (${math.floor(tokensUsed / 2000 * 2) / 100})"
    if reply:
        tokensUsed += num_tokens_from_string(reply, "cl100k_base")
        tokensUsed += num_tokens_from_string(message, "cl100k_base")
        reply = f"AndrewBot: {reply.replace('AndrewBot: ', '')}"
        messages.append({"role": "assistant", "content": reply})

    return jsonify({"reply": reply})

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))  # Use Replit suggested port

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>AndrewBot</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <style>
      body {
        font-family: 'Roboto', sans-serif;
        background: linear-gradient(to bottom right, #1CDA06, #009AD5); /* Tech-inspired linear gradient */
        color: #fff;
        margin: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }

      #chat-container {
        background-color: #333;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        width: 100%;
        max-width: 400px;
        padding: 20px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        height: 500px;
        overflow: hidden;
      }

      #messages {
        height: calc(100% - 60px); /* Adjust height to include input field and button */
        overflow-y: auto;
        padding: 10px;
        background: #1a1a1a;
        border-radius: 8px;
      }

      .message {
        color: #f0f0f0;
        padding: 10px;
        border-radius: 16px;
        display: block;
        max-width: 80%;
        word-wrap: break-word; /* Ensure long words do not extend a message */
        margin-bottom: 10px;
        overflow: hidden; /* Hide the overflow */
        text-overflow: ellipsis; /* Show ellipsis for long texts */
      }

      .bot-reply {
        background: #1CDA06;
        align-self: flex-start;
      }

      .user-message {
        background: #009AD5;
        align-self: flex-end;
      }

      form {
        display: flex;
        margin-top: 10px;
      }

      input[type=text] {
        flex: 1;
        padding: 10px;
        margin-right: 8px;
        border: none;
        border-radius: 16px;
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
        color: #333;
      }

      button {
        padding: 10px 20px;
        border: none;
        border-radius: 16px;
        background-color: #005FB7;
        color: white;
        cursor: pointer;
        transition: background-color 0.3s;
      }

      button:hover {
        background-color: #009AD5;
      }

      button:active {
        transform: scale(0.98);
      }
      .chat-image {
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        margin-top: 10px;
      }

    </style>
  <script>
    // Helper function to create a new element and set attributes
    const createElementWithAttributes = (tag, attributes) => {
      const element = document.createElement(tag);
      for (const key in attributes) {
        element.setAttribute(key, attributes[key]);
      }
      return element;
    };
    // Check if the message is an image URL
    const isImageUrl = (message) => {
      return /\/use\/.*\.(?:jpg|gif|png)/gi.test(message);
    };
    // Function to process and display the received message
    // Function to process and display the received message
    // Function to process and display the received message
    const displayMessage = (message, isBot) => {
      const messagesContainer = document.getElementById('messages');
      const messageClass = isBot ? 'message bot-reply' : 'message user-message';
      // Create a div element for the message
      const messageEl = createElementWithAttributes('div', { class: messageClass });
      if (isBot && isImageUrl(message)) {
        // Get the relative URL from the message
        const imageUrl = message.match(/\/use\/.*\.(?:jpg|gif|png)/gi)[0];
        // Create an img element for displaying the image
        const imgEl = createElementWithAttributes('img', { src: imageUrl, class: 'chat-image' });
        messageEl.appendChild(imgEl);
      } else {
        // Text message
        messageEl.innerText = message;
      }
      // Append the message to the messages container and scroll into view
      messagesContainer.appendChild(messageEl);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    };
    
    // Update sendMessage function
    async function sendMessage(event) {
      event.preventDefault();
      const messageInput = document.getElementById('message');
      const messageText = messageInput.value.trim();
      const formData = new FormData();
      formData.append('message', messageText);

      // Append user message
      displayMessage(`You: ${messageText}`, false);
      messageInput.value = '';

      try {
        const response = await fetch('/ask', {
          method: 'POST',
          body: formData
        });

        if (response.ok) {
          const data = await response.json();
          if (data.redirect) {
            window.location.href = data.redirect;
          } else {
            // Append bot reply
            displayMessage(data.reply, true);
          }
        } else {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
      } catch (error) {
        console.error('There was a problem with the fetch operation:', error);
      }
    }

    document.addEventListener('DOMContentLoaded', function() {
      const chatForm = document.getElementById('chat-form');
      chatForm.addEventListener('submit', sendMessage);
    });
  </script>
</head>
<body>
    <div id="chat-container">
      <h1>AndrewBot Chat</h1>
      <div id="messages"></div>
      <form id="chat-form">
          <input type="text" name="message" id="message" placeholder="Say something..." required>
          <button type="submit">Send</button>
      </form>
    </div>
</body>
</html>

And Access:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Access Code Required</title>
  <style>
    body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        background-color: #f0f0f0;
        font-family: Arial, sans-serif;
    }
    #accessForm {
        padding: 20px;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        background-color: #ffffff;
        text-align: center;
    }
    #accessCode {
        margin-top: 10px;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ddd;
        width: calc(100% - 22px); /* Input width minus padding and border */
    }
    button {
        margin-top: 10px;
        padding: 10px 15px;
        border-radius: 5px;
        border: none;
        background-color: #005FB7;
        color: #ffffff;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
    button:hover {
        background-color: #009AD5;
    }
  </style>
</head>
<body>
  <form id="accessForm" action="/validate-access" method="POST">
    <label for="accessCode">Enter Access Code:</label><br>
    <input type="text" id="accessCode" name="accessCode" required>
    <button type="submit">Submit</button>
  </form>
  <!-- This is where the IDE will be embedded -->
  <div id="ideContainer" style="display: none;"></div>

  <script>
    document.getElementById('accessForm').onsubmit = async function(e) {
      e.preventDefault();
      const formData = new FormData(e.target); // Using FormData to capture form data
      const response = await fetch('/validate-access', {
        method: 'POST',
        body: formData // Passing formData directly
      });
      const data = await response.json();

      if (data.status === 'success') {
        // Directly relocate to the home page, since access is granted.
        window.location.href = '/';
      } else {
        // Show an alert box if the access code is incorrect or any other error occurs.
        alert(data.message);
      }
    }
  </script>

</body>
</html>
1 Like

What do you mean? Flask is a powerful backend that gives you usability with HTML.

either that or its replit
cuz it kept on trying to redirect to /ask when it was a function in the flask main

Did you do a preventDefault call?

nope, i can invite you though, what’s your replit username

Usernames here are (for the most part) the same as on Replit.

(Only exceptions are for people with hyphens [-] in their usernames and @9pfs1)

3 Likes

Not working… still

But the UI is impressive, nice job there

1 Like