Browse Source

админ панель #5

Anton 1 year ago
parent
commit
2793ceb640
  1. 3
      .gitignore
  2. 49
      README.md
  3. 0
      adminpanel/__init__.py
  4. 16
      adminpanel/asgi.py
  5. 4
      adminpanel/config.py
  6. 9
      adminpanel/settings.py
  7. 11
      adminpanel/urls.py
  8. 16
      adminpanel/wsgi.py
  9. 0
      adminpanelapp/__init__.py
  10. 44
      adminpanelapp/admin.py
  11. 6
      adminpanelapp/apps.py
  12. 0
      adminpanelapp/migrations/__init__.py
  13. 39
      adminpanelapp/models.py
  14. 6
      adminpanelapp/templates/send_telegram_message.html
  15. 3
      adminpanelapp/tests.py
  16. 10
      adminpanelapp/urls.py
  17. 4
      adminpanelapp/views.py
  18. 11
      bot_sys/config.py
  19. 22
      manage.py
  20. 2
      requirements.txt
  21. 2
      template/bd_item_add.py

3
.gitignore vendored

@ -3,3 +3,6 @@ config_root_ids
__pycache__
log.txt
bot.db
adminpanelapp/migrations
adminpanel/__init__.py
.env

49
README.md

@ -1,4 +1,4 @@
## TPlatformBot
TPlatformBot
### Видеоинструкции
@ -17,25 +17,25 @@
3. Профиль пользователя
4. Права доступа
5. Пользователи и группы пользователей
4. Проекты
5. Задачи
6. Потребности
7. Комментарии
8. Языки (сообщения и кнопки)
9. Заказы
10. Подписки
6. Проекты
7. Задачи
8. Потребности
9. Комментарии
10. Языки (сообщения и кнопки)
11. Заказы
12. Подписки
---------
---
Данный бот позволяет создать свою площадку для взаимодействия на некоммерческой основе в мессенджере Telegram и обмениваться ресурсами и компетенциями для реализации различных проектов.
Сам бот разработан на языке программирования **Python** с использованием фреймворка **Aiogram**. База данных - **SQLite3**.
------
---
**Установка, первичная настройка и запуск**
>Для работы требуется, как минимум, Python 3.8.
> Для работы требуется, как минимум, Python 3.8.
*** Загрузка зависимостей ***
@ -45,7 +45,7 @@
`sudo apt-get install python3-modules-sqlite3`
`python3 -m pip install -r requirements.txt`
`python3 -m pip install -r requirements.txt`
*** Запуск ***
@ -65,4 +65,27 @@
## Тестовая версия
Тестовая версия запущена по ссылке
http://t.me/Test_TPlatform_bot
http://t.me/Test_TPlatform_bot
## Запуск Админ панели
## 1. Выполните миграции
python manage.py migrate
2. Создайте суперпользователя
python manage.py createsuperuser
3. Введите имя пользователя, почту и пароль
4. Запустите сервер
python manage.py runserver
5. Перейдите по адерсу http://127.0.0.1:8000/ (адрес выведится в терминале) и введите данные ранее созданного пользователя и пароль
## 2. Создайте SECRET_KEY для джанго
1. Создайте в корне проекта файл .env
2. Сгенерирйте секретный ключ. Для этого в терминале (python manage.py shell) выполните следующие команды.
from django.core.management.utils import get_random_secret_key
get_random_secret_key()
3. Вставьте полученный ключ в файл .env
SECRET_KEY='ваш секретный ключ'

0
adminpanel/__init__.py

16
adminpanel/asgi.py

@ -1,16 +0,0 @@
"""
ASGI config for adminpanel project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanel.settings')
application = get_asgi_application()

4
adminpanel/config.py

@ -4,8 +4,6 @@ g_telegram_bot_api_token = ''
telegram_bot_api_token_file_name = 'config_telegram_bot_api_token'
# ---------------------------------------------------------
# Дополнительные функции
def ClearReadLine(a_Line):
return a_Line[:-1]
def GetFirstLineFromFile(a_FileName):
f = open(a_FileName, 'r')
result = f.readline()
@ -21,5 +19,5 @@ def GetAllLinesFromFile(a_FileName):
def GetTelegramBotApiToken():
global g_telegram_bot_api_token
if len(g_telegram_bot_api_token) == 0:
g_telegram_bot_api_token = ClearReadLine(GetFirstLineFromFile(telegram_bot_api_token_file_name))
g_telegram_bot_api_token = str().strip(GetFirstLineFromFile(telegram_bot_api_token_file_name))
return g_telegram_bot_api_token

9
adminpanel/settings.py

@ -11,21 +11,22 @@ https://docs.djangoproject.com/en/4.1/ref/settings/
"""
import os
from pathlib import Path
from dotenv import load_dotenv
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-13x&cmg=f1gx9u(i@s(xplh+4x=+@ucyujcqf2t3hu7@i(k=fe'
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['127.0.0.1', 'mirocod.svo.ru']
# Application definition
@ -106,7 +107,7 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ru'
TIME_ZONE = 'UTC'

11
adminpanel/urls.py

@ -1,11 +0,0 @@
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('adminpanelapp.urls')),
path('', RedirectView.as_view(url='/admin/adminpanelapp/orders'), name='')
]

16
adminpanel/wsgi.py

@ -1,16 +0,0 @@
"""
WSGI config for adminpanel project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanel.settings')
application = get_wsgi_application()

0
adminpanelapp/__init__.py

44
adminpanelapp/admin.py

@ -1,44 +0,0 @@
from django.http import HttpResponseRedirect
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.utils.safestring import mark_safe
from .models import Orders
from django.contrib import admin, messages
from django.urls import reverse
class OrdersAdmin(admin.ModelAdmin):
list_display = ('orderName', 'orderCreateDateTime', 'orderDesc', 'orderAddress', 'show_photo', 'show_photopay')
actions =['send_message']
exclude = ['orderAccess', 'userID', 'orderPhoto', 'orderPhotoPay']
def show_photo(self, obj):
html = obj.get_photo_html()
return mark_safe(html)
show_photo.short_description = 'Фото'
def show_photopay(self, obj):
html = obj.get_photopay_html()
return mark_safe(html)
show_photopay.short_description = 'Чек'
def send_message(orders, request, queryset):
selected_objects = request.POST.getlist(ACTION_CHECKBOX_NAME)
if len(selected_objects) != 1:
messages.error(request, "Выберите только один объект")
return
selected_user_id = int(selected_objects[0])
obj = queryset.get(orderID=selected_user_id)
user_id = obj.userID
url = reverse('send_telegram_message', kwargs={'chat_id': user_id})
return HttpResponseRedirect(url)
send_message.short_description = 'Отправка сообщения'
admin.site.register(Orders, OrdersAdmin)

6
adminpanelapp/apps.py

@ -1,6 +0,0 @@
from django.apps import AppConfig
class AdminpanelappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'adminpanelapp'

0
adminpanelapp/migrations/__init__.py

39
adminpanelapp/models.py

@ -1,3 +1,4 @@
import time
from urllib.parse import quote
import requests
@ -14,7 +15,7 @@ class Orders(models.Model):
orderName = models.CharField(max_length=100, verbose_name='наименование', null=True)
orderDesc = models.TextField(verbose_name='описание', null=True)
orderPhoto = models.ImageField(verbose_name='фото', null=True)
orderPhotoPay = models.ImageField(upload_to='photo/', verbose_name='чек')
orderPhotoPay = models.ImageField(verbose_name='чек')
orderAddress = models.CharField(max_length=100, verbose_name='адрес доставки', blank=True, null=True)
orderAccess = models.CharField(max_length=100, verbose_name='доступ', blank=True, null=True)
orderCreateDateTime = models.DateTimeField(auto_now_add=True, null=True, verbose_name='дата и время создания')
@ -37,12 +38,13 @@ class Orders(models.Model):
<body>
<img src="{photo_url}" width="{width}" height="{height}" class="small-photo">
<img src="{photo_url}" width="{large_width}" height="{large_height}" class="large-photo">
<a href="#" onclick="togglePhoto()" id="toggle-button" class="button">Увеличить фото</a>
<a href="#" onclick="togglePhoto(event)" class="button">Увеличить фото</a>
<script>
function togglePhoto() {{
var smallPhoto = document.getElementsByClassName("small-photo")[0];
var largePhoto = document.getElementsByClassName("large-photo")[0];
var toggleButton = document.getElementById("toggle-button");
function togglePhoto(event) {{
var toggleButton = event.target;
var container = toggleButton.parentNode;
var smallPhoto = container.querySelector(".small-photo");
var largePhoto = container.querySelector(".large-photo");
if (smallPhoto.style.display === "none") {{
smallPhoto.style.display = "block";
@ -86,6 +88,7 @@ class Orders(models.Model):
response = requests.get(url)
data = response.json()
if data['ok']:
file_path = data["result"]["file_path"]
photo_url = f"https://api.telegram.org/file/bot{token}/{quote(file_path, safe='')}"
@ -95,20 +98,21 @@ class Orders(models.Model):
<body>
<img src="{photo_url}" width="{width}" height="{height}" class="small-photo">
<img src="{photo_url}" width="{large_width}" height="{large_height}" class="large-photo">
<a href="#" onclick="togglePhotoPay()" id="toggle-button" class="button">Увеличить фото</a>
<a href="#" onclick="togglePhoto(event)" class="button">Увеличить фото</a>
<script>
function togglePhotoPay() {{
var smallPhotoPay = document.getElementsByClassName("small-photo")[1];
var largePhotoPay = document.getElementsByClassName("large-photo")[1];
var toggleButton = document.getElementById("toggle-button");
if (smallPhotoPay.style.display === "none") {{
smallPhotoPay.style.display = "block";
largePhotoPay.style.display = "none";
function togglePhoto(event) {{
var toggleButton = event.target;
var container = toggleButton.parentNode;
var smallPhoto = container.querySelector(".small-photo");
var largePhoto = container.querySelector(".large-photo");
if (smallPhoto.style.display === "none") {{
smallPhoto.style.display = "block";
largePhoto.style.display = "none";
toggleButton.innerHTML = "Увеличить фото";
}} else {{
smallPhotoPay.style.display = "none";
largePhotoPay.style.display = "block";
smallPhoto.style.display = "none";
largePhoto.style.display = "block";
toggleButton.innerHTML = "Уменьшить фото";
}}
}}
@ -135,6 +139,7 @@ class Orders(models.Model):
"""
return html
class Meta:
verbose_name_plural = 'Заказы'

6
adminpanelapp/templates/send_telegram_message.html

@ -0,0 +1,6 @@
<form method="post">
{% csrf_token %}
<label for="message">Сообщение:</label>
<input type="text" chat_id="message" name="message">
<button type="submit">Отправить сообщение</button>
</form>

3
adminpanelapp/tests.py

@ -1,3 +0,0 @@
from django.test import TestCase
# Create your tests here.

10
adminpanelapp/urls.py

@ -1,10 +0,0 @@
from django.urls import path, include
from .views import send_telegram_message
urlpatterns = [
path('send_telegram_message/<int:chat_id>/', send_telegram_message, name='send_telegram_message'),
]

4
adminpanelapp/views.py

@ -3,14 +3,14 @@ from django.http import HttpResponseRedirect
import requests
from django.urls import reverse
from django.shortcuts import render
from bot_sys.config import g_telegram_bot_api_token
from bot_sys.config import GetTelegramBotApiToken
def send_telegram_message(request, chat_id):
if request.method == 'POST':
message = request.POST.get('message')
bot_token = g_telegram_bot_api_token
bot_token = GetTelegramBotApiToken()
url = f'https://api.telegram.org/bot{bot_token}/sendMessage?text={message}&chat_id={chat_id}'
response = requests.get(url)

11
bot_sys/config.py

@ -24,11 +24,12 @@ root_ids_file_name = 'config_root_ids'
# Дополнительные функции
def ClearReadLine(a_Line):
cleaned_line = ""
for char in a_Line:
if char.isprintable():
cleaned_line += char
return cleaned_line
<<<<<<< HEAD
line = a_Line.strip()
return line
=======
return a_Line[:-1]
>>>>>>> parent of 88fcd3e (админпанель для бота #5)
def GetFirstLineFromFile(a_FileName):
f = open(a_FileName, 'r')

22
manage.py

@ -1,22 +0,0 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'adminpanel.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

2
requirements.txt

@ -1,2 +1,4 @@
aiogram==2.20
colorama==0.4.5
Django==2.2.1
python-dotenv

2
template/bd_item_add.py

@ -82,7 +82,7 @@ def FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableNa
if a_Message.photo == None or len(a_Message.photo) == 0:
await state.finish()
return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(error_photo_type_message), keyboard_func = a_FinishButtonFunc)
field_value = a_Message.photo[-1].file_id
field_value = a_Message.photo[0].file_id
else:
result = a_Message.text
if a_PostProcessFunc:

Loading…
Cancel
Save