Compare commits
No commits in common. "e55e489ce79de91774a60ad18171716315090637" and "cc05c9cf8a3547c02c85d6183bc8cfb9c41e2487" have entirely different histories.
e55e489ce7
...
cc05c9cf8a
2
.gitignore
vendored
2
.gitignore
vendored
@ -3,5 +3,3 @@ secrets/admins.txt
|
|||||||
python-bot/handlers/__pycache__
|
python-bot/handlers/__pycache__
|
||||||
python-bot/utils/__pycache__
|
python-bot/utils/__pycache__
|
||||||
python-bot/__pycache__
|
python-bot/__pycache__
|
||||||
python-bot/logs/bot.log
|
|
||||||
python-bot/data.json
|
|
||||||
|
|||||||
181
README.md
181
README.md
@ -1,150 +1,93 @@
|
|||||||
# Telegram-бот для молитвенного поминания
|
# Bot_of_Pray
|
||||||
## Описание проекта
|
|
||||||
Бот предоставляет пользователям возможность отправлять имена для молитвенного поминания священнику. Система позволяет добавлять имена в разные типы записок, оставлять комментарии и управлять своими записями.
|
|
||||||
## Основные функции
|
|
||||||
|
|
||||||
### Типы записок:
|
|
||||||
* О здравии
|
|
||||||
* За упокой
|
|
||||||
* Комментарии
|
|
||||||
|
|
||||||
### Управление записями:
|
|
||||||
* Просмотр текущих записей
|
|
||||||
* Добавление новых имен
|
|
||||||
* Очистка записей
|
|
||||||
* Сохранение изменений
|
|
||||||
|
|
||||||
### Админ-панель:
|
## Getting started
|
||||||
* Получение уведомлений о новых записях
|
|
||||||
* Статистика использования
|
|
||||||
* Управление записями
|
|
||||||
|
|
||||||
## Архитектура проекта
|
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||||
|
|
||||||
### Структура папок:
|
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||||
* handlers/ - обработчики команд и callback-запросов
|
|
||||||
* utils/ - вспомогательные функции
|
|
||||||
* messages.py - текстовые сообщения
|
|
||||||
* main.py - точка входа приложения
|
|
||||||
* prefixes.json - файл с префиксами
|
|
||||||
* requirements.txt - зависимости проекта
|
|
||||||
|
|
||||||
## Основные компоненты
|
## Add your files
|
||||||
|
|
||||||
### Обработчики:
|
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||||
* Пользовательские команды
|
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
||||||
* Callback-запросы
|
|
||||||
* Админ-команды
|
|
||||||
* Базовые функции
|
|
||||||
* Утилиты:
|
|
||||||
* Работа с базой данных
|
|
||||||
|
|
||||||
### Форматирование сообщений
|
```
|
||||||
* Отправка уведомлений
|
cd existing_repo
|
||||||
* Логирование
|
git remote add origin http://ce878cb2b302/artemiy/bot_of_pray.git
|
||||||
|
git branch -M main
|
||||||
## Требования и установка
|
git push -uf origin main
|
||||||
|
|
||||||
### Необходимые зависимости:
|
|
||||||
|
|
||||||
* Python 3.8+
|
|
||||||
* Python-telegram-bot
|
|
||||||
* Дополнительные библиотеки из requirements.txt
|
|
||||||
Настройка и запуск
|
|
||||||
|
|
||||||
## Настройка и запуск
|
|
||||||
|
|
||||||
### Контейнеризация проекта
|
|
||||||
|
|
||||||
Проект реализован с использованием Docker Compose. Конфигурация описана в файле docker-compose.yaml:
|
|
||||||
```yaml
|
|
||||||
services:
|
|
||||||
telegram-bot:
|
|
||||||
image: python
|
|
||||||
volumes:
|
|
||||||
- ./python-bot:/usr/src/app
|
|
||||||
- ./secrets:/usr/src/app/secrets
|
|
||||||
- ./requirements.txt:/usr/src/app/requirements.txt
|
|
||||||
working_dir: /usr/src/app
|
|
||||||
command: python main.py
|
|
||||||
environment:
|
|
||||||
- TELEGRAM_TOKEN_FILE=/usr/src/app/secrets/token.txt
|
|
||||||
- TELEGRAM_DATABASE=/usr/src/app/data.json
|
|
||||||
- TELEGRAM_ADMINS=/usr/src/app/secrets/admins.txt
|
|
||||||
entrypoint: ["sh", "-c", "export PIP_ROOT_USER_ACTION=ignore && pip install -r /usr/src/app/requirements.txt && pip install --upgrade pip && python main.py"]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Настройка окружения:
|
## Integrate with your tools
|
||||||
* Создайте файл .env с необходимыми переменными:
|
|
||||||
```bash
|
|
||||||
TELEGRAM_TOKEN_FILE=path/to/token.txt
|
|
||||||
TELEGRAM_DATABASE=path/to/database.json
|
|
||||||
TELEGRAM_ADMINS=path/to/admins.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
### Установка зависимостей:
|
- [ ] [Set up project integrations](http://ce878cb2b302/artemiy/bot_of_pray/-/settings/integrations)
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
### Запуск бота:
|
|
||||||
``` bash
|
|
||||||
python main.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## Структура данных
|
## Collaborate with your team
|
||||||
|
|
||||||
### База данных:
|
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||||
Хранится в формате JSON
|
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||||
|
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||||
|
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||||
|
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
||||||
|
|
||||||
### Структура:
|
## Test and Deploy
|
||||||
```
|
|
||||||
{
|
|
||||||
"user_id": {
|
|
||||||
"О здравии": ["имя1", "имя2"],
|
|
||||||
"За упокой": ["имя1", "имя2"],
|
|
||||||
"Комментарий": "текст комментария"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
## Развертывание
|
|
||||||
|
|
||||||
### Рекомендации:
|
Use the built-in continuous integration in GitLab.
|
||||||
|
|
||||||
* Используйте Docker для деплоя
|
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
|
||||||
* Настройте мониторинг состояния бота
|
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||||
* Добавьте систему автоматического перезапуска
|
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||||
* Обеспечьте регулярное резервное копирование данных
|
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||||
|
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||||
|
|
||||||
## Поддержка и развитие
|
***
|
||||||
|
|
||||||
### Документация:
|
# Editing this README
|
||||||
* Все основные функции документированы в коде
|
|
||||||
* Добавлены комментарии к критическим участкам
|
|
||||||
|
|
||||||
### Тестирование:
|
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||||
* Реализовано базовое логирование ошибок
|
|
||||||
* Добавлены проверки корректности данных
|
|
||||||
## Контактная информация
|
|
||||||
|
|
||||||
### Поддержка:
|
## Suggestions for a good README
|
||||||
Для вопросов и предложений обращайтесь к разработчикам
|
|
||||||
## Лицензирование
|
|
||||||
|
|
||||||
### Лицензия:
|
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||||
|
|
||||||
GPL3.0
|
## Name
|
||||||
|
Choose a self-explaining name for your project.
|
||||||
|
|
||||||
## История изменений
|
## Description
|
||||||
|
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||||
|
|
||||||
### Версия 1.0:
|
## Badges
|
||||||
|
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||||
|
|
||||||
* Базовая функциональность
|
## Visuals
|
||||||
|
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||||
|
|
||||||
* Система уведомлений
|
## Installation
|
||||||
|
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||||
|
|
||||||
* Управление записями
|
## Usage
|
||||||
|
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||||
|
|
||||||
* Админ-панель
|
## Support
|
||||||
|
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||||
|
|
||||||
|
## Roadmap
|
||||||
|
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
State if you are open to contributions and what your requirements are for accepting them.
|
||||||
|
|
||||||
|
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||||
|
|
||||||
|
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||||
|
|
||||||
|
## Authors and acknowledgment
|
||||||
|
Show your appreciation to those who have contributed to the project.
|
||||||
|
|
||||||
|
## License
|
||||||
|
For open source projects, say how it is licensed.
|
||||||
|
|
||||||
|
## Project status
|
||||||
|
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||||
|
|||||||
16
python-bot/data.json
Normal file
16
python-bot/data.json
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"275365081": {},
|
||||||
|
"5208958601": {},
|
||||||
|
"5138022092": {},
|
||||||
|
"1052025073": {},
|
||||||
|
"5194228756": {},
|
||||||
|
"396736532": {},
|
||||||
|
"65282424": {
|
||||||
|
"Комментарий": "<href=asdas>"
|
||||||
|
},
|
||||||
|
"6904456206": {},
|
||||||
|
"560771220": {},
|
||||||
|
"141910767": {},
|
||||||
|
"1190907418": {},
|
||||||
|
"1048114637": {}
|
||||||
|
}
|
||||||
70
python-bot/handlers/callback_handlers.py.save
Normal file
70
python-bot/handlers/callback_handlers.py.save
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
from telegram import Update
|
||||||
|
from telegram.ext import CallbackQueryHandler, CallbackContext
|
||||||
|
from utils.logger import logger
|
||||||
|
from handlers.user_handlers import names_menu, user_start
|
||||||
|
from utils.database import save_database, USER_DATA
|
||||||
|
from handlers.database_handlers import show_names, clear_names
|
||||||
|
from utils.message_sender import send_message
|
||||||
|
from utils.user_data import get_user_info
|
||||||
|
from handlers.admin_handlers import notify_admins
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_admin_buttons(update: Update, context: CallbackContext) -> None: #handlers/callback_handlers.py
|
||||||
|
query = update.callback_query
|
||||||
|
query.answer()
|
||||||
|
del context.user_data['type']
|
||||||
|
if query.data == 'admin_action1':
|
||||||
|
bot.send_message(chat_id=query.message.chat_id, text="Выполнено админ действие 1")
|
||||||
|
elif query.data == 'admin_action2':
|
||||||
|
bot.send_message(chat_id=query.message.chat_id, text="Выполнено админ действие 2")
|
||||||
|
|
||||||
|
async def handle_user_buttons(update: Update, context: CallbackContext) -> None: #handlers/callback_handlers.py
|
||||||
|
global USER_DATA
|
||||||
|
if
|
||||||
|
del context.user_data['type']
|
||||||
|
query = update.callback_query
|
||||||
|
await query.answer()
|
||||||
|
|
||||||
|
if query.data == "user_life":
|
||||||
|
context.user_data['type'] = "О здравии"
|
||||||
|
elif query.data == "user_dead":
|
||||||
|
context.user_data['type'] = "За упокой"
|
||||||
|
elif query.data == "user_comment":
|
||||||
|
context.user_data['type'] = "Комментарий"
|
||||||
|
elif query.data == "user_show":
|
||||||
|
await show_names(update, context)
|
||||||
|
return
|
||||||
|
elif query.data == "user_send":
|
||||||
|
try:
|
||||||
|
save_database(USER_DATA)
|
||||||
|
except:
|
||||||
|
logger.error("Ошибка сохранения в файл json: {e}")
|
||||||
|
return
|
||||||
|
user_info = await get_user_info(update, context)
|
||||||
|
# admin_notify(udate, context,)
|
||||||
|
await notify_admins(update, context, user_info["name"])
|
||||||
|
#Отправляем сообщение админам
|
||||||
|
return
|
||||||
|
elif query.data == "user_clear":
|
||||||
|
try:
|
||||||
|
del context.user_data['type']
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
await clear_names(update, context)
|
||||||
|
await user_start(update, context)
|
||||||
|
return
|
||||||
|
elif query.data == "user_clear_type":
|
||||||
|
await clear_names(update, context)
|
||||||
|
await names_menu(update, context)
|
||||||
|
return
|
||||||
|
# Переходим в меню имен только если выбран корректный тип
|
||||||
|
if context.user_data.get('type'):
|
||||||
|
await names_menu(update, context)
|
||||||
|
else:
|
||||||
|
await send_message(update, context,"Неверный запрос")
|
||||||
|
|
||||||
|
|
||||||
|
def register_handlers(app):
|
||||||
|
app.add_handler(CallbackQueryHandler(handle_user_buttons, pattern='^user_'))
|
||||||
|
app.add_handler(CallbackQueryHandler(handle_admin_buttons, pattern='^admin_'))
|
||||||
|
# app.add_handler(CallbackQueryHandler(handle_confirm_buttons, pattern='^confirm_'))
|
||||||
49
python-bot/handlers/parse_handlers.py.bak
Normal file
49
python-bot/handlers/parse_handlers.py.bak
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
from telegram import Update
|
||||||
|
from telegram.ext import CommandHandler, MessageHandler, filters, CallbackContext
|
||||||
|
from utils.logger import logger
|
||||||
|
from handlers.user_handlers import user_keyboard
|
||||||
|
from utils.message_sender import send_message
|
||||||
|
from utils.prefixes import PREFIXES
|
||||||
|
|
||||||
|
async def parse_names(update: Update, context: CallbackContext) -> None:
|
||||||
|
global USER_DATA
|
||||||
|
|
||||||
|
try:
|
||||||
|
typen = context.user_data['type']
|
||||||
|
user_info = await get_user_info(update)
|
||||||
|
user_id = user_info["id"]
|
||||||
|
|
||||||
|
# Для комментария сохраняем весь текст
|
||||||
|
if typen == "Комментарий":
|
||||||
|
names = update.message.text.strip()
|
||||||
|
else:
|
||||||
|
# Парсим имена для других типов
|
||||||
|
|
||||||
|
names = parse_names_helper(update.message.text)
|
||||||
|
|
||||||
|
# Сохраняем данные
|
||||||
|
if user_id not in USER_DATA:
|
||||||
|
USER_DATA[user_id] = {}
|
||||||
|
|
||||||
|
if typen not in USER_DATA[user_id]:
|
||||||
|
USER_DATA[user_id][typen] = []
|
||||||
|
|
||||||
|
# Для комментария сохраняем строку, для остальных - список
|
||||||
|
if typen == "Комментарий":
|
||||||
|
USER_DATA[user_id][typen] = names
|
||||||
|
else:
|
||||||
|
USER_DATA[user_id][typen].extend(names)
|
||||||
|
|
||||||
|
# Форматируем вывод
|
||||||
|
if typen == "Комментарий":
|
||||||
|
await send_message(update, context, f"Сохранен комментарий: {names}")
|
||||||
|
else:
|
||||||
|
saved_names = ', '.join(USER_DATA[user_id][typen])
|
||||||
|
await send_message(update, context, f"{typen}: {saved_names}")
|
||||||
|
logger.info(f"{USER_DATA}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Ошибка при обработке: {e}")
|
||||||
|
await send_message(update, context, "Произошла ошибка при обработке данных")
|
||||||
|
del context.user_data['type']
|
||||||
|
await send_message (update,context,"Выберите действие:", reply_markup=user_keyboard)
|
||||||
82618
python-bot/logs/bot.log
Normal file
82618
python-bot/logs/bot.log
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
x
Reference in New Issue
Block a user