commit 61137438c2ea1f8c2cd7a484c5bb308154c3778d Author: Sanders Date: Fri Feb 7 14:00:16 2025 +0300 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ca0a5a2 --- /dev/null +++ b/build.gradle @@ -0,0 +1,57 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.2' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'ru.cathub' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' +// developmentOnly 'org.springframework.boot:spring-boot-docker-compose' + runtimeOnly 'org.postgresql:postgresql' + + implementation 'org.springframework.boot:spring-boot-starter-cache' + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + //testImplementation 'org.springframework.boot:spring-boot-testcontainers' + //testImplementation 'org.testcontainers:junit-jupiter' + //testImplementation 'org.testcontainers:postgresql' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + // implementation group: 'org.telegram', name: 'telegrambots', version: '6.9.7.1' + + // implementation 'org.telegram:telegrambots-meta:8.2.0' // И эту +// https://mvnrepository.com/artifact/org.telegram/telegrambots-springboot-longpolling-starter + implementation group: 'org.telegram', name: 'telegrambots-springboot-longpolling-starter', version: '7.2.0' +// https://mvnrepository.com/artifact/org.telegram/telegrambots-client + implementation group: 'org.telegram', name: 'telegrambots-client', version: '7.2.0' + + implementation 'org.hibernate:hibernate-core:6.4.4.Final' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + + // https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine + implementation group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.2.0' + + // https://mvnrepository.com/artifact/io.hypersistence/hypersistence-utils-hibernate-63 + implementation group: 'io.hypersistence', name: 'hypersistence-utils-hibernate-63', version: '3.9.1' + + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/create.sql b/create.sql new file mode 100644 index 0000000..6eeeb09 --- /dev/null +++ b/create.sql @@ -0,0 +1,964 @@ +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; + + create table books ( + rating integer, + bot_user_id bigint, + id bigint generated by default as identity, + author varchar(255), + title varchar(255), + primary key (id) + ); + + create table bot_user ( + chat_id bigint, + created_date_time timestamp(6), + id bigint not null, + user_type varchar(255) check (user_type in ('USER','ADMIN')), + working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), + primary key (id) + ); + + create table messages ( + bot_user_id bigint, + created_at timestamp(6), + id bigint generated by default as identity, + content TEXT, + type varchar(255) check (type in ('TEXT','FILE','COMMAND')), + primary key (id) + ); + + alter table if exists books + add constraint FKa9x6empm1nnnicld7s6v8yipr + foreign key (bot_user_id) + references bot_user; + + alter table if exists messages + add constraint FKbaqitbc8w0203kqcxcj88wfn9 + foreign key (bot_user_id) + references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; +create table books (rating integer, bot_user_id bigint, id bigint generated by default as identity, author varchar(255), title varchar(255), primary key (id)); +create table bot_user (chat_id bigint, created_date_time timestamp(6), id bigint not null, user_type varchar(255) check (user_type in ('USER','ADMIN')), working_mode varchar(255) check (working_mode in ('BOOK','TORRENT','AI','NO_MODE')), primary key (id)); +create table messages (bot_user_id bigint, created_at timestamp(6), id bigint generated by default as identity, content TEXT, type varchar(255) check (type in ('TEXT','FILE','COMMAND')), primary key (id)); +alter table if exists books add constraint FKa9x6empm1nnnicld7s6v8yipr foreign key (bot_user_id) references bot_user; +alter table if exists messages add constraint FKbaqitbc8w0203kqcxcj88wfn9 foreign key (bot_user_id) references bot_user; diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e2847c8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..9042edc --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'TelegaBot' diff --git a/src/main/java/ru/cathub/telegabot/TelegaBotApplication.java b/src/main/java/ru/cathub/telegabot/TelegaBotApplication.java new file mode 100644 index 0000000..672a383 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/TelegaBotApplication.java @@ -0,0 +1,13 @@ +package ru.cathub.telegabot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TelegaBotApplication { + + public static void main(String[] args) { + SpringApplication.run(TelegaBotApplication.class, args); + } + +} diff --git a/src/main/java/ru/cathub/telegabot/bot/KeyboardHelper.java b/src/main/java/ru/cathub/telegabot/bot/KeyboardHelper.java new file mode 100644 index 0000000..daeb4c2 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/bot/KeyboardHelper.java @@ -0,0 +1,172 @@ +package ru.cathub.telegabot.bot; + +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardRow; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; +import ru.cathub.telegabot.model.Book; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.repository.BookRepository; + +import java.util.ArrayList; +import java.util.List; + +import static ru.cathub.telegabot.utils.Constants.*; + +public class KeyboardHelper { + + public static ReplyKeyboardMarkup getMainMenuKeyboard() { + + List keyboardRows = new ArrayList<>(); + + // Первая строка кнопок + // KeyboardRow row1 = new KeyboardRow(); + // row1.add(new KeyboardButton("Отправить текст")); + // row1.add(new KeyboardButton("Загрузить .torrent")); + + // Вторая строка кнопок + KeyboardRow row2 = new KeyboardRow(); + row2.add(new KeyboardButton("Книжник")); + row2.add(new KeyboardButton("Помощь")); + + // keyboardRows.add(row1); + keyboardRows.add(row2); + + + ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(keyboardRows); + keyboardMarkup.setResizeKeyboard(true); // Адаптировать размер клавиатуры + keyboardMarkup.setOneTimeKeyboard(false); // Клавиатура остается после использования + + + return keyboardMarkup; + } + + public static ReplyKeyboardMarkup getBookMenuKeyboard() { + List keyboardRows = new ArrayList<>(); + + KeyboardRow row1 = new KeyboardRow(); + row1.add(new KeyboardButton(ADD_BOOK)); + row1.add(new KeyboardButton(LIST_BOOKS)); + + KeyboardRow row2 = new KeyboardRow(); + row2.add(new KeyboardButton(EDIT_BOOKS)); + row2.add(new KeyboardButton(BACK)); + + keyboardRows.add(row1); + keyboardRows.add(row2); + + ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(keyboardRows); + keyboardMarkup.setResizeKeyboard(true); + keyboardMarkup.setOneTimeKeyboard(false); + + return keyboardMarkup; + } + + public static InlineKeyboardMarkup getBookListKeyboard(int currentPage, boolean hasNext) { + + + List rows = new ArrayList<>(); + + // Кнопки навигации + InlineKeyboardRow navRow = new InlineKeyboardRow(); + + if (currentPage > 0) { + navRow.add(InlineKeyboardButton.builder() + .text("← Назад") + .callbackData("BOOK_PAGE_" + (currentPage - 1)) + .build()); + } + + if (hasNext) { + navRow.add(InlineKeyboardButton.builder() + .text("Вперед →") + .callbackData("BOOK_PAGE_" + (currentPage + 1)) + .build()); + } + + if (!navRow.isEmpty()) { + rows.add(navRow); + } + return new InlineKeyboardMarkup(rows); + } + + + public static InlineKeyboardMarkup getBookEditListKeyboard(BotUser user, List books) { + + List rows = new ArrayList<>(); + InlineKeyboardRow navRow = new InlineKeyboardRow(); + int counter = 1; + for (Book book : books) { + navRow.add(InlineKeyboardButton.builder() + .text(book.getTitle()) + .callbackData("BOOK_EDIT_ID_" + book.getId()) + .build()); + if (counter % 5 == 0) { + rows.add(navRow); + navRow = new InlineKeyboardRow(); + } + counter++; + } + + if (!navRow.isEmpty()) { + rows.add(navRow); + } + + return new InlineKeyboardMarkup(rows); + } + + + public static InlineKeyboardMarkup getEditOptions(BotUser user) { + + List rows = new ArrayList<>(); + InlineKeyboardRow navRow = new InlineKeyboardRow(); + // Первый ряд кнопок + navRow.add( + InlineKeyboardButton.builder() + .text("Название ✏️") + .callbackData("BOOK_EDIT_TITLE") + .build() + ); + navRow.add( + InlineKeyboardButton.builder() + .text("Автор ✒️") + .callbackData("BOOK_EDIT_AUTHOR") + .build() + ); + + // Второй ряд кнопок + navRow.add( + InlineKeyboardButton.builder() + .text("Рейтинг ⭐️") + .callbackData("BOOK_EDIT_RATING") + .build() + ); + navRow.add( + InlineKeyboardButton.builder() + .text("Отмена ❌") + .callbackData("BOOK_EDIT_CANCEL") + .build() + ); + + rows.add(navRow); + + return new InlineKeyboardMarkup(rows); + } + + public String getWelcomeMessage() { + return "✨ *Добро пожаловать в BookBot!* 📚\n" + + "_Ваш персональный помощник для управления библиотекой_\n\n" + + "Чтобы начать, отправьте:\n" + + "👉 `/start` — активировать бота и открыть меню\n\n" + + "**С нами вы сможете:**\n" + + "🔸 Добавлять книги с рейтингом\n" + + "🔸 Просматривать свою коллекцию\n" + + "🔸 Редактировать записи\n" + + "🔸 Сортировать по рейтингу\n\n" + + "📌 *Не забывайте: всегда можно вернуться в главное меню командой* `/start`\n\n" + + "_📖 Давайте начнём ваше литературное путешествие!_"; + } +} \ No newline at end of file diff --git a/src/main/java/ru/cathub/telegabot/bot/TelegaBot.java b/src/main/java/ru/cathub/telegabot/bot/TelegaBot.java new file mode 100644 index 0000000..057fbd9 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/bot/TelegaBot.java @@ -0,0 +1,116 @@ +package ru.cathub.telegabot.bot; + +import jakarta.annotation.PostConstruct; +import lombok.Getter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.telegram.telegrambots.longpolling.util.TelegramOkHttpClientFactory; +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient; +import org.telegram.telegrambots.longpolling.BotSession; +import org.telegram.telegrambots.longpolling.interfaces.LongPollingUpdateConsumer; +import org.telegram.telegrambots.longpolling.starter.AfterBotRegistration; +import org.telegram.telegrambots.longpolling.starter.SpringLongPollingBot; +import org.telegram.telegrambots.longpolling.util.LongPollingSingleThreadUpdateConsumer; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.objects.File; +import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.api.objects.User; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; +import org.telegram.telegrambots.meta.generics.TelegramClient; +import ru.cathub.telegabot.exception.ServiceException; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.service.BookManageService; +import ru.cathub.telegabot.service.DataService; +import ru.cathub.telegabot.service.TelegramBotService; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; + +@Component +public class TelegaBot implements SpringLongPollingBot, LongPollingSingleThreadUpdateConsumer { + + // private final QwenService qwenService; +// private final MessageRepository messageRepository; + // private final DelugeService delugeService; + + // public TelegramBot(QwenService qwenService, MessageRepository messageRepository, DelugeService delugeService) { +// this.qwenService = qwenService; + // this.messageRepository = messageRepository; + // this.delugeService = delugeService; + // } + private final String botToken; + private final String botUsername; + private final OkHttpTelegramClient telegramClient; + private final TelegramBotService telegramBotService; + private final DataService dataService; + + public TelegaBot( + @Value("${bot.token}") String botToken, + @Value("${bot.name}") String botUsername, + TelegramBotService telegramBotService, DataService dataService + ) { + this.botToken = botToken; + this.botUsername = botUsername; + this.telegramClient = new OkHttpTelegramClient(botToken); + this.telegramBotService = telegramBotService; + this.dataService = dataService; + } + + + @Override + public String getBotToken() { + return botToken; + } + + @Override + public LongPollingUpdateConsumer getUpdatesConsumer() { + return this; + } + + @AfterBotRegistration + public void afterRegistration(BotSession botSession) { + System.out.println("Registered bot running state is: " + botSession.isRunning()); + } + + + @Override + public void consume(Update update) { + + BotUser user = null; + if (update.hasMessage()) { + user = dataService.saveUserIfNotExists(update.getMessage().getFrom(), update.getMessage().getChatId()); + } else { + user = dataService.saveUserIfNotExists(update.getCallbackQuery().getFrom(), null); + } + + if (update.hasCallbackQuery()) { + var callbackData = update.getCallbackQuery().getData(); + + telegramBotService.processQuery(user,callbackData); + } + + if (update.hasMessage() && update.getMessage().isCommand()) { + var command = update.getMessage().getText(); + telegramBotService.processCommand(user,command); + return; + } + + if (update.hasMessage()) { + String messageText = update.getMessage().getText(); + try { + telegramBotService.processInput(user,messageText); + } catch (ServiceException e) { + throw new RuntimeException(e); + } + } else if (update.hasMessage() && update.getMessage().hasDocument()) { + //TODO + ;//handleTorrentFile(update); + } + } +} diff --git a/src/main/java/ru/cathub/telegabot/configuration/CacheConfig.java b/src/main/java/ru/cathub/telegabot/configuration/CacheConfig.java new file mode 100644 index 0000000..c5e51bd --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/configuration/CacheConfig.java @@ -0,0 +1,26 @@ +package ru.cathub.telegabot.configuration; + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import org.springframework.cache.caffeine.CaffeineCacheManager; + +import java.util.concurrent.TimeUnit; + +@Configuration +@EnableCaching +public class CacheConfig { + + @Bean + public CacheManager cacheManager() { + CaffeineCacheManager cacheManager = new CaffeineCacheManager(); + cacheManager.setCaffeine(Caffeine.newBuilder() + .expireAfterWrite(30, TimeUnit.MINUTES) // Время жизни записи + .maximumSize(1000) // Максимальное количество элементов + .recordStats()); // Включение статистики + return cacheManager; + } +} diff --git a/src/main/java/ru/cathub/telegabot/configuration/HibernateConfig.java b/src/main/java/ru/cathub/telegabot/configuration/HibernateConfig.java new file mode 100644 index 0000000..206ee89 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/configuration/HibernateConfig.java @@ -0,0 +1,23 @@ +package ru.cathub.telegabot.configuration; + +import io.hypersistence.utils.hibernate.query.QueryStackTraceLogger; +import org.hibernate.cfg.AvailableSettings; +import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + +import java.util.Map; +// +//@Configuration +//public class HibernateConfig implements HibernatePropertiesCustomizer { +// +// @Override +// public void customize(Map hibernateProperties) { +// hibernateProperties.put( +// AvailableSettings.STATEMENT_INSPECTOR, +// new QueryStackTraceLogger( +// "ru.cathub.telegabot" +// ) +// ); +// } +//} diff --git a/src/main/java/ru/cathub/telegabot/configuration/TelegramConfig.java b/src/main/java/ru/cathub/telegabot/configuration/TelegramConfig.java new file mode 100644 index 0000000..5f45add --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/configuration/TelegramConfig.java @@ -0,0 +1,24 @@ +package ru.cathub.telegabot.configuration; + +import io.hypersistence.utils.hibernate.query.QueryStackTraceLogger; +import org.hibernate.cfg.AvailableSettings; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; +import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient; +import org.telegram.telegrambots.meta.generics.TelegramClient; + +import java.util.Map; + +@Configuration +public class TelegramConfig { + + @Bean + public TelegramClient telegramClient(@Value("${bot.token}") String token) { + return new OkHttpTelegramClient(token); + } + + +} diff --git a/src/main/java/ru/cathub/telegabot/exception/ServiceException.java b/src/main/java/ru/cathub/telegabot/exception/ServiceException.java new file mode 100644 index 0000000..5221e2e --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/exception/ServiceException.java @@ -0,0 +1,12 @@ +package ru.cathub.telegabot.exception; + +public class ServiceException extends Exception { + + public ServiceException(String message) { + super(message); + } + + public ServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/ru/cathub/telegabot/model/Book.java b/src/main/java/ru/cathub/telegabot/model/Book.java new file mode 100644 index 0000000..ba172d1 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/model/Book.java @@ -0,0 +1,24 @@ +package ru.cathub.telegabot.model; + +import jakarta.persistence.*; +import lombok.*; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "books") +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + private String author; + private Integer rating; + + @ManyToOne + @JoinColumn(name = "bot_user_id") + private BotUser botUser; +} \ No newline at end of file diff --git a/src/main/java/ru/cathub/telegabot/model/BookCreationCache.java b/src/main/java/ru/cathub/telegabot/model/BookCreationCache.java new file mode 100644 index 0000000..98d4774 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/model/BookCreationCache.java @@ -0,0 +1,14 @@ +package ru.cathub.telegabot.model; + +import lombok.Data; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Data +public class BookCreationCache { + + private String title; + private String author; + private Integer rating; +} diff --git a/src/main/java/ru/cathub/telegabot/model/BotMessage.java b/src/main/java/ru/cathub/telegabot/model/BotMessage.java new file mode 100644 index 0000000..78879c3 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/model/BotMessage.java @@ -0,0 +1,32 @@ +package ru.cathub.telegabot.model; +import jakarta.persistence.*; +import lombok.*; +import java.time.LocalDateTime; +@Entity +@Table(name = "messages") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BotMessage { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(columnDefinition = "TEXT") + private String content; + + @Enumerated(EnumType.STRING) + private MessageType type; + + private LocalDateTime createdAt; + + @ManyToOne + @JoinColumn(name = "botUser_id") + private BotUser botUser; + + public enum MessageType { + TEXT, FILE, COMMAND + } +} diff --git a/src/main/java/ru/cathub/telegabot/model/BotUser.java b/src/main/java/ru/cathub/telegabot/model/BotUser.java new file mode 100644 index 0000000..d3fe75e --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/model/BotUser.java @@ -0,0 +1,48 @@ +package ru.cathub.telegabot.model; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.CreationTimestamp; + +import java.time.LocalDateTime; +import java.util.List; + + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Entity +public class BotUser { + + public enum UserType { + USER, ADMIN } + + public enum WorkingMode { + BOOK,TORRENT,AI,NO_MODE + } + + @Id + private Long id; + + private Long chatId; + + @Enumerated(EnumType.STRING) + @Builder.Default + private UserType userType = UserType.USER; + + + @Enumerated(EnumType.STRING) + @Builder.Default + private WorkingMode workingMode = WorkingMode.NO_MODE; + + @CreationTimestamp + private LocalDateTime createdDateTime; + + @OneToMany(mappedBy = "botUser", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List botMessages; + + @OneToMany(mappedBy = "botUser", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List books; + +} diff --git a/src/main/java/ru/cathub/telegabot/repository/BookRepository.java b/src/main/java/ru/cathub/telegabot/repository/BookRepository.java new file mode 100644 index 0000000..d86bc76 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/repository/BookRepository.java @@ -0,0 +1,23 @@ +package ru.cathub.telegabot.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.cathub.telegabot.model.Book; +import ru.cathub.telegabot.model.BotUser; +import java.util.List; +import java.util.Optional; + +public interface BookRepository extends JpaRepository { + List findByBotUser(BotUser botUser); + + Page findByBotUser(BotUser botUser, Pageable pageable); + + @Query("SELECT b FROM Book b WHERE b.botUser = :user ORDER BY b.id DESC") + List findPaginatedByBotUser(@Param("user") BotUser user, Pageable pageable); + + Optional findByIdAndBotUser(Long bookId, BotUser user); +} \ No newline at end of file diff --git a/src/main/java/ru/cathub/telegabot/repository/MessageRepository.java b/src/main/java/ru/cathub/telegabot/repository/MessageRepository.java new file mode 100644 index 0000000..5c25efb --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/repository/MessageRepository.java @@ -0,0 +1,8 @@ +package ru.cathub.telegabot.repository; + + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.cathub.telegabot.model.BotMessage; + +public interface MessageRepository extends JpaRepository { +} diff --git a/src/main/java/ru/cathub/telegabot/repository/UserRepository.java b/src/main/java/ru/cathub/telegabot/repository/UserRepository.java new file mode 100644 index 0000000..7cc9308 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/repository/UserRepository.java @@ -0,0 +1,7 @@ +package ru.cathub.telegabot.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.cathub.telegabot.model.BotUser; + +public interface UserRepository extends JpaRepository { +} diff --git a/src/main/java/ru/cathub/telegabot/service/BookCacheService.java b/src/main/java/ru/cathub/telegabot/service/BookCacheService.java new file mode 100644 index 0000000..72b5687 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/BookCacheService.java @@ -0,0 +1,21 @@ +package ru.cathub.telegabot.service; + +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import ru.cathub.telegabot.model.BookCreationCache; + +import static ru.cathub.telegabot.utils.Constants.BOOK_CACHE_NAME; + + +public interface BookCacheService { + @Cacheable(value = BOOK_CACHE_NAME, key = "#userId") + BookCreationCache getCache(Long userId); + + @CachePut(value = BOOK_CACHE_NAME, key = "#userId") + BookCreationCache updateCache(Long userId, BookCreationCache cache); + + @CacheEvict(value = BOOK_CACHE_NAME, key = "#userId") + void clearCache(Long userId); +} diff --git a/src/main/java/ru/cathub/telegabot/service/BookManageService.java b/src/main/java/ru/cathub/telegabot/service/BookManageService.java new file mode 100644 index 0000000..9fdbbc3 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/BookManageService.java @@ -0,0 +1,15 @@ +package ru.cathub.telegabot.service; + +import org.telegram.telegrambots.meta.api.objects.message.Message; +import ru.cathub.telegabot.exception.ServiceException; +import ru.cathub.telegabot.model.BookCreationCache; +import ru.cathub.telegabot.model.BotUser; + +public interface BookManageService { + + void processBookInput(BotUser user, String text); + + void handleStartMessage(BotUser botUser) throws ServiceException; + + void processBookQuery(BotUser user, String text); +} diff --git a/src/main/java/ru/cathub/telegabot/service/DataService.java b/src/main/java/ru/cathub/telegabot/service/DataService.java new file mode 100644 index 0000000..9319aac --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/DataService.java @@ -0,0 +1,11 @@ +package ru.cathub.telegabot.service; + +import org.telegram.telegrambots.meta.api.objects.User; +import ru.cathub.telegabot.model.BotMessage; +import ru.cathub.telegabot.model.BotUser; + +public interface DataService { + public BotUser saveUserIfNotExists(User tgUser, Long chatId); + public BotMessage saveMessage(BotUser user, String content, BotMessage.MessageType type); + +} diff --git a/src/main/java/ru/cathub/telegabot/service/TelegramBotService.java b/src/main/java/ru/cathub/telegabot/service/TelegramBotService.java new file mode 100644 index 0000000..dd2fa25 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/TelegramBotService.java @@ -0,0 +1,12 @@ +package ru.cathub.telegabot.service; + +import ru.cathub.telegabot.exception.ServiceException; +import ru.cathub.telegabot.model.BotUser; + +public interface TelegramBotService { + void processInput(BotUser botUser, String text) throws ServiceException; + + void processCommand(BotUser botUser, String text); + + void processQuery(BotUser botUser, String callbackData); +} diff --git a/src/main/java/ru/cathub/telegabot/service/TelegramClientService.java b/src/main/java/ru/cathub/telegabot/service/TelegramClientService.java new file mode 100644 index 0000000..6ecdfb1 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/TelegramClientService.java @@ -0,0 +1,18 @@ +package ru.cathub.telegabot.service; + + +import org.telegram.telegrambots.meta.api.objects.message.Message; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; +import ru.cathub.telegabot.model.BotUser; + +public interface TelegramClientService { + + Message sendMessage(BotUser botUser, String text, ReplyKeyboard replyKeyboard); + + Message sendMessage(BotUser botUser, String text); + + Message sendMessageWithMarkdown(BotUser botUser, String text, InlineKeyboardMarkup bookListKeyboard); + + void editMessage(BotUser botUser, int messageId, String s); +} diff --git a/src/main/java/ru/cathub/telegabot/service/impl/BookCacheServiceImpl.java b/src/main/java/ru/cathub/telegabot/service/impl/BookCacheServiceImpl.java new file mode 100644 index 0000000..4c64ce6 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/impl/BookCacheServiceImpl.java @@ -0,0 +1,33 @@ +package ru.cathub.telegabot.service.impl; + +import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import ru.cathub.telegabot.model.BookCreationCache; +import ru.cathub.telegabot.service.BookCacheService; + +import static ru.cathub.telegabot.utils.Constants.BOOK_CACHE_NAME; + +@Service +@RequiredArgsConstructor +public class BookCacheServiceImpl implements BookCacheService { + + @Override + @Cacheable(value = BOOK_CACHE_NAME, key = "#userId") + public BookCreationCache getCache(Long userId) { + return null; // Автоматически вернет null, если нет в кэше + } + + @Override + @CachePut(value = BOOK_CACHE_NAME, key = "#userId") + public BookCreationCache updateCache(Long userId, BookCreationCache cache) { + return cache; + } + + @Override + @CacheEvict(value = BOOK_CACHE_NAME, key = "#userId") + public void clearCache(Long userId) { + } +} diff --git a/src/main/java/ru/cathub/telegabot/service/impl/BookManageServiceImpl.java b/src/main/java/ru/cathub/telegabot/service/impl/BookManageServiceImpl.java new file mode 100644 index 0000000..fc6f788 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/impl/BookManageServiceImpl.java @@ -0,0 +1,242 @@ +package ru.cathub.telegabot.service.impl; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import ru.cathub.telegabot.bot.KeyboardHelper; +import ru.cathub.telegabot.exception.ServiceException; +import ru.cathub.telegabot.model.Book; +import ru.cathub.telegabot.model.BookCreationCache; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.repository.BookRepository; +import ru.cathub.telegabot.repository.UserRepository; +import ru.cathub.telegabot.service.BookCacheService; +import ru.cathub.telegabot.service.BookManageService; +import ru.cathub.telegabot.service.TelegramClientService; + +import java.util.Optional; + +import static ru.cathub.telegabot.bot.KeyboardHelper.*; +import static ru.cathub.telegabot.utils.Constants.*; + + +@Service +@RequiredArgsConstructor +@Slf4j +public class BookManageServiceImpl implements BookManageService { + + private final TelegramClientService telegramClientService; + private final UserRepository userRepository; + private final BookCacheService bookCacheService; + private final BookRepository bookRepository; + + + @Override + public void processBookInput(BotUser user, String text) { + Long userId = user.getId(); + BookCreationCache cache = bookCacheService.getCache(userId); + + switch (text) { + case LIST_BOOKS: + showPaginatedBookList(user, 0,null); + break; + case EDIT_BOOKS: + startBookEditing(user); + break; + default: + if (cache == null) { + handleNewAddRequest(user, text); + } else { + handleExistingAddCache(user, cache, text); + } + } + } + + @Override + public void handleStartMessage(BotUser botUser) throws ServiceException { + botUser.setWorkingMode(BotUser.WorkingMode.BOOK); + userRepository.save(botUser); + telegramClientService.sendMessage(botUser, "Начало обработки книг", KeyboardHelper.getBookMenuKeyboard()); + } + + @Override + public void processBookQuery(BotUser user, String text) { + if (text.startsWith("BOOK_PAGE_")) { + int page = Integer.parseInt(text.split("_")[2]); + Integer messageId = Integer.parseInt(text.split("_")[3]); + showPaginatedBookList(user, page,messageId); + } else if (text.startsWith("BOOK_EDIT_ID_")) { + Long bookId = Long.parseLong(text.split("_")[3]); + processBookSelection(user, bookId); + } else { + switch (text) { + case "BOOK_EDIT_TITLE": + handleEditTitle(user); + break; + case "BOOK_EDIT_AUTHOR": + //handleEditAuthor(user); + break; + case "BOOK_EDIT_RATING": + //handleEditRating(user); + break; + case "BOOK_EDIT_CANCEL": + // cancelEditing(user); + break; + } + + } + } + + private void handleEditTitle(BotUser user) { + // user.setBookEditState(BookEditState.EDITING_TITLE); + telegramClientService.sendMessage(user, "Введите новое название:"); + } + + private void handleNewAddRequest(BotUser user, String text) { + if (ADD_BOOK.equals(text)) { + BookCreationCache newCache = new BookCreationCache(); + bookCacheService.updateCache(user.getId(), newCache); + telegramClientService.sendMessage(user, "Введите название книги:"); + } + } + + public void handleExistingAddCache(BotUser user, BookCreationCache cache, String text) { + if (cache.getTitle() == null) { + cache.setTitle(text); + bookCacheService.updateCache(user.getId(), cache); + telegramClientService.sendMessage(user, "Введите автора:"); + } else if (cache.getAuthor() == null) { + cache.setAuthor(text); + bookCacheService.updateCache(user.getId(), cache); + telegramClientService.sendMessage(user, "Введите рейтинг:"); + } else { + try { + int year = Integer.parseInt(text); + saveBook(user, cache, year); + bookCacheService.clearCache(user.getId()); + telegramClientService.sendMessage(user, "Книга сохранена!"); + handleStartMessage(user); + } catch (NumberFormatException e) { + telegramClientService.sendMessage(user, "Ошибка! Введите целов число"); + } catch (ServiceException e) { + throw new RuntimeException(e); + } + } + } + + private void saveBook(BotUser user, BookCreationCache cache, int rating) { + Book book = Book.builder() + .title(cache.getTitle()) + .rating(rating) + .author(cache.getAuthor()) + .botUser(user) + .build(); + bookRepository.save(book); + } + + private void showPaginatedBookList(BotUser botUser, int page, Integer messageId) { + try { + + Pageable pageable = PageRequest.of(page, 5); + Page books = bookRepository.findByBotUser(botUser,pageable); + + StringBuilder sb = new StringBuilder(); + + // Экранируем заголовок + sb.append("📚 *Ваша книжная полка*\n\n"); + + int counter = 1; + for (Book book : books) { + sb.append(formatBookEntry(book, (counter-1)%5)); + counter++; + } + telegramClientService.editMessage(botUser, messageId, escapeMarkdown(sb.toString())); + + telegramClientService.sendMessageWithMarkdown( + botUser, + escapeMarkdown(sb.toString()), + getBookListKeyboard(page, books.hasNext()) + ); + + } catch (Exception e) { + // 6. Обработка ошибок + log.error("Error loading book list", e); + telegramClientService.sendMessage(botUser, "❌ Ошибка при загрузке списка книг"); + } + } + + private String escapeMarkdown(String text) { + return text.replaceAll("([_*\\[\\]()~`>#+=|{}.!-])", "\\\\$1"); + } + + public void startBookEditing(BotUser user) { + // user.setBookEditState(BookEditState.SELECTING_BOOK); + userRepository.save(user); + telegramClientService.sendMessage(user, "Выберите книгу для редактирования:", + getBookEditListKeyboard(user, bookRepository.findByBotUser(user))); + } + + private void processBookSelection(BotUser user, Long bookId) { + try { + Optional book = bookRepository.findByIdAndBotUser(bookId, user); + + if (book.isPresent()) { + log.info("Found book with id {}", bookId); + + telegramClientService.sendMessage(user, "Выберите поле для редактирования:", getEditOptions(user)); + } else { + telegramClientService.sendMessage(user, "Книга не найдена"); + } + } catch (NumberFormatException e) { + telegramClientService.sendMessage(user, "Некорректный ID книги"); + } + } + + private static final String FULL_STAR = "⭐"; // Эмодзи U+2B50 + private static final String EMPTY_STAR = "☆"; // Символ U+2606 + + public static String formatRating(int rating) { + // Ограничиваем рейтинг в диапазоне 0-10 + int validatedRating = Math.min(10, Math.max(0, rating)); + + StringBuilder sb = new StringBuilder(); + + // Добавляем заполненные звезды + for (int i = 0; i < validatedRating; i++) { + sb.append(FULL_STAR); + } + + // Добавляем пустые звезды + for (int i = validatedRating; i < 10; i++) { + sb.append(EMPTY_STAR); + } + + // Добавляем текстовое представление + sb.append(" (").append(validatedRating).append("/10)"); + + return sb.toString(); + } + + private String getBookIcon(int index) { + String[] icons = {"📘", "📙", "📕", "📗", "📓"}; + return icons[index % icons.length]; + } + private String formatBookEntry(Book book, int index) { + return String.format( + "%s *%s*\n" + + "✍️ _%s_\n" + + "🏆 %s\n" + + // "\n" + + "▔▔▔▔▔▔▔▔▔▔▔▔▔▔\n", + getBookIcon(index), + escapeMarkdown(book.getTitle()), + escapeMarkdown(book.getAuthor()), + formatRating(book.getRating()) + ); + } + + +} diff --git a/src/main/java/ru/cathub/telegabot/service/impl/DataServiceImpl.java b/src/main/java/ru/cathub/telegabot/service/impl/DataServiceImpl.java new file mode 100644 index 0000000..c8ea54b --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/impl/DataServiceImpl.java @@ -0,0 +1,50 @@ +package ru.cathub.telegabot.service.impl; + + +import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.telegram.telegrambots.meta.api.objects.User; +import ru.cathub.telegabot.model.BotMessage; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.repository.MessageRepository; +import ru.cathub.telegabot.repository.UserRepository; +import ru.cathub.telegabot.service.DataService; + +import java.time.LocalDateTime; + +import static java.time.ZoneOffset.UTC; + +@Service +@RequiredArgsConstructor +public class DataServiceImpl implements DataService { + + private final UserRepository userRepository; + private final MessageRepository messageRepository; + + @Override + @Transactional + @Cacheable(value = "users", key = "#tgUser.id") + public BotUser saveUserIfNotExists(User tgUser, Long chatId) { + return userRepository.findById(tgUser.getId()) + .orElseGet(() -> { + BotUser newUser = BotUser.builder() + .id(tgUser.getId()) + .createdDateTime(LocalDateTime.now(UTC)) + .chatId(chatId) + .build(); + return userRepository.save(newUser); + }); + } + + @Transactional + public BotMessage saveMessage(BotUser user, String content, BotMessage.MessageType type) { + BotMessage message = BotMessage.builder() + .content(content) + .type(type) + .botUser(user) + .build(); + return messageRepository.save(message); + } +} diff --git a/src/main/java/ru/cathub/telegabot/service/impl/TelegramBotServiceImpl.java b/src/main/java/ru/cathub/telegabot/service/impl/TelegramBotServiceImpl.java new file mode 100644 index 0000000..ff8fce0 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/impl/TelegramBotServiceImpl.java @@ -0,0 +1,79 @@ +package ru.cathub.telegabot.service.impl; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import ru.cathub.telegabot.bot.KeyboardHelper; +import ru.cathub.telegabot.exception.ServiceException; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.repository.UserRepository; +import ru.cathub.telegabot.service.BookManageService; +import ru.cathub.telegabot.service.TelegramBotService; +import ru.cathub.telegabot.service.TelegramClientService; + +import static ru.cathub.telegabot.utils.Constants.*; + +@Service +@RequiredArgsConstructor +public class TelegramBotServiceImpl implements TelegramBotService { + + private final TelegramClientService telegramClientService; + private final BookManageService bookManageService; + private final UserRepository userRepository; + + @Override + public void processInput(BotUser botUser, String text) throws ServiceException { + switch (text) { +// case "Отправить текст ИИ": +// sendMessage(chatId, "Введите ваш текст:"); +// break; +// +// case "Загрузить .torrent": +// sendMessage(chatId, "Отправьте .torrent файл."); +// break; + + case "Книжник": + bookManageService.handleStartMessage(botUser); + break; + + case "Помощь": + telegramClientService.sendMessage(botUser, "Выберите действие из меню."); + break; + + case BACK: + processStart(botUser); + break; + case EDIT_BOOKS: + bookManageService.processBookInput(botUser,text); + break; + default: + switch (botUser.getWorkingMode()) { + case BOOK: + bookManageService.processBookInput(botUser,text); + break; + } + } + } + + @Override + public void processCommand(BotUser botUser, String text) { + switch (text) { + case START: + processStart(botUser); + break; + } + } + + public void processStart(BotUser botUser){ + telegramClientService.sendMessage(botUser, "Добро пожаловать! Выберите действие:", KeyboardHelper.getMainMenuKeyboard()); + botUser.setWorkingMode(BotUser.WorkingMode.NO_MODE); + userRepository.save(botUser); + } + + @Override + public void processQuery(BotUser botUser, String callbackData) + { + if (callbackData.startsWith("BOOK_")) { + bookManageService.processBookQuery(botUser,callbackData); + } + } +} diff --git a/src/main/java/ru/cathub/telegabot/service/impl/TelegramClientServiceImps.java b/src/main/java/ru/cathub/telegabot/service/impl/TelegramClientServiceImps.java new file mode 100644 index 0000000..7e95206 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/service/impl/TelegramClientServiceImps.java @@ -0,0 +1,75 @@ +package ru.cathub.telegabot.service.impl; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; +import org.telegram.telegrambots.meta.api.objects.message.Message; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; +import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; +import org.telegram.telegrambots.meta.generics.TelegramClient; +import ru.cathub.telegabot.model.BotUser; +import ru.cathub.telegabot.service.TelegramClientService; + +@Service +@RequiredArgsConstructor +@Slf4j +public class TelegramClientServiceImps implements TelegramClientService { + + private final TelegramClient telegramClient; + + @Override + public Message sendMessage(BotUser botUser, String text, ReplyKeyboard replyKeyboard) { + SendMessage message = SendMessage.builder() + .chatId(botUser.getChatId().toString()) + .text(text) + .replyMarkup(replyKeyboard) + .build(); + + try { + return telegramClient.execute(message); + } catch (TelegramApiException e) { + System.out.println("Ошибка отправки сообщения: {}" + e.getMessage()); + throw new RuntimeException(e); + } + } + + @Override + public Message sendMessage(BotUser botUser, String text) { + return sendMessage(botUser, text, null); + } + + @Override + public Message sendMessageWithMarkdown(BotUser botUser, String text, InlineKeyboardMarkup bookListKeyboard) { + SendMessage message = SendMessage.builder() + .chatId(botUser.getChatId().toString()) + .parseMode("MarkdownV2") + .replyMarkup(bookListKeyboard) + .text(text) + .build(); + + try { + return telegramClient.execute(message); + } catch (TelegramApiException e) { + //logger.error("Ошибка отправки сообщения", e); + throw new RuntimeException(e); + } + } + + @Override + public void editMessage(BotUser botUser, int messageId, String s) { + + try { + telegramClient.execute(EditMessageText.builder() + .chatId(botUser.getChatId().toString()) + .messageId(messageId) + .text(s) + .build()); + } catch (TelegramApiException e) { + log.error("Ошибка отправки сообщения", e); + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/ru/cathub/telegabot/utils/CacheUtils.java b/src/main/java/ru/cathub/telegabot/utils/CacheUtils.java new file mode 100644 index 0000000..dcacbf2 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/utils/CacheUtils.java @@ -0,0 +1,15 @@ +package ru.cathub.telegabot.utils; + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.springframework.cache.CacheManager; +import org.springframework.cache.caffeine.CaffeineCacheManager; +import org.springframework.context.annotation.Bean; +// +//public class CacheUtils { +// @Bean +// public CacheManager cacheManager(Caffeine caffeine) { +// CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(); +// caffeineCacheManager.setCaffeine(caffeine); +// return caffeineCacheManager; +// } +//} diff --git a/src/main/java/ru/cathub/telegabot/utils/Constants.java b/src/main/java/ru/cathub/telegabot/utils/Constants.java new file mode 100644 index 0000000..72e1e31 --- /dev/null +++ b/src/main/java/ru/cathub/telegabot/utils/Constants.java @@ -0,0 +1,12 @@ +package ru.cathub.telegabot.utils; + +public class Constants{ + public static final String START = "/start"; + + public static final String BOOK_CACHE_NAME = "bookCache"; + public static final String ADD_BOOK = "Добавить книгу"; + public static final String LIST_BOOKS = "Список книг"; + public static final String BACK = "Назад"; + public static final String EDIT_BOOKS = "Редактировать книги"; + +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..f14138c --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,28 @@ +spring.application.name=TelegaBot +bot.token=5908676914:AAGU9LVyXYZYafpRgwOf1tolk0HGYvcHszY +bot.name=TelegaBot + +cbr.currency.rates.xml.url=http://www.cbr.ru/scripts/XML_daily.asp + +spring.jpa.properties.jakarta.persistence.schema-generation.scripts.action=create +spring.jpa.properties.jakarta.persistence.schema-generation.scripts.create-target=create.sql +spring.jpa.properties.jakarta.persistence.schema-generation.scripts.create-source=metadata + +spring.datasource.url=jdbc:postgresql://192.168.0.10:5432/telegabot +spring.datasource.username=postgres +spring.datasource.password=Vftrixpo05 +spring.jpa.hibernate.ddl-auto=update +spring.jpa.generate-ddl=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect + +# ?????????? SQL-??????? +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=false + +# ?????????? ????????? ???????? +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +logging.level.io.hypersistence.utils.hibernate.query=DEBUG + +# ??????????? ???? +logging.level.org.springframework.cache=INFO \ No newline at end of file diff --git a/src/test/java/ru/cathub/telegabot/TelegaBotApplicationTests.java b/src/test/java/ru/cathub/telegabot/TelegaBotApplicationTests.java new file mode 100644 index 0000000..7476db1 --- /dev/null +++ b/src/test/java/ru/cathub/telegabot/TelegaBotApplicationTests.java @@ -0,0 +1,23 @@ +package ru.cathub.telegabot; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@SpringBootTest +@TestPropertySource(locations = "classpath:application.properties") // Указываем файл свойств +class TelegramBotApplicationTests { + + @Value("${bot.token}") // Инъекция значения из application.properties + private String botToken; + + @Test + void testBotTokenIsLoaded() { + // Проверяем, что значение не пустое + assertNotNull(botToken, "Bot token should not be null"); + System.out.println("Bot Token: " + botToken); // Для отладки + } +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..e98454c --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,12 @@ +spring.application.name=TelegaBot +bot.token=aaa +bot.name=TelegaBot +spring.boot.enable-auto-configuration-report=false +cbr.currency.rates.xml.url=http://www.cbr.ru/scripts/XML_daily.asp + +spring.datasource.url=jdbc:postgresql://192.168.0.10:5432/telegabot +spring.datasource.username=postgres +spring.datasource.password=Vftrixpo05 +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect