Commit 81d7044c authored by Dmitry Shelepnev's avatar Dmitry Shelepnev
Browse files

Test alpha-version of telebot

parent 48f12571
Loading
Loading
Loading
Loading
+2 −3
Original line number Diff line number Diff line
@@ -22,7 +22,7 @@ or from github.com with the following command:

The following dependencies should be established for the project:

    yum install python3                            # setup command for RedHad, Fedora, CentOS
    yum install python3                            # setup command for RHEL, Fedora, CentOS
    python3 -m pip install -r requirements.txt

1.3 We initialize the database and fill in the initial data (genres)
@@ -67,8 +67,7 @@ If all previous steps were successful, then the library can be accessed by the f
>     HTTP-version: http://<Your server>:8001/

It should be taken into account that by default the project uses a simple sqlite3 database, which
is one-user. Therefore, until the scanning process is completed, the
previous attempts to access the server may result in an error
is one-user. Therefore, until the scanning process is completed, the attempts to access the server may result in an error
"A server error occurred." Please contact the administrator. "
To eliminate this problem, you need to use multi-user databases, for example MYSQL.

+2 −2
Original line number Diff line number Diff line
@@ -22,7 +22,7 @@

Для работы проекта необходимо установить указанные  зависимости: 

	yum install python3                            # команда установки для RedHad, Fedora, CentOS
	yum install python3                            # команда установки для RHEL, Fedora, CentOS
	python3 -m pip install -r requirements.txt
   
1.3 Производим инициализацию базы данных и заполнение начальными данными (жанры)
@@ -70,7 +70,7 @@

Следует принять во внимание, что по умолчанию в проекте используется простая БД sqlite3, которая
является одно-пользовательской. Поэтому пока не будет завершен процесс сканирования, запущенный 
ранее попытки доступа к серверу могут завершаться ошибкой 
ранее, попытки доступа к серверу могут завершаться ошибкой
"A server error occurred.  Please contact the administrator."  
Для устранения указанной проблемы необходимо ипользовать многопользовательские БД, Например MYSQL.
	
+64 −11
Original line number Diff line number Diff line
@@ -2,15 +2,17 @@ import os
import signal
import sys
import logging
import re

from django.core.management.base import BaseCommand
from django.db import transaction, connection, connections
from django.conf import settings as main_settings
from django.urls import reverse

from opds_catalog.models import Book, Author, Series, bookshelf, Counter, Catalog, Genre, lang_menu
from opds_catalog.models import Book, Author
from opds_catalog import settings 
from constance import config
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

class Command(BaseCommand):
    help = 'SimpleOPDS Telegram Bot engine.'
@@ -60,21 +62,70 @@ class Command(BaseCommand):
        bot.sendMessage(chat_id=update.message.chat_id, text="Здравствуйте %s! Для поиска книги, введите ее полное наименование или часть:"%(update.message.from_user.username))
        self.logger.info("Start talking with user: %s"%update.message.from_user)

    def textMessage(self, bot, update):
    def getBooks(self, bot, update):
        book_name=update.message.text
        response = 'Выполняю поиск книги: %s' % (book_name)
        self.logger.info("Got message from user %s: %s" % (update.message.from_user.username, book_name))

        if len(book_name)<3:
            response = 'Слишком короткая строка для поиска, попробуйте еще раз.'
        else:
            response = 'Выполняю поиск книги: %s' % (book_name)

        bot.send_message(chat_id=update.message.chat_id, text=response)
        self.logger.info("Send message to user %s: %s" % (update.message.from_user.username,response))

        if len(book_name) < 3:
            return

        books = Book.objects.filter(search_title__contains=book_name.upper()).order_by('search_title', '-docdate')
        response = "Найдено %s книг. Выберите нужную для скачивания."%books.count()
        bcount = books.count()

        response = 'По Вашему запросу ничего не найдено, попробуйте еще раз.' if bcount==0 else 'Найдено %s книг(и). Выберите нужную для скачивания.'%bcount
        bot.send_message(chat_id=update.message.chat_id, text=response)
        self.logger.info("Send message to user %s: %s" % (update.message.from_user.username,response))

        if books.count()>0:
            for b in books:
                bot.send_message(chat_id=update.message.chat_id, text=b.title)
                # bot.send_message(chat_id=update.message.chat_id, text=(', '.join(a['full_name']) for a in b.authors.values()) )
                bot.send_message(chat_id=update.message.chat_id, text="Скачать книгу: %s\n\n"%b.filename)
                authors = ', '.join([a['full_name'] for a in b.authors.values()])
                response='<b>%(title)s</b>\n%(author)s\n/download%(link)s\n\n'%{'title':b.title, 'author':authors,'link':b.id}
                bot.send_message(chat_id=update.message.chat_id, text=response, parse_mode='HTML')

    def downloadBooks(self, bot, update):
        book_id_set=re.findall(r'\d+$',update.message.text)
        if len(book_id_set)==1:
            try:
                book_id=int(book_id_set[0])
                book=Book.objects.get(id=book_id)
            except:
                book=None
        else:
            book_id=None
            book=None

        if book==None:
            response = 'Книга по указанной Вами ссылке не найдена, попробуйте повторить поиск книги сначала.'
            bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML')
            self.logger.info("Not find download links: %s" % response)
            return

        authors = ', '.join([a['full_name'] for a in book.authors.values()])
        response = '<b>%(title)s</b>\n%(author)s\n<b>Аннотация:</b>%(annotation)s\n' % {'title': book.title, 'author': authors, 'annotation':book.annotation}

        buttons = [InlineKeyboardButton(book.format.upper(),
                                        url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download", kwargs={"book_id": book.id, "zip_flag": 0}))]
        if not book.format in settings.NOZIP_FORMATS:
            buttons += [InlineKeyboardButton(book.format.upper()+'.ZIP',
                                             url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:download",kwargs={"book_id": book.id, "zip_flag": 1}))]
        if (config.SOPDS_FB2TOEPUB != "") and (book.format == 'fb2'):
            buttons += [InlineKeyboardButton('EPUB',
                                             url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "epub"}))]
        if (config.SOPDS_FB2TOMOBI != "") and (book.format == 'fb2'):
            buttons += [InlineKeyboardButton('MOBI',
                                             url=config.SOPDS_SITE_ROOT+reverse("opds_catalog:convert",kwargs={"book_id": book.id, "convert_type": "mobi"}))]

        markup = InlineKeyboardMarkup([buttons])
        bot.sendMessage(chat_id=update.message.chat_id, text=response, parse_mode='HTML', reply_markup=markup)
        self.logger.info("Send download buttons: %s" % buttons)

    def start(self):
        writepid(self.pidfile)
@@ -84,10 +135,12 @@ class Command(BaseCommand):
            updater = Updater(token=config.SOPDS_TELEBOT_API_TOKEN)

            start_command_handler = CommandHandler('start', self.startCommand)
            text_message_handler = MessageHandler(Filters.text, self.textMessage)
            getBook_handler = MessageHandler(Filters.text, self.getBooks)
            download_handler = RegexHandler('^/download\d+$',self.downloadBooks)

            updater.dispatcher.add_handler(start_command_handler)
            updater.dispatcher.add_handler(text_message_handler)
            updater.dispatcher.add_handler(getBook_handler)
            updater.dispatcher.add_handler(download_handler)
            updater.start_polling(clean=True)
            updater.idle()
        except (KeyboardInterrupt, SystemExit):
+2 −1
Original line number Diff line number Diff line
@@ -175,6 +175,7 @@ CONSTANCE_CONFIG = OrderedDict([
    ('SOPDS_CACHE_TIME', (1200, _('Pages cache time'))),

    ('SOPDS_TELEBOT_API_TOKEN', ('', _('Telegramm API Token'))),
    ('SOPDS_SITE_ROOT', ('http://you_domain:8001/', _('Root URL for your SOPDS Site'))),
    
    ('SOPDS_AUTH', (True,_('Enable authentication'))),
    ('SOPDS_ALPHABET_MENU', (True,_('Enable alphabet submenu'))),   
@@ -218,7 +219,7 @@ CONSTANCE_CONFIG_FIELDSETS = {
    '2. Server Options': ('SOPDS_AUTH', 'SOPDS_ALPHABET_MENU', 'SOPDS_DOUBLES_HIDE', 'SOPDS_COVER_SHOW', 'SOPDS_SPLITITEMS', 'SOPDS_MAXITEMS', 'SOPDS_TITLE_AS_FILENAME', 'SOPDS_NOCOVER_PATH'),    
    '3. Scanner Options': ('SOPDS_FB2SAX','SOPDS_ZIPSCAN','SOPDS_ZIPCODEPAGE', 'SOPDS_INPX_ENABLE', 'SOPDS_INPX_SKIP_UNCHANGED', 'SOPDS_INPX_TEST_ZIP', 'SOPDS_INPX_TEST_FILES', 'SOPDS_DELETE_LOGICAL'),
    '4. Scanner Shedule': ('SOPDS_SCAN_SHED_MIN', 'SOPDS_SCAN_SHED_HOUR', 'SOPDS_SCAN_SHED_DAY','SOPDS_SCAN_SHED_DOW'),
    '5. Telegramm Bot Options': ('SOPDS_TELEBOT_API_TOKEN',),
    '5. Telegramm Bot Options': ('SOPDS_TELEBOT_API_TOKEN','SOPDS_SITE_ROOT'),
    '6. Converters Options': ('SOPDS_FB2TOEPUB', 'SOPDS_FB2TOMOBI', 'SOPDS_TEMP_DIR'),
    '7. Log & PID Files': ('SOPDS_SERVER_LOG', 'SOPDS_SCANNER_LOG', 'SOPDS_TELEBOT_LOG','SOPDS_SERVER_PID','SOPDS_SCANNER_PID','SOPDS_TELEBOT_PID'),
}