├── .gitignore ├── LICENSE ├── README.md ├── coreOpenai ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py ├── openapp ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_alter_chatgptbot_options_chatgptbot_created_at.py │ └── __init__.py ├── models.py ├── telgrambot.py ├── tests.py ├── urls.py └── views.py ├── requirements.txt ├── static └── css │ ├── bootstrap.min.css │ └── sign-in.css └── templates ├── base.html ├── index.html ├── login.html └── users └── register.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Django # 2 | *.log 3 | *.pot 4 | *.pyc 5 | __pycache__ 6 | db.sqlite3 7 | 8 | # Environments 9 | .env 10 | .venv 11 | env/ 12 | venv/ 13 | ENV/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # openai-API 2 | Django application that integrates with the OpenAI API to generate natural language responses to user inputs. The application is designed to work with both Telegram and web browsers, allowing users to interact with it in whichever way is most convenient for them. 3 | 4 | ![telegram-cloud-document-2-5436324961939630234](https://user-images.githubusercontent.com/109435929/219484501-5df534fe-9af5-49d1-b30f-e241853a68ad.jpg) 5 | 6 | 7 | 8 | The application comes with Login, Logout, and Sign up pages, which allow users to create accounts and access the full functionality of the app. Additionally, users have the option to remove their conversation with one click, ensuring that their privacy is protected. 9 | 10 | 11 | ![telegram-cloud-document-2-5436324961939630241](https://user-images.githubusercontent.com/109435929/219484314-820627b2-09d7-4545-837c-1f03119434f1.jpg) 12 | 13 | #Error Handling with Nice ui message using django messages framework 14 | 15 | image 16 | 17 | 18 | #LOGIN : Error Handling 19 | image 20 | 21 | 22 | Once a user inputs a message via Telegram or the web interface, the Django application uses the OpenAI API to generate a response, which is then sent back to the user via the same channel. The application's integration with the OpenAI API allows for a wide range of possible use cases, from customer service chatbots to intelligent assistants for websites and apps. 23 | 24 | ![telegram-cloud-document-2-5436324961939630239](https://user-images.githubusercontent.com/109435929/219484568-22823544-93e8-49a6-b424-fe89992e4dbc.jpg) 25 | 26 | #a better ui in messages page: 27 | image 28 | 29 | 30 | 31 | 32 | The code is written in Python, using the Django web framework and the OpenAI API for natural language processing. The repository includes all the necessary files to run the application, as well as documentation on how to set it up and use it. 33 | 34 | If you're interested in exploring the possibilities of natural language generation with Django and the OpenAI API, this repository is a great starting point. Feel free to clone the repo and start experimenting! 35 | 36 | Prerequisites: 37 | 38 | Python >=3.10 39 | 40 | 41 | Git 42 | 43 | 44 | OpenAI API key 45 | 46 | 47 | Telegram bot token (if using Telegram integration) 48 | 49 | Clone the repository 50 | Create Venv and Install dependencies by running : pip install -r requirements.txt 51 | Run the migrations: 52 | python manage.py makemigrations 53 | python manage.py migrate 54 | 55 | -------------------------------------------------------------------------------- /coreOpenai/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kouidersif/openai-API/537b24e4012708e777dc7557f604c81f0f60b83d/coreOpenai/__init__.py -------------------------------------------------------------------------------- /coreOpenai/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for coreOpenai project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coreOpenai.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /coreOpenai/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for coreOpenai project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.1.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.1/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | import os 15 | 16 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 17 | BASE_DIR = Path(__file__).resolve().parent.parent 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = 'django-insecure-ki&$9fzkqtqk74s#(01j2ix=5yze&(sx0zw8&v^%=_@rtq%#12' 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = True 28 | 29 | ALLOWED_HOSTS = [] 30 | 31 | 32 | # Application definition 33 | 34 | INSTALLED_APPS = [ 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | 'openapp', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'coreOpenai.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [BASE_DIR, 'templates'], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'coreOpenai.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/4.1/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/4.1/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/4.1/howto/static-files/ 119 | 120 | STATIC_URL = 'static/' 121 | 122 | STATICFILES_DIRS = [ 123 | os.path.join(BASE_DIR, "static/") 124 | ] 125 | 126 | # #static root 127 | # STATIC_ROOT = os.path.join(BASE_DIR, 'static/') 128 | 129 | # Default primary key field type 130 | # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field 131 | 132 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 133 | 134 | LOGIN_REDIRECT_URL = 'main' 135 | -------------------------------------------------------------------------------- /coreOpenai/urls.py: -------------------------------------------------------------------------------- 1 | """coreOpenai URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/4.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from django.conf import settings 19 | from django.conf.urls.static import static 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path("", include("openapp.urls")), 24 | ] 25 | 26 | 27 | urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -------------------------------------------------------------------------------- /coreOpenai/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for coreOpenai project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coreOpenai.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'coreOpenai.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /openapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kouidersif/openai-API/537b24e4012708e777dc7557f604c81f0f60b83d/openapp/__init__.py -------------------------------------------------------------------------------- /openapp/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import ChatGptBot 3 | # Register your models here. 4 | 5 | 6 | 7 | admin.site.register(ChatGptBot) -------------------------------------------------------------------------------- /openapp/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class OpenappConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'openapp' 7 | -------------------------------------------------------------------------------- /openapp/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.contrib.auth.forms import UserCreationForm, AuthenticationForm 3 | from django.contrib.auth.models import User 4 | 5 | class SignUpForm(UserCreationForm): 6 | class Meta: 7 | model = User 8 | fields= ['username','password1', 'password2'] 9 | exclude = ['email'] 10 | def __init__(self, *args, **kwargs): 11 | super(SignUpForm, self).__init__(*args, **kwargs) 12 | self.fields['username'].widget.attrs['class'] = 'form-control' 13 | self.fields['password1'].widget.attrs['class'] = 'form-control' 14 | self.fields['password2'].widget.attrs['class'] = 'form-control' 15 | 16 | 17 | 18 | 19 | 20 | class UserLoginForm(AuthenticationForm): 21 | class Meta: 22 | model = User 23 | fields= ['username', 'password'] 24 | def __init__(self, *args, **kwargs): 25 | super(UserLoginForm, self).__init__(*args, **kwargs) 26 | self.fields['username'].widget.attrs['class'] = 'form-control' 27 | self.fields['username'].widget.attrs['placeholder'] = 'Username' 28 | self.fields['password'].widget.attrs['class'] = 'form-control' 29 | self.fields['password'].widget.attrs['placeholder'] = 'Password' 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /openapp/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 4.1.6 on 2023-12-23 13:25 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='ChatGptBot', 19 | fields=[ 20 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('messageInput', models.TextField()), 22 | ('bot_response', models.TextField()), 23 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 24 | ], 25 | ), 26 | ] 27 | -------------------------------------------------------------------------------- /openapp/migrations/0002_alter_chatgptbot_options_chatgptbot_created_at.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 5.0.8 on 2024-08-31 20:56 2 | 3 | import django.utils.timezone 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('openapp', '0001_initial'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AlterModelOptions( 15 | name='chatgptbot', 16 | options={'ordering': ['-created_at'], 'verbose_name': 'Messages History', 'verbose_name_plural': 'Messages History'}, 17 | ), 18 | migrations.AddField( 19 | model_name='chatgptbot', 20 | name='created_at', 21 | field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), 22 | preserve_default=False, 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /openapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kouidersif/openai-API/537b24e4012708e777dc7557f604c81f0f60b83d/openapp/migrations/__init__.py -------------------------------------------------------------------------------- /openapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth import get_user_model 3 | # Create your models here. 4 | User = get_user_model() 5 | 6 | class ChatGptBot(models.Model): 7 | user = models.ForeignKey(User, on_delete=models.CASCADE) 8 | messageInput = models.TextField() 9 | bot_response = models.TextField() 10 | created_at = models.DateTimeField(auto_now_add=True) 11 | def __str__(self): 12 | return self.user.username 13 | 14 | class Meta: 15 | verbose_name = 'Messages History' 16 | verbose_name_plural = 'Messages History' 17 | ordering = ['created_at'] 18 | -------------------------------------------------------------------------------- /openapp/telgrambot.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from telegram import Update 3 | from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters 4 | import openai 5 | import os 6 | from dotenv import load_dotenv 7 | load_dotenv() 8 | openai.api_key = os.getenv("OPENAI_API_KEY") 9 | telegram_token = os.getenv("TELEGRAM_TOKEN") 10 | 11 | 12 | 13 | logging.basicConfig( 14 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 15 | level=logging.INFO 16 | ) 17 | 18 | 19 | #first command to start conversation 20 | async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): 21 | await context.bot.send_message(chat_id=update.effective_chat.id, text="Hi, i'm ready to assist you, please ask anything you want!") 22 | 23 | 24 | 25 | async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE): 26 | message = update.message.text 27 | response = openai.Completion.create( 28 | model="text-davinci-003", 29 | prompt=message, 30 | temperature=0, 31 | max_tokens=100, 32 | top_p=1, 33 | frequency_penalty=0.5, 34 | presence_penalty=0, 35 | 36 | ) 37 | await context.bot.send_message(chat_id=update.effective_chat.id, text=response['choices'][0]['text']) 38 | 39 | 40 | if __name__ == '__main__': 41 | 42 | application = ApplicationBuilder().token(telegram_token).build() 43 | 44 | echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo) 45 | start_handler = CommandHandler('start', start) 46 | application.add_handler(start_handler) 47 | application.add_handler(echo_handler) 48 | 49 | application.run_polling() -------------------------------------------------------------------------------- /openapp/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /openapp/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from openapp import views 3 | 4 | 5 | urlpatterns=[ 6 | path("", views.HomeView.as_view(), name='main'), 7 | path("sign-up/", views.SignUp.as_view(), name='signup'), 8 | path("delete/", views.DeleteHistory, name='deleteChat'), 9 | path("logout/", views.logout_view, name="logout"), 10 | path("login/", views.LoginView.as_view(), name="login"), 11 | ] -------------------------------------------------------------------------------- /openapp/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from django.urls import reverse 3 | from django.http import HttpResponse 4 | # Create your views here. 5 | from dotenv import load_dotenv 6 | import os 7 | from openai import OpenAI 8 | import openai 9 | from .models import ChatGptBot 10 | load_dotenv() 11 | from django.contrib.auth import authenticate, login 12 | from django.views.generic import CreateView, DeleteView, FormView, ListView 13 | from django.contrib.auth.mixins import LoginRequiredMixin 14 | from .forms import SignUpForm, UserLoginForm 15 | from django.urls import reverse_lazy 16 | from django.contrib.auth.decorators import login_required 17 | from django.contrib.auth import logout 18 | from django.contrib import messages 19 | 20 | 21 | 22 | 23 | client = OpenAI( 24 | # This is the default and can be omitted 25 | api_key=os.getenv("OPENAI_API_KEY"), 26 | ) 27 | 28 | 29 | 30 | 31 | class HomeView(LoginRequiredMixin, ListView): 32 | model = ChatGptBot 33 | template_name = 'index.html' 34 | context_object_name = 'get_history' 35 | 36 | def get_queryset(self): 37 | return ChatGptBot.objects.filter(user=self.request.user) 38 | 39 | def post(self, request, *args, **kwargs): 40 | user_input = request.POST.get('userInput') 41 | clean_user_input = str(user_input).strip() 42 | try: 43 | response = client.chat.completions.create( 44 | model="gpt-3.5-turbo", 45 | messages=[ 46 | { 47 | "role": "user", 48 | "content": clean_user_input, 49 | } 50 | ], 51 | ) 52 | bot_response = response.choices[0].message.content 53 | obj, created = ChatGptBot.objects.get_or_create( 54 | user=request.user, 55 | messageInput=clean_user_input, 56 | bot_response=bot_response, 57 | ) 58 | except openai.APIConnectionError as e: 59 | messages.warning(request, f"Failed to connect to OpenAI API, check your internet connection") 60 | except openai.RateLimitError as e: 61 | messages.warning(request, f"You exceeded your current quota, please check your plan and billing details.") 62 | messages.warning(request, f"If you are a developper change the API Key") 63 | 64 | return redirect(request.META['HTTP_REFERER']) 65 | 66 | 67 | 68 | class SignUp(CreateView): 69 | form_class = SignUpForm 70 | template_name = "users/register.html" 71 | def form_valid(self, form): 72 | response = super().form_valid(form) 73 | # Get the user's username and password in order to automatically authenticate user after registration 74 | username = form.cleaned_data['username'] 75 | password = form.cleaned_data['password1'] 76 | # Authenticate the user and log him/her in 77 | user = authenticate(username=username, password=password) 78 | login(self.request, user) 79 | return response 80 | def form_invalid(self, form): 81 | for field, errors in form.errors.items(): 82 | for error in errors: 83 | messages.warning(self.request, f"{field}: {error}") 84 | return redirect(self.request.META['HTTP_REFERER']) 85 | def get_success_url(self): 86 | return reverse("main") 87 | 88 | 89 | 90 | class LoginView(FormView): 91 | form_class = UserLoginForm 92 | template_name = "login.html" 93 | def form_valid(self, form): 94 | response = super().form_valid(form) 95 | # Get the user's username and password and authenticate 96 | username = form.cleaned_data['username'] 97 | password = form.cleaned_data['password'] 98 | # Authenticate the user and log him/her in 99 | user = authenticate(username=username, password=password) 100 | login(self.request, user) 101 | messages.success(self.request, "You are logged in") 102 | return response 103 | def form_invalid(self, form): 104 | for field, errors in form.errors.items(): 105 | for error in errors: 106 | messages.warning(self.request, f"{error}") 107 | return redirect(self.request.META['HTTP_REFERER']) 108 | def get_success_url(self): 109 | return reverse("main") 110 | 111 | 112 | 113 | @login_required 114 | def DeleteHistory(request): 115 | chatGptobjs = ChatGptBot.objects.filter(user = request.user) 116 | chatGptobjs.delete() 117 | messages.success(request, "All messages have been deleted") 118 | return redirect(request.META['HTTP_REFERER']) 119 | 120 | 121 | def logout_view(request): 122 | logout(request) 123 | messages.success(request, "Succesfully logged out") 124 | return redirect("main") -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohappyeyeballs==2.4.0 2 | aiohttp==3.10.2 3 | aiosignal==1.3.1 4 | annotated-types==0.6.0 5 | anyio==3.6.2 6 | asgiref==3.7.2 7 | async-timeout==4.0.2 8 | attrs==22.2.0 9 | certifi==2024.7.4 10 | charset-normalizer==3.0.1 11 | distro==1.8.0 12 | Django==5.0.8 13 | frozenlist==1.3.3 14 | h11==0.14.0 15 | h2==4.1.0 16 | hpack==4.0.0 17 | httpcore==0.16.3 18 | httpx==0.23.3 19 | hyperframe==6.0.1 20 | idna==3.7 21 | multidict==6.0.4 22 | openai==1.6.1 23 | pydantic==2.5.3 24 | pydantic_core==2.14.6 25 | python-dotenv==0.21.1 26 | python-telegram-bot==20.1 27 | requests==2.32.3 28 | rfc3986==1.5.0 29 | sniffio==1.3.0 30 | sqlparse==0.5.0 31 | tqdm==4.66.3 32 | typing_extensions==4.9.0 33 | urllib3==1.26.19 34 | yarl==1.8.2 35 | -------------------------------------------------------------------------------- /static/css/sign-in.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | height: 100%; 4 | } 5 | 6 | body { 7 | display: flex; 8 | align-items: center; 9 | padding-top: 40px; 10 | padding-bottom: 40px; 11 | background-color: #f5f5f5; 12 | } 13 | 14 | .form-signin { 15 | max-width: 330px; 16 | padding: 15px; 17 | } 18 | 19 | .form-signin .form-floating:focus-within { 20 | z-index: 2; 21 | } 22 | 23 | .form-signin input[type="email"] { 24 | margin-bottom: -1px; 25 | border-bottom-right-radius: 0; 26 | border-bottom-left-radius: 0; 27 | } 28 | 29 | 30 | 31 | .bd-placeholder-img { 32 | font-size: 1.125rem; 33 | text-anchor: middle; 34 | -webkit-user-select: none; 35 | -moz-user-select: none; 36 | user-select: none; 37 | } 38 | 39 | @media (min-width: 768px) { 40 | .bd-placeholder-img-lg { 41 | font-size: 3.5rem; 42 | } 43 | } 44 | 45 | .b-example-divider { 46 | height: 3rem; 47 | background-color: rgba(0, 0, 0, .1); 48 | border: solid rgba(0, 0, 0, .15); 49 | border-width: 1px 0; 50 | box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15); 51 | } 52 | 53 | .b-example-vr { 54 | flex-shrink: 0; 55 | width: 1.5rem; 56 | height: 100vh; 57 | } 58 | 59 | .bi { 60 | vertical-align: -.125em; 61 | fill: currentColor; 62 | } 63 | 64 | .nav-scroller { 65 | position: relative; 66 | z-index: 2; 67 | height: 2.75rem; 68 | overflow-y: hidden; 69 | } 70 | 71 | .nav-scroller .nav { 72 | display: flex; 73 | flex-wrap: nowrap; 74 | padding-bottom: 1rem; 75 | margin-top: -1px; 76 | overflow-x: auto; 77 | text-align: center; 78 | white-space: nowrap; 79 | -webkit-overflow-scrolling: touch; 80 | } -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | {% block title %}{% endblock title %} 10 | 11 | 12 | 14 | 15 | 16 | 17 | 18 | 36 | 37 | 38 | 39 | {% if messages %} 40 | 47 | {% endif %} 48 | {% block content %} 49 | 50 | {% endblock content %} 51 | 52 | 53 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block title %}BotHome - Home{% endblock title %} 4 | 5 | 6 | {% block content %} 7 |
8 | {% if not get_history %} 9 |

Hi {{request.user.username}} 👋, Let's Talk!🤖

10 | {% endif %} 11 |
    12 | {% for history in get_history %} 13 |
  1. 14 |
    15 |
    You ({{history.user.username}})
    16 | {{history.messageInput}} 17 |
    18 |
  2. 19 |
  3. 20 |
    21 |
    AI bot
    22 | {{history.bot_response}} 23 |
    24 |
  4. 25 | {% endfor %} 26 |
27 |
28 | {% csrf_token %} 29 | 30 |
31 | 33 | 35 |
36 |
37 | {% if get_history %} 38 | Delete Chat 39 | {% endif %} 40 | Log out 42 |
43 | 44 |
45 | 46 |
47 | {% endblock content %} -------------------------------------------------------------------------------- /templates/login.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% load static %} 3 | 4 | 5 | {% block title %}User Registration{% endblock title %} 6 | 7 | 8 | {% block content %} 9 | 10 |
11 |
12 | {% csrf_token %} 13 | 14 |

Please Log in

15 | 16 |
17 | {{form.username}} 18 | 19 |
20 |
21 | {{form.password}} 22 | 23 |
24 | 25 |

Don't have an account? Sign up

26 |

© 2023

27 |
28 |
29 | 30 | {% endblock content %} -------------------------------------------------------------------------------- /templates/users/register.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% load static %} 3 | 4 | 5 | {% block title %}User Registration{% endblock title %} 6 | 7 | 8 | {% block content %} 9 | 10 |
11 |
12 | {% csrf_token %} 13 | 14 |

Please sign up

15 | 16 |
17 | {{form.username}} 18 | 19 |
20 |
21 | {{form.password1}} 22 | 23 | 24 |
25 |
26 | {{form.password2}} 27 | 28 |
29 | 30 |

Already have an account? Log in

31 | 32 |

© 2023

33 |
34 |
35 | 36 | {% endblock content %} --------------------------------------------------------------------------------