Compare commits

...

170 Commits

Author SHA1 Message Date
763e08e96e
added BoxAnswerPayload.THREAD_ID
All checks were successful
continuous-integration/drone/push Build is passing
2024-09-04 00:19:07 +03:00
e64396522b
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-24 18:46:02 +03:00
19b1ff10b9
[maven-release-plugin] prepare release v.1.5.2
All checks were successful
continuous-integration/drone/tag Build is passing
2024-06-24 18:46:01 +03:00
d1fcedba6d
Добавлен Quarkus Bom
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-24 18:45:11 +03:00
fc3ce8a81b
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-24 18:07:18 +03:00
08fb3e215d
[maven-release-plugin] prepare release v.1.5.1
All checks were successful
continuous-integration/drone/tag Build is passing
2024-06-24 18:07:18 +03:00
891a19024d
Добавил в ButtonClickAttachment messageId
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-24 18:06:26 +03:00
24173d7e55
[maven-release-plugin] prepare for next development iteration
Some checks failed
continuous-integration/drone/push Build is failing
2024-06-24 16:56:56 +03:00
19bc531141
[maven-release-plugin] prepare release v.1.5.0
All checks were successful
continuous-integration/drone/tag Build is passing
2024-06-24 16:56:56 +03:00
9e345b2ed1
fixed cicd
All checks were successful
continuous-integration/drone/push Build is passing
2024-06-24 16:51:33 +03:00
4911456cbb
[maven-release-plugin] prepare for next development iteration
Some checks failed
continuous-integration/drone/push Build is failing
2024-06-24 16:41:44 +03:00
5ccf4f5288
[maven-release-plugin] prepare release v.1.5.0
Some checks failed
continuous-integration/drone/tag Build is failing
2024-06-24 16:41:44 +03:00
2d79362e67
Обновлены версии библиотек. Обновление с API телеги: теперь при нажатии кнопки телеграм не всегда присылает сообщение с этой кнопкой. Если сообщение старое, то самое сообщение может быть не отправлено.
Some checks failed
continuous-integration/drone/push Build is failing
2024-06-24 16:40:48 +03:00
04e5d3435b
Добавил новый UnitTrigger
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-03 17:42:58 +03:00
872c5f4886
disable docs site
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-02 22:24:57 +03:00
84c2fc8815
disable docs site 2023-12-02 22:24:50 +03:00
227e38077b
[maven-release-plugin] prepare for next development iteration
Some checks failed
continuous-integration/drone/push Build is failing
2023-12-02 22:22:04 +03:00
ce64657c23
[maven-release-plugin] prepare release v.1.4.1 2023-12-02 22:22:03 +03:00
fe272ff9c6
fix cicd
Some checks failed
continuous-integration/drone/push Build is failing
2023-12-02 22:12:24 +03:00
4eb9ad7a3d
fix cicd
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-12-02 22:11:20 +03:00
c5a2aca433
fix cicd
Some checks are pending
continuous-integration/drone/push Build is pending
2023-12-02 22:10:35 +03:00
647b87522a
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-12-02 19:27:20 +03:00
1d272d0d70
[maven-release-plugin] prepare release v.1.4.0 2023-12-02 19:27:20 +03:00
de25a6033b
Добавил в ButtonClickAttachment информацию о сообщении
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-12-02 10:46:23 +03:00
d6f28d53a8
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 21:35:43 +03:00
6ca2a0dfca
[maven-release-plugin] prepare release v.1.3.0 2023-11-27 21:35:43 +03:00
d3a18e8baa
<godfather.core.ver>1.2.0</godfather.core.ver>
Some checks reported errors
continuous-integration/drone/push Build was killed
2023-11-27 21:35:03 +03:00
8d0f174127
Добавил обработку replayMail
Some checks reported errors
continuous-integration/drone/push Build was killed
2023-11-27 21:34:28 +03:00
72bbd768f8
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 15:49:58 +03:00
a4fa53f0d4
[maven-release-plugin] prepare release v.1.2.2 2023-11-27 15:49:58 +03:00
35556762f0
Поправил обработку изображений
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 15:49:14 +03:00
3eeb78b42a
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 15:39:08 +03:00
2c3847adaf
[maven-release-plugin] prepare release v.1.2.1 2023-11-27 15:39:08 +03:00
1d49b09c54
Поправил обработку стикеров. И улучшил генерацию названий для файлов.
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 15:37:06 +03:00
1975bee405
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-27 14:22:41 +03:00
033a440303
[maven-release-plugin] prepare release v.1.2.0 2023-11-27 14:22:40 +03:00
c8bb581599
Улучшил работу с файлами 2023-11-27 14:21:50 +03:00
02f037c292
SubscribeConvert UnsubscribeConvert update
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-25 12:18:26 +03:00
f45281fa9a
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-24 21:32:31 +03:00
a8b0d93586
[maven-release-plugin] prepare release v.1.1.0 2023-11-24 21:32:31 +03:00
71a574eff7
plugin update version [skip ci] 2023-11-24 21:31:53 +03:00
c7673e0520
<godfather.core.ver>1.1.0</godfather.core.ver> [skip ci] 2023-11-24 21:27:55 +03:00
139bd06692
Добавил новые типы вложений: стикеры и голосовые. Также добавил новый тип события: отредактированное сообщение
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-24 21:18:35 +03:00
842c36086e
Обновление версии telegram 2023-11-24 21:15:09 +03:00
ab9cd53816
[maven-release-plugin] prepare for next development iteration
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-18 21:03:43 +03:00
44dc556166
[maven-release-plugin] prepare release v.1.0.0 2023-11-18 21:03:43 +03:00
1ecdba5349
<godfather.core.ver>1.0.0</godfather.core.ver>
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-18 21:02:37 +03:00
78a072ed90
Добавил обработку подписи к изображениям
Some checks reported errors
continuous-integration/drone/push Build encountered an error
2023-11-18 18:06:21 +03:00
58fc497894
Merge branch 'bugfix/answer-save' into develop
Some checks failed
continuous-integration/drone/push Build is failing
# Conflicts:
#	pom.xml
#	telegram-consumer/pom.xml
#	telegram-consumer/telegram-consumer-main/pom.xml
#	telegram-consumer/telegram-consumer-quarkus/pom.xml
#	telegram-consumer/telegram-consumer-simple/pom.xml
#	telegram-context/pom.xml
#	telegram-context/telegram-context-main/pom.xml
#	telegram-context/telegram-context-quarkus/pom.xml
#	telegram-context/telegram-context-simple/pom.xml
#	telegram-core/pom.xml
#	telegram-core/telegram-core-main/pom.xml
#	telegram-core/telegram-core-quarkus/pom.xml
#	telegram-core/telegram-core-simple/pom.xml
#	telegram-domain/pom.xml
#	telegram-domain/telegram-domain-main/pom.xml
#	telegram-domain/telegram-domain-quarkus/pom.xml
#	telegram-domain/telegram-domain-simple/pom.xml
#	telegram-sender/pom.xml
#	telegram-sender/telegram-sender-main/pom.xml
#	telegram-sender/telegram-sender-quarkus/pom.xml
#	telegram-sender/telegram-sender-simple/pom.xml
#	telegram-simple/pom.xml
#	telegram-webhook/pom.xml
#	telegram-webhook/telegram-webhook-quarkus/pom.xml
2023-05-24 06:06:45 +03:00
b99bc9a104
[maven-release-plugin] prepare for next development iteration 2023-05-24 06:05:06 +03:00
47e294c7e7
[maven-release-plugin] prepare release v.0.0.72 2023-05-24 06:05:06 +03:00
c8a8d5ef3a
pre release 2023-05-24 06:04:37 +03:00
7134b691ff
Merge branch 'bugfix/answer-save' into develop
# Conflicts:
#	pom.xml
#	telegram-consumer/pom.xml
#	telegram-consumer/telegram-consumer-main/pom.xml
#	telegram-consumer/telegram-consumer-quarkus/pom.xml
#	telegram-consumer/telegram-consumer-simple/pom.xml
#	telegram-context/pom.xml
#	telegram-context/telegram-context-main/pom.xml
#	telegram-context/telegram-context-quarkus/pom.xml
#	telegram-context/telegram-context-simple/pom.xml
#	telegram-core/pom.xml
#	telegram-core/telegram-core-main/pom.xml
#	telegram-core/telegram-core-quarkus/pom.xml
#	telegram-core/telegram-core-simple/pom.xml
#	telegram-domain/pom.xml
#	telegram-domain/telegram-domain-main/pom.xml
#	telegram-domain/telegram-domain-quarkus/pom.xml
#	telegram-domain/telegram-domain-simple/pom.xml
#	telegram-sender/pom.xml
#	telegram-sender/telegram-sender-main/pom.xml
#	telegram-sender/telegram-sender-quarkus/pom.xml
#	telegram-sender/telegram-sender-simple/pom.xml
#	telegram-simple/pom.xml
#	telegram-webhook/pom.xml
#	telegram-webhook/telegram-webhook-quarkus/pom.xml
2023-05-23 16:45:44 +03:00
72966f398e
[maven-release-plugin] prepare for next development iteration 2023-05-23 16:42:04 +03:00
86fc3ceb1d
[maven-release-plugin] prepare release v.0.0.71 2023-05-23 16:42:04 +03:00
5ae9d1e1bc
pre release 2023-05-23 16:41:32 +03:00
aad321cbe6
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-18 01:26:31 +03:00
5d5968767a
[maven-release-plugin] prepare release v.0.0.70 2023-05-18 01:26:30 +03:00
80602fa8de
pre release 2023-05-18 01:26:01 +03:00
f7c6a9099b
Добавил моментальный ответ в WebhookController
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-17 18:49:24 +03:00
796519cb1f
[maven-release-plugin] prepare for next development iteration
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-14 01:52:16 +03:00
c0e2190ca7
[maven-release-plugin] prepare release v.0.0.69 2023-05-14 01:52:15 +03:00
ad20c7c440
prerelease 2023-05-14 01:51:45 +03:00
697c0c038d
Объединил UnitTrigger 2023-05-14 01:51:20 +03:00
abf27f1bec
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-10 00:40:14 +03:00
fac961be44
[maven-release-plugin] prepare release v.0.0.68 2023-05-10 00:40:13 +03:00
6936e252f4
Добавил возможность отвечать на сообщения 2023-05-10 00:39:17 +03:00
e00f683226
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-10 00:14:56 +03:00
80e8cfffe1
[maven-release-plugin] prepare release v.0.0.67 2023-05-10 00:14:56 +03:00
23e01a3145
При разбивке большого сообщения на несколько добавил клавиатуру в последнее сообщение 2023-05-10 00:14:27 +03:00
824a95a305
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-08 11:43:37 +03:00
ff6730aa6c
[maven-release-plugin] prepare release v.0.0.66 2023-05-08 11:43:37 +03:00
ca234e619c
Переработал обработку исключений при отрпавке 2023-05-08 11:43:03 +03:00
dd4133f22b
[maven-release-plugin] prepare for next development iteration 2023-05-03 18:43:27 +03:00
2201c2f3c8
[maven-release-plugin] prepare release v.0.0.65
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-03 18:43:26 +03:00
a8d1c7b67c
Изменил обработку CallbackQueryConvert
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-03 18:42:43 +03:00
332ba4f0f1
Изменил обработку вебхуков 2023-05-03 18:18:35 +03:00
e2dd95e489
[maven-release-plugin] prepare for next development iteration 2023-05-03 01:23:40 +03:00
b3f5eea491
[maven-release-plugin] prepare release v.0.0.64
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-03 01:23:40 +03:00
3319ce794b
pre-release 2023-05-03 01:23:11 +03:00
dc0b990ad0
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-28 01:55:55 +03:00
bd5056fc20
[maven-release-plugin] prepare release v.0.0.63
Some checks failed
continuous-integration/drone/push Build is failing
2023-04-28 01:55:55 +03:00
0b346d8b4e
пререлиз 2023-04-28 01:55:19 +03:00
ed2f31f9f1
Логирование
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-26 22:09:46 +03:00
9b43ba9a4f
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-26 20:25:41 +03:00
ceffe1fb80
[maven-release-plugin] prepare release v.0.0.62
Some checks failed
continuous-integration/drone/push Build is failing
2023-04-26 20:25:41 +03:00
0ea693f54a
pre-release 2023-04-26 20:24:46 +03:00
0c5ef4b3bf
Добавил jandex плагин
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-26 16:05:10 +03:00
d18895ec3e
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-24 11:44:17 +03:00
2e2b5a46f6
[maven-release-plugin] prepare release v.0.0.61 2023-04-24 11:44:17 +03:00
4264b3bf64
Подготовка к релизу 2023-04-24 11:43:50 +03:00
083a679bbd
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-24 10:02:36 +03:00
a734cce73b
[maven-release-plugin] prepare release v.0.0.60 2023-04-24 10:02:36 +03:00
9d831c3d14
Подготовка к релизу 2023-04-24 10:01:33 +03:00
79f99ae7c1
Отправка файлов
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-24 03:03:26 +03:00
c7595ff2e4
Поправил EventDistributorService
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-24 01:50:45 +03:00
945079d6e1
Поправил логирование
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-23 13:41:34 +03:00
ba140017cb
Поправил MailAutoresponderTelegram
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-23 05:03:07 +03:00
059b360d03
Поправил MailAutoresponderTelegram
Some checks failed
continuous-integration/drone/push Build is failing
2023-04-23 03:21:43 +03:00
266aa852e2
Добавил поддержку получения и отправки видео
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-22 17:23:06 +03:00
455a8e1316
Вернул обработка вебхуков
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-19 10:22:48 +03:00
36a5d1b478
Поправил поведение WebhookController
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-17 01:04:14 +03:00
a18dceb617
Заменил executorservice телеги на mutiny
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-15 12:57:46 +03:00
ae6ffab2a8
Добавил поддержку html
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-11 10:25:09 +03:00
27f21ce24a
Добавил исключения при отправке сообщений
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-10 10:12:21 +03:00
124368fcc8
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-09 18:17:05 +03:00
c6470be521
[maven-release-plugin] prepare release v.0.0.59 2023-04-09 18:17:05 +03:00
46c0b16271
pre release 2023-04-09 18:16:38 +03:00
f561786d58
Добавил метод в UnitTrigger
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-09 11:24:12 +03:00
955d7b4841
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-07 10:12:25 +03:00
ffda4fa659
[maven-release-plugin] prepare release v.0.0.58 2023-04-07 10:12:25 +03:00
779ec0bbe9
Исправил баг в ButtonClickAttachment 2023-04-07 10:11:58 +03:00
6ed4a8d273
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-07 09:31:18 +03:00
4e5a547af4
[maven-release-plugin] prepare release v.0.0.57 2023-04-07 09:31:18 +03:00
2f7f84cdf2
Исправил баг в SimpleButton 2023-04-07 09:30:52 +03:00
9d39f4d1aa
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-06 20:24:34 +03:00
546503c17a
[maven-release-plugin] prepare release v.0.0.56 2023-04-06 20:24:33 +03:00
70b06f0964
перенес реализации клавиатур 2023-04-06 20:24:05 +03:00
369edb829c
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-03 13:58:50 +03:00
be16f741b7
[maven-release-plugin] prepare release v.0.0.55 2023-04-03 13:58:50 +03:00
3a3c9cc285
godfather 0.0.56 2023-04-03 13:58:19 +03:00
cff4f3eed8
Поправил пробелму в MarkupKeyBoard
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-02 21:31:24 +03:00
476a97001c
Удалил лишний метод в отправке
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-02 14:39:12 +03:00
6414f92904
Добавил Vertex для LongPolling
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-02 12:58:20 +03:00
e960c273a0
Поправил заполнение SentBox при replace
All checks were successful
continuous-integration/drone/push Build is passing
2023-04-01 21:46:15 +03:00
ee2024d37f
Добавляю логирование 2023-03-30 22:32:53 +03:00
f916f7aa09
Добавил файлы для отправки
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-30 19:42:22 +03:00
2713cd8246
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-29 01:21:19 +03:00
bcfa12d7f7
[maven-release-plugin] prepare release v.0.0.54 2023-03-29 01:21:19 +03:00
183cc4a203
godfather 0.0.55 2023-03-29 01:20:27 +03:00
19c75c4c49
Доработка клавиатур 2023-03-29 01:20:00 +03:00
317fd066c9
Исправления в TelegramSender
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-27 20:43:24 +03:00
efe3e042e2
Разделение большого сообщения на несколько сообщений
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-26 22:08:32 +03:00
40fd76590f
Переработка получения событий от телеграма для поддержки микросервисной архитектуры
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-26 17:42:44 +03:00
b657d588bb
Доработка
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-24 01:26:11 +03:00
bef5f42eb4
Добавил возможность проверки подписки на канал/группу
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-22 04:16:35 +03:00
fd7c53060a
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-20 17:12:15 +03:00
44efe13ece
[maven-release-plugin] prepare release v.0.0.53 2023-03-20 17:12:15 +03:00
0cec0e651b
godfather ver 0.0.54 2023-03-20 17:11:45 +03:00
6f45154878
Упростил кнопки 2023-03-19 21:54:27 +03:00
77f2c67540
Доработка вебхуков
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 19:28:11 +03:00
c1febc78e9
Доработка вебхуков
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 19:08:41 +03:00
2f3d7b9b10
Добавил логирование вебхуков
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 18:21:48 +03:00
c2d9b5db78
Добавил логирование инициализации вебхука
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 17:49:22 +03:00
be8d9a3c82
Настройка вебхука
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 16:34:53 +03:00
8f8b524b0e
UniTrigger
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-19 10:29:03 +03:00
9c2f04c483
EventDistributorService получил событие для обработки InlineQuery. Поправил SubscribeConvert
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-18 14:01:24 +03:00
0e575cc09f
Рефакторинг EventDistributorService
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-18 11:08:02 +03:00
90c54f0d76
Бета версия вебхука и бета версия оплаты
Some checks failed
continuous-integration/drone/push Build is failing
2023-03-17 03:16:18 +03:00
2d240152fa
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-16 00:48:01 +03:00
9a6d44a959
[maven-release-plugin] prepare release v.0.0.52 2023-03-16 00:48:01 +03:00
ccf9001099
Подготовка к релизу 2023-03-16 00:47:33 +03:00
767e4182bb
Пишу документацию
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-15 20:07:48 +03:00
245254628a
Рефакторинг 2023-03-15 20:07:30 +03:00
c379904d26
Пишу документацию
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-15 02:19:09 +03:00
06729e031d
Пишу документацию
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-14 02:11:04 +03:00
f01acf5d85
Настройка сайта документации 2023-03-13 23:01:25 +03:00
c334f159c9
Настройка сайта документации
Some checks reported errors
continuous-integration/drone/push Build was killed
continuous-integration/drone Build is passing
2023-03-13 22:56:49 +03:00
5f883ca6da
Настройка сайта документации
Some checks failed
continuous-integration/drone/push Build is failing
2023-03-13 22:55:49 +03:00
08e9f8a8ab
Рефакторинг документации 2023-03-13 22:45:23 +03:00
ba7f6df62e
Рефакторинг документации
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-13 19:19:13 +03:00
2ad2f64dfb
Рефакторинг документации 2023-03-13 19:18:55 +03:00
cb9ae97cef
Рефакторинг документации
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-13 19:07:24 +03:00
71ff043a9a
Рефакторинг документации
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone Build is passing
2023-03-13 18:49:49 +03:00
ff4db62d9c
Рефакторинг документации
Some checks failed
continuous-integration/drone/push Build is failing
2023-03-13 18:48:04 +03:00
666cf965ed
Рефакторинг документации
Some checks reported errors
continuous-integration/drone/push Build was killed
2023-03-13 18:45:36 +03:00
0508604290
Рефакторинг документации
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone Build is failing
2023-03-13 18:33:50 +03:00
50feffd2c7
[maven-release-plugin] prepare for next development iteration
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-05 18:59:21 +03:00
0985765fbd
[maven-release-plugin] prepare release v.0.0.51 2023-03-05 18:59:21 +03:00
4d41a2375d
Добавил возможность задавать команды в бота
All checks were successful
continuous-integration/drone/push Build is passing
2023-03-05 18:10:41 +03:00
144 changed files with 3635 additions and 1388 deletions

View File

@ -13,9 +13,8 @@ volumes:
path: /drone/volume/m2
steps:
- name: publish
image: maven:3.8.5-openjdk-17
image: hub.docker.struchkov.dev/maven:3.9.5-eclipse-temurin-17-alpine
privileged: true
volumes:
- name: m2
@ -27,6 +26,8 @@ steps:
- echo "$MAVEN_SETTINGS" >> maven-settings.xml
- mvn --settings maven-settings.xml -U -P snapshot clean deploy
image_pull_secrets:
- DOCKER_AUTH
---
kind: pipeline
type: docker
@ -42,9 +43,8 @@ volumes:
path: /drone/volume/m2
steps:
- name: publish maven central
image: maven:3.8.5-openjdk-17
image: hub.docker.struchkov.dev/maven:3.9.5-eclipse-temurin-17-alpine
privileged: true
volumes:
- name: m2
@ -57,11 +57,14 @@ steps:
GPG_PASSPHRASE:
from_secret: GPG_PASSPHRASE
commands:
- apk add --no-cache gnupg
- echo "$GPG_PRIVATE_KEY" >> gpg.key
- echo "$MAVEN_SETTINGS" >> maven-settings.xml
- gpg --pinentry-mode loopback --passphrase $GPG_PASSPHRASE --import gpg.key
- mvn --settings maven-settings.xml -U -P ossrh,release clean deploy
image_pull_secrets:
- DOCKER_AUTH
---
kind: pipeline
type: docker
@ -77,9 +80,8 @@ volumes:
path: /drone/volume/m2
steps:
- name: publish struchkov nexus
image: maven:3.8.5-openjdk-17
image: hub.docker.struchkov.dev/maven:3.9.5-eclipse-temurin-17-alpine
privileged: true
volumes:
- name: m2
@ -92,50 +94,62 @@ steps:
GPG_PASSPHRASE:
from_secret: GPG_PASSPHRASE
commands:
- apk add --no-cache gnupg
- echo "$GPG_PRIVATE_KEY" >> gpg.key
- echo "$MAVEN_SETTINGS" >> maven-settings.xml
- gpg --pinentry-mode loopback --passphrase $GPG_PASSPHRASE --import gpg.key
- mvn --settings maven-settings.xml -U -P ossrh,release-struchkov-nexus clean deploy
image_pull_secrets:
- DOCKER_AUTH
#---
#kind: pipeline
#type: docker
#name: create-docs-site
#name: create-develop-docs-site
#
#trigger:
# branch:
# - develop
# - docs
# - master
#
#clone:
# disable: true
#
#steps:
# - name: build site
# image: upagge/mkdocs-material
#
# - name: build docs
# image: private.docker.struchkov.dev/mkdocs:latest
# volumes:
# - name: mkdocs_cache
# path: ${DRONE_WORKSPACE}/documentation/ru/.cache
# environment:
# SSH_DEPLOY_KEY:
# from_secret: SSH_DEPLOY_KEY
# SSH_DEPLOY_HOST:
# from_secret: SSH_DEPLOY_HOST
# SSH_DEPLOY_PORT:
# from_secret: SSH_DEPLOY_PORT
# SSH_DEPLOY_PATH:
# from_secret: SSH_DEPLOY_PATH
# SSH_DEPLOY_USER:
# from_secret: SSH_DEPLOY_USER
# GIT_SSH:
# from_secret: GIT_SSH
# GIT_SSH_COMMAND: "ssh -i ~/.ssh/id_rsa -p 222"
# commands:
# - eval $(ssh-agent -s)
# - mkdir -p ~/.ssh
# - echo "$SSH_DEPLOY_KEY" >> ~/.ssh/id_rsa
# - chmod 700 ~/.ssh
# - echo "$GIT_SSH" >> ~/.ssh/id_rsa
# - chmod 600 ~/.ssh/id_rsa
# - ssh-keyscan -p $SSH_DEPLOY_PORT $SSH_DEPLOY_HOST >> ~/.ssh/known_hosts
# - ssh-keyscan -p 222 git.struchkov.dev >> ~/.ssh/known_hosts
# - chmod 644 ~/.ssh/known_hosts
# - cd documentation
# - mkdocs build
# - mv site godfather-telegram
# - scp -r -P $SSH_DEPLOY_PORT ./godfather-telegram $SSH_DEPLOY_USER@$SSH_DEPLOY_HOST:$SSH_DEPLOY_PATH
# - git config --global user.name "${DRONE_COMMIT_AUTHOR_NAME}"
# - git config --global user.email "${DRONE_COMMIT_AUTHOR_EMAIL}"
# - git clone ${DRONE_GIT_SSH_URL} .
# - git checkout $DRONE_COMMIT
# - cd documentation/spring/ru
# - mike deploy --prefix godfather-telegram/spring/ru --branch docs-deploy --push --update-aliases develop
#
#image_pull_secrets:
# - DOCKER_AUTH
#
#volumes:
# - name: mkdocs_cache
# host:
# path: /drone/volume/mkdocs_cache/godfather_telegram/spring/ru
---
kind: signature
hmac: bdeec02d3273fc1640c972d68cc52bffa2319ea53470d0c273f42125a1dec127
hmac: 888a81f78d73d24d45c080c5c9250ed58888e8217c7d67d27af9baa5ce861a82
...

3
.gitignore vendored
View File

@ -77,4 +77,5 @@ com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
/documentation/site/
/documentation/spring/ru/site/
/documentation/spring/ru/.cache/

View File

@ -1,10 +0,0 @@
# Hello Mutiny!
Once you made Mutiny available to your classpath, you can start writing code.
Let's start with this simple program:
## Test
### Test 2
## Test 3

View File

@ -1,122 +0,0 @@
---
hide:
- toc
---
# Варианты добавления в проект
Есть несколько вариантов добавить фреймворк в проект. Изучите их все и выберете подходящий под ваши задачи.
## Spring Boot Starter
Самый простой способ, если у вас небольшой монолитный Spring Boot проект.
=== ":simple-apachemaven: Maven"
```xml
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot-spring-boot-starter</artifactId>
<version>0.0.50-SNAPSHOT</version>
</dependency>
```
=== ":simple-gradle: Gradle"
``` c++
#include <iostream>
int main(void) {
std::cout << "Hello world!" << std::endl;
return 0;
}
```
## Quarkus Extension
На данный момент раздел находится в разработке.
=== ":simple-apachemaven: Maven"
```
```
=== ":simple-gradle: Gradle"
```
```
### Reactive
На данный момент раздел находится в разработке.
## Основные зависимости проекта
Вы можете добавить основные зависимости в свой проект и сконфигурировать его более тонко под ваши нужды. Однако для этого потребуется хорошее знание архитектуры проекта.
Этот вариант подойдет вам, если у вас используется микросервисная архитектура. Так как логично разделить стадии получения, обработки и отправки сообщений на разные сервисы.
Также этот вариант подойдет вам, если вы используете менее популярный фреймворк, так как основные зависимости написаны без привязки к какому-то конкретному фреймворку.
Всего основных зависимостей три:
=== ":simple-spring: Spring"
Эти зависимости подойдут вам, если вы используете SpringBoot 3.0.0+
=== ":simple-apachemaven: Maven"
``` xml title="Позволяет получать сообщения"
```
``` xml title="Содержит всю логику работы"
```
``` xml title="Позволяет отправлять сообщения"
```
=== ":simple-gradle: Gradle"
``` xml title="Позволяет получать сообщения"
```
``` xml title="Содержит всю логику работы"
```
``` xml title="Позволяет отправлять сообщения"
```
=== ":simple-quarkus: Quarkus"
Эти зависимости подойдут вам, если вы используете Quarkus 2.16.0+
=== ":simple-apachemaven: Maven"
``` xml title="Позволяет получать сообщения"
```
``` xml title="Содержит всю логику работы"
```
``` xml title="Позволяет отправлять сообщения"
```
=== ":simple-gradle: Gradle"
``` xml title="Позволяет получать сообщения"
```
``` xml title="Содержит всю логику работы"
```
``` xml title="Позволяет отправлять сообщения"
```

View File

@ -1,10 +0,0 @@
# Hello Mutiny!
Once you made Mutiny available to your classpath, you can start writing code.
Let's start with this simple program:
## Test
### Test 2
## Test 3

View File

@ -1,9 +0,0 @@
---
hide:
- navigation
- comments
title: Home
---
# Godfather Telegram Фреймворк для создания Telegram ботов

View File

@ -1,95 +0,0 @@
site_name: GodFather Telegram
site_url: https://docs.struchkov.dev/godfather-telegram/
repo_url: https://github.com/Godfather-Bots/telegram-bot
repo_name: Godfather-Bots/telegram-bot
copyright: Copyright &copy; 2018 - 2023 Struchkov Mark
#edit_uri: edit/master/documentation/docs
nav:
- 'index.md'
- 'Быстрый старт':
- 'getting-started/installing-dependencies.md'
- 'getting-started/configuration.md'
# - 'Гайды':
- 'Архитектура':
- 'architecture/concept.md'
# - 'ChangeLog':
theme:
name: material
custom_dir: overrides
language: ru
favicon: assets/favicon.ico
icon:
logo: simple/telegram
repo: fontawesome/brands/github
palette:
- scheme: default
primary: light blue
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
- scheme: slate
toggle:
icon: material/brightness-4
name: Switch to light mode
features:
- navigation.instant
- navigation.indexes
- navigation.sections
- navigation.tracking
- navigation.tabs
- navigation.tabs.sticky
- navigation.footer
- search
- search.suggest
- search.highlight
- content.action.edit
- content.code.copy
- toc.follow
plugins:
- social
- meta
- tags
- search:
lang: ru
- git-revision-date-localized:
enable_creation_date: true
markdown_extensions:
- toc:
permalink: true
toc_depth: 3
title: Содержание
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.snippets
- pymdownx.inlinehilite
- pymdownx.details
- pymdownx.smartsymbols
- pymdownx.betterem
- pymdownx.tabbed:
alternate_style: true
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
extra:
generator: false
analytics:
provider: custom
property: foobar
version:
provider: mike
# alternate:
# - name: Русский
# link: /ru/
# lang: ru

View File

@ -0,0 +1,17 @@
=== ":simple-apachemaven: Maven"
``` xml
<!-- https://mvnrepository.com/artifact/dev.struchkov.godfather.telegram/telegram-bot-spring-boot-starter -->
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot-spring-boot-starter</artifactId>
<version>0.0.51</version>
</dependency>
```
=== ":simple-gradle: Gradle"
``` groovy
// https://mvnrepository.com/artifact/dev.struchkov.godfather.telegram/telegram-bot-spring-boot-starter
implementation 'dev.struchkov.godfather.telegram:telegram-bot-spring-boot-starter:0.0.51'
```

View File

@ -0,0 +1,59 @@
# Основная идея
Проект GodFather направлен на унификацию создания ботов для различных мессенджеров сетей.
## Юнит
Базовая сущность фреймворка. Юнит содержит в себе различные лямба выражения, которые встраиваются в процесс обработки сообщений. Именно в написании этих лямбд и заключается основная работа с библиотекой.
Есть несколько разных типов юнитов, подробнее о каждом читайте в отдельном разделе.
Юнит представляет собой некую конфигурацию, которая передается в обработчик юнита. У каждого типа юнита есть свой обработчик.
Юниты могут образовывать связный список, тем самым определяя дерево сценарий бота.
## Сценарий
Для понимания рассмотрим небольшой пример по схеме изображенной ниже. Так же небольшие примеры обработки есть в тестах.
![Типичный сценарий](img/scenario.png){ loading=lazy align=left }
Сценариями в данном случае являются:
* Unit1 —> Unit2 —> Unit5 —> Unit7 —> Unit9
* Unit1 —> Unit2 —> Unit6 —> Unit8;
* Unit1 —> Unit3 —> Unit6 —> Unit8;
* Unit1 —> Unit4 —> Unit9;
* Unit10.
Пользователь присылает боту свое первое сообщение, например, «Привет». Если сообщение удовлетворяет регулярному выражению или содержит необходимое количество ключевых слов Unit1, то возвращается Unit1, то же самое относится к Unit10.
Если оба юнита удовлетворяют запросу пользователя, то будет возвращен юнит с большим приоритетом (поле priority). Если приоритеты равны, то случайный Unit.
В нашем примере, на первое сообщение, пользователь получил Unit1, поэтому следующее сообщение пользователя будет ассоциироваться с множеством: Unit2, Unit3 и Unit4.
## Механизм выбора юнита
Пока сценарий линейный никакой необходимости в определении юнита нет. Однако, когда у вас на одном уровне находится несколько юнитов, то возникает необходимость выбрать юнит для последующей обработки сообщений. (1)
{ .annotate }
1. Обратимся к предыдущей схеме сценария. Как выбрать какой юнит обработать после обработки Unit 1?
Юниты обладают триггерами, которые сигнализируют о том, что данный юнит может обработать запрос от пользователя.
Механизм выбора можно описать несколькими этапами:
* Сначала проверяются триггеры у всех юнитов.
* Все юниты, триггеры которых сработали, являются потенциальными кандидатами на обработку
* Из этих юнитов выбирается юнит с наибольшим приоритетом. Если у них одинаковый приоритет, то выбирается случайный юнит.
Но как выбираются первые юниты (1) для обработки? В начале сценария стоят main юниты. Именно main юниты участвуют в первом раунде выбора обработчика. Чтобы создать main юнит, необходимо в аннотации `@Unit` установить параметр `main = true`.
{ .annotate }
1. На схеме это Unit 1 и Unit 2
Также существуют так называемые глобальные юниты, которые участвуют в каждом раунде выбора. Чтобы создать глобальный unit, необходимо в аннотации `@Unit` установить параметр `global = true`.

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

View File

@ -0,0 +1,16 @@
# Устройство юнитов
## Приоритет
## Триггеры
Позволяют указать при каком условии данный юнит будет выбран для обработки.
### `triggerCheck()`
Позволяет реализовать любую проверку. Принимает на вход `Predicate` с полученным сообщением.
### `triggerPhrase()`
## Ответ

View File

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,3 @@
# Change.Log
## 1.0.0

View File

@ -0,0 +1,65 @@
# Hello GodFather
Начнем разработку бота с простого примера. Поздороваемся с пользователем.
## Регистрация бота
Сначала нужно зарегистрировать бота и получить токен в Telegram.
[:robot: Зарегистрировать бота](@BotFather){ .md-button }
## Зависимости
--8<-- ".dependencies.md"
## Конфигурация
Теперь необходимо указать данные для подключения к боту в Telegram.
``` yaml title="application.yml"
telegram:
bot:
username: username_bot
token: your_token
```
### Прокси
Если телеграм заблокирован у вашего хостера/провайдера, вы можете использовать прокси
``` yaml title="application.yml" hl_lines="5-11"
telegram:
bot:
username: username_bot
token: your_token
proxy:
enable: true
host: PROXY_HOST
port: PROXY_PORT
type: PROXY_TYPE
user: PROXY_USERNAME
password: PROXY_PASSWORD
```
## Первый юнит
Теперь создаем класс конфигурации юнитов и добавляем первый юнит (1).
{ .annotate }
1. Юниты это базовая сущность фреймворка
``` java
@Component
public class GeneralMenu implements UnitConfiguration {
@Unit(value = GENERAL_MENU, main = true)
public AnswerText<Mail> generalMenu() {
return AnswerText.<Mail>builder()
.answer(boxAnswer("Hello!"))
.build();
}
}
```
Вот и все, можете запустить ваше приложение и написать боту в телеграм. Если вы все сделали правильно, то он ответит вам.

View File

@ -0,0 +1,2 @@
# Безопасность

View File

@ -0,0 +1,36 @@
---
hide:
- comments
- navigation
---
# GodFather Bot - Фреймворк для создания Telegram ботов
Данный фреймворк обладает мощным API для создания диалоговых Telegram ботов.
!!! note ""
Данный фреймворк имеет версии как для SpringBoot :simple-spring:, так и для Quarkus Reactive :simple-quarkus:.
Посмотрите, как легко сделать Hello World:
``` java
@Component
public class GeneralMenu implements UnitConfiguration {
@Unit(value = GENERAL_MENU, main = true)
public AnswerText<Mail> generalMenu() {
return AnswerText.<Mail>builder()
.answer(boxAnswer("Hello, World!"))
.build();
}
}
```
## Добавляем зависимости
Чтобы начать, выберете свой сборщик вкладку и добавьте зависимости в проект.
--8<-- ".dependencies.md"

View File

@ -0,0 +1,77 @@
.md-typeset .admonition, .md-typeset details {
font-size: 0.75rem;
}
.md-typeset h1, .md-typeset h2 {
font-weight: 500;
}
.md-typeset h2 {
margin-top: 4rem;
}
.md-typeset h3 {
margin-top: 2.2rem;
}
.md-typeset mark {
background-color: #fff3bc;
margin: -4px -4px -6px;
padding: 4px 4px 6px;
}
@keyframes heart {
0%, 40%, 80%, 100% {
transform: scale(1);
}
20%, 60% {
transform: scale(1.15);
}
}
.heart {
animation: heart 1000ms infinite;
}
@keyframes ninja-disappear {
0% {
opacity: 1;
}
50% {
opacity: 0.3;
}
100% {
opacity: 1;
}
}
.ninja-disappear {
animation: ninja-disappear 3000ms infinite;
animation-delay: 1500ms;
}
@keyframes jingle-bell-swing {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(10deg);
}
100% {
transform: rotate(0deg);
}
}
.jingle-bell {
animation: jingle-bell-swing 2s ease-in-out infinite;
transform-origin: center;
}
@media(min-width: 768px) {
.frontpage-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
column-gap: 2em;
row-gap: 1em;
}
}

View File

@ -0,0 +1,26 @@
---
description: Спонсорская поддержка делает проект устойчивым, так как она окупает время сопровождающих этого проекта.
hide:
- comments
- navigation
---
# :heart:{ .heart } Поддержать разработку
Спонсорская поддержка делает проект устойчивым, так как она окупает время сопровождающих этого проекта - очень дефицитный ресурс, который тратится на разработку новых функций, исправление ошибок, повышение стабильности, решение проблем и общую поддержку. ==Самое большое узкое место в Open Source - это время.==
***
Вы можете выбрать любой удобный способ поддержки разработки:
- Банковская карта: [https://www.tinkoff.ru/cf/4iU6NB3uzqx](https://www.tinkoff.ru/cf/4iU6NB3uzqx)
- Крипта:
* BTC (Taproot): `bc1pt49vnp43c4mktk6309zlq3020dzd0p89gc8d90zzn4sgjvck56xs0t86vy`
* ETH: `0x7668C802Bd71Be965671D4Bbb1AD90C7f7f32921`
* USDT (ERC-20): `0x7668C802Bd71Be965671D4Bbb1AD90C7f7f32921`
* DAI (ERC-20): `0x7668C802Bd71Be965671D4Bbb1AD90C7f7f32921`
* BNB: `0xDa41aC95f606850f2E01ba775e521Cd385AA7D03`
* USD: `0xDa41aC95f606850f2E01ba775e521Cd385AA7D03`
* DAI: `0xDa41aC95f606850f2E01ba775e521Cd385AA7D03`

View File

@ -0,0 +1,137 @@
site_name: GodFather Telegram
site_url: https://docs.struchkov.dev/godfather-telegram/spring/ru
repo_url: https://github.com/Godfather-Bots/telegram-bot
repo_name: Godfather-Bots/telegram-bot
copyright: Copyright &copy; 2018 - 2023 Struchkov Mark
#edit_uri: edit/master/documentation/docs
nav:
- О проекте:
- index.md
- Конфигурация:
- Hello World!: getting-started/hello-godfather.md
- Юниты:
- architecture/unit.md
- architecture/unit/answer-text.md
- architecture/unit/answer-check.md
- Гайды:
- Безопасность: guides/security.md
- Циклическая зависимость: guides/cyclic.md
- Обработка ошибок: guides/event-handler.md
- Обработка событий: guides/event-handler.md
- Архитектура:
- Основная идея: architecture/general.md
- ChangeLog: changelog/index.md
- Поддержать: support-development.md
theme:
name: material
custom_dir: overrides
language: ru
favicon: assets/favicon.ico
icon:
logo: simple/telegram
repo: fontawesome/brands/github
palette:
- media: "(prefers-color-scheme)"
primary: light blue
accent: indigo
scheme: default
toggle:
icon: material/brightness-auto
name: Switch to light mode
- media: "(prefers-color-scheme: light)"
primary: light blue
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
toggle:
icon: material/brightness-4
name: Switch to system preference
features:
- navigation.instant
- navigation.indexes
- navigation.sections
- navigation.tracking
- navigation.footer
- navigation.tabs
- navigation.tabs.sticky
- navigation.prune
- search
- search.suggest
- search.highlight
- content.action.edit
- content.code.copy
- content.code.annotate
- content.tooltips
- toc.follow
- toc.integrate
plugins:
- social
- typeset
# - blog:
# blog_toc: true
# post_date_format: short
# post_url_format: "{slug}"
# archive_toc: true
# categories: false
# authors: false
# - optimize:
# optimize_jpg_quality: 90
- tags
- search:
lang: ru
markdown_extensions:
- pymdownx.details
- pymdownx.superfences
- pymdownx.inlinehilite
- pymdownx.snippets:
auto_append:
- includes/abbreviations.md
- pymdownx.critic
- pymdownx.caret
- pymdownx.keys
- pymdownx.mark
- pymdownx.tilde
- attr_list
- def_list
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.tabbed:
alternate_style: true
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
- admonition
- abbr
- md_in_html
- footnotes
- toc:
toc_depth: 3
title: Содержание
permalink: ⚓︎
extra_css:
- stylesheets/extra.css
extra:
generator: false
analytics:
provider: custom
property: foobar
version:
provider: mike
# alternate:
# - name: Русский
# link: /ru/
# lang: ru

53
pom.xml
View File

@ -4,7 +4,7 @@
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
@ -14,6 +14,7 @@
<module>telegram-consumer</module>
<module>telegram-context</module>
<module>telegram-simple</module>
<module>telegram-webhook</module>
</modules>
<name>Telegram Bot</name>
@ -37,29 +38,38 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<godfather.core.ver>0.0.52</godfather.core.ver>
<godfather.core.ver>1.3.1</godfather.core.ver>
<quarkus.platform.version>3.8.4</quarkus.platform.version>
<!-- https://mvnrepository.com/artifact/org.telegram/telegrambots -->
<telegrambots.ver>6.3.0</telegrambots.ver>
<telegrambots.ver>6.9.7.1</telegrambots.ver>
<haiti.version>2.6.0</haiti.version>
<haiti.version>3.0.3</haiti.version>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin.maven.compiler.ver>3.10.1</plugin.maven.compiler.ver>
<plugin.maven.compiler.ver>3.13.0</plugin.maven.compiler.ver>
<!-- https://mvnrepository.com/artifact/org.sonatype.plugins/nexus-staging-maven-plugin -->
<plugin.nexus.staging.ver>1.6.13</plugin.nexus.staging.ver>
<plugin.nexus.staging.ver>1.7.0</plugin.nexus.staging.ver>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-source-plugin -->
<plugin.maven.source.ver>3.2.1</plugin.maven.source.ver>
<plugin.maven.source.ver>3.3.1</plugin.maven.source.ver>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-javadoc-plugin -->
<plugin.maven.javadoc.ver>3.5.0</plugin.maven.javadoc.ver>
<plugin.maven.javadoc.ver>3.7.0</plugin.maven.javadoc.ver>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-gpg-plugin -->
<plugin.maven.gpg.ver>3.0.1</plugin.maven.gpg.ver>
<plugin.maven.gpg.ver>3.2.4</plugin.maven.gpg.ver>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-release-plugin -->
<plugin.maven.release.ver>3.0.0-M7</plugin.maven.release.ver>
<plugin.maven.release.ver>3.1.0</plugin.maven.release.ver>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus.platform</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain-main</artifactId>
@ -245,9 +255,32 @@
<artifactId>telegrambotsextensions</artifactId>
<version>${telegrambots.ver}</version>
</dependency>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-web-api</artifactId>
<version>10.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.26</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>

View File

@ -4,7 +4,7 @@
<parent>
<artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-consumer</artifactId>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-consumer-main</artifactId>

View File

@ -1,28 +0,0 @@
package dev.struchkov.godfather.telegram.main.consumer;
import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import java.time.LocalDateTime;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class SubscribeConvert {
private SubscribeConvert() {
utilityClass();
}
public static Subscribe apply(ChatMemberUpdated updated) {
final Chat chat = updated.getChat();
final Subscribe subscribe = new Subscribe();
subscribe.setTelegramId(chat.getId().toString());
subscribe.setLastName(chat.getLastName());
subscribe.setFirstName(chat.getFirstName());
subscribe.setSubscriptionDate(LocalDateTime.now());
return subscribe;
}
}

View File

@ -1,28 +0,0 @@
package dev.struchkov.godfather.telegram.main.consumer;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import java.time.LocalDateTime;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class UnsubscribeConvert {
private UnsubscribeConvert() {
utilityClass();
}
public static Unsubscribe apply(ChatMemberUpdated updated) {
final Chat chat = updated.getChat();
final Unsubscribe unsubscribe = new Unsubscribe();
unsubscribe.setTelegramId(chat.getId().toString());
unsubscribe.setLastName(chat.getLastName());
unsubscribe.setFirstName(chat.getFirstName());
unsubscribe.setSubscriptionDate(LocalDateTime.now());
return unsubscribe;
}
}

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-consumer-quarkus</artifactId>

View File

@ -1,16 +1,17 @@
package dev.struchkov.godfather.telegram.quarkus.consumer;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.main.domain.content.EditedMail;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.quarkus.context.service.EventHandler;
import dev.struchkov.godfather.quarkus.context.service.EventDispatching;
import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert;
import dev.struchkov.godfather.telegram.main.consumer.MessageMailConvert;
import dev.struchkov.godfather.telegram.main.consumer.SubscribeConvert;
import dev.struchkov.godfather.telegram.main.consumer.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.main.context.convert.CallbackQueryConvert;
import dev.struchkov.godfather.telegram.main.context.convert.MessageMailConvert;
import dev.struchkov.godfather.telegram.main.context.convert.SubscribeConvert;
import dev.struchkov.godfather.telegram.main.context.convert.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.core.TelegramConnectBot;
import io.smallrye.mutiny.Multi;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.smallrye.mutiny.Uni;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
@ -18,13 +19,11 @@ import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/**
* TODO: Добавить описание класса.
@ -33,11 +32,11 @@ import static dev.struchkov.haiti.utils.Checker.checkNotNull;
*/
public class EventDistributorService implements EventDistributor {
private final Map<String, List<EventHandler>> eventHandlerMap;
private final EventDispatching eventDispatching;
public EventDistributorService(TelegramConnectBot telegramConnectBot, List<EventHandler> eventProviders) {
this.eventHandlerMap = eventProviders.stream().collect(Collectors.groupingBy(EventHandler::getEventType));
telegramConnectBot.initEventDistributor(this);
public EventDistributorService(TelegramConnect telegramConnect, EventDispatching eventDispatching) {
this.eventDispatching = eventDispatching;
telegramConnect.initEventDistributor(this);
}
@Override
@ -46,56 +45,49 @@ public class EventDistributorService implements EventDistributor {
.onItem().transformToUni(
v -> {
final Message message = update.getMessage();
final Message editedMessage = update.getEditedMessage();
final CallbackQuery callbackQuery = update.getCallbackQuery();
if (checkNotNull(message)) {
if (!isEvent(message)) {
final Optional<List<EventHandler>> optHandlers = getHandler(Mail.TYPE);
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(MessageMailConvert.apply(message))
).concatenate().toUni().replaceWithVoid();
}
return Uni.createFrom().voidItem();
}
final PreCheckoutQuery preCheckoutQuery = update.getPreCheckoutQuery();
final InlineQuery inlineQuery = update.getInlineQuery();
final ChosenInlineQuery chosenInlineQuery = update.getChosenInlineQuery();
// запросы к боту из чатов: https://core.telegram.org/bots/inline
if (update.hasInlineQuery()) {
return Uni.createFrom().item(new EventContainer<>(InlineQuery.class, inlineQuery));
}
if (checkNotNull(callbackQuery)) {
final Optional<List<EventHandler>> optHandlers = getHandler(Mail.TYPE);
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(CallbackQueryConvert.apply(callbackQuery))
).concatenate().toUni().replaceWithVoid();
}
return Uni.createFrom().voidItem();
if (update.hasChosenInlineQuery()) {
return Uni.createFrom().item(new EventContainer<>(ChosenInlineQuery.class, chosenInlineQuery));
}
if (checkNotNull(update.getMyChatMember())) {
if (update.hasPreCheckoutQuery()) {
return Uni.createFrom().item(new EventContainer<>(PreCheckoutQuery.class, preCheckoutQuery));
}
if (update.hasMessage()) {
return Uni.createFrom().item(new EventContainer<>(Mail.class, MessageMailConvert.apply(message)));
}
if (update.hasEditedMessage()) {
return Uni.createFrom().item(new EventContainer<>(EditedMail.class, MessageMailConvert.applyEdited(editedMessage)));
}
if (update.hasCallbackQuery()) {
return Uni.createFrom().item(new EventContainer<>(Mail.class, CallbackQueryConvert.apply(callbackQuery)));
}
if (update.hasMyChatMember()) {
final ChatMemberUpdated chatMember = update.getMyChatMember();
if ("kicked".equals(chatMember.getNewChatMember().getStatus())) {
final Optional<List<EventHandler>> optHandlers = getHandler(Unsubscribe.TYPE);
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(UnsubscribeConvert.apply(chatMember))
).concatenate().toUni().replaceWithVoid();
}
return Uni.createFrom().voidItem();
return Uni.createFrom().item(new EventContainer<>(Unsubscribe.class, UnsubscribeConvert.apply(chatMember)));
}
if ("member".equals(chatMember.getNewChatMember().getStatus())) {
final Optional<List<EventHandler>> optHandlers = getHandler(Subscribe.TYPE);
if (optHandlers.isPresent()) {
return Multi.createFrom().iterable(optHandlers.get())
.onItem().transformToUni(
eventHandler -> eventHandler.handle(SubscribeConvert.apply(chatMember))
).concatenate().toUni().replaceWithVoid();
}
return Uni.createFrom().voidItem();
return Uni.createFrom().item(new EventContainer<>(Subscribe.class, SubscribeConvert.apply(chatMember)));
}
}
return Uni.createFrom().voidItem();
return Uni.createFrom().nullItem();
}
);
).onItem().ifNotNull().transformToUni(eventDispatching::dispatch);
}
private boolean isEvent(Message message) {
@ -119,8 +111,4 @@ public class EventDistributorService implements EventDistributor {
}
}
private Optional<List<EventHandler>> getHandler(String type) {
return Optional.ofNullable(eventHandlerMap.get(type));
}
}

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-consumer</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-consumer-simple</artifactId>

View File

@ -1,26 +1,33 @@
package dev.struchkov.godfather.telegram.simple.consumer;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.main.domain.content.ChatMail;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.simple.context.service.EventHandler;
import dev.struchkov.godfather.simple.context.service.EventDispatching;
import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import dev.struchkov.godfather.telegram.main.consumer.CallbackQueryConvert;
import dev.struchkov.godfather.telegram.main.consumer.MessageMailConvert;
import dev.struchkov.godfather.telegram.main.consumer.SubscribeConvert;
import dev.struchkov.godfather.telegram.main.consumer.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.main.context.convert.CallbackQueryConvert;
import dev.struchkov.godfather.telegram.main.context.convert.MessageChatMailConvert;
import dev.struchkov.godfather.telegram.main.context.convert.MessageMailConvert;
import dev.struchkov.godfather.telegram.main.context.convert.SubscribeConvert;
import dev.struchkov.godfather.telegram.main.context.convert.UnsubscribeConvert;
import dev.struchkov.godfather.telegram.simple.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.simple.core.TelegramConnectBot;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.MaybeInaccessibleMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.inlinequery.ChosenInlineQuery;
import org.telegram.telegrambots.meta.api.objects.inlinequery.InlineQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotBlank;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/**
* TODO: Добавить описание класса.
@ -29,40 +36,78 @@ import java.util.stream.Collectors;
*/
public class EventDistributorService implements EventDistributor {
private final Map<String, List<EventHandler>> eventProviderMap;
private final EventDispatching eventDispatching;
public EventDistributorService(TelegramConnectBot telegramConnectBot, List<EventHandler> eventProviders) {
this.eventProviderMap = eventProviders.stream().collect(Collectors.groupingBy(EventHandler::getEventType));
telegramConnectBot.initEventDistributor(this);
public EventDistributorService(TelegramConnect telegramConnect, EventDispatching eventDispatching) {
this.eventDispatching = eventDispatching;
telegramConnect.initEventDistributor(this);
}
@Override
public void processing(@NotNull Update update) {
final Message message = update.getMessage();
final CallbackQuery callbackQuery = update.getCallbackQuery();
if (message != null) {
if (!isEvent(message)) {
getHandler(Mail.TYPE).ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(MessageMailConvert.apply(message))));
return;
}
}
if (callbackQuery != null) {
getHandler(Mail.TYPE).ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(CallbackQueryConvert.apply(callbackQuery))));
final PreCheckoutQuery preCheckoutQuery = update.getPreCheckoutQuery();
final InlineQuery inlineQuery = update.getInlineQuery();
if (update.hasInlineQuery()) {
eventDispatching.dispatch(new EventContainer<>(InlineQuery.class, inlineQuery));
return;
}
if (update.getMyChatMember() != null) {
if (update.hasChosenInlineQuery()) {
eventDispatching.dispatch(new EventContainer<>(ChosenInlineQuery.class, update.getChosenInlineQuery()));
}
if (update.hasPreCheckoutQuery()) {
eventDispatching.dispatch(new EventContainer<>(PreCheckoutQuery.class, preCheckoutQuery));
return;
}
if (update.hasMessage()) {
processionMessage(message);
return;
}
if (update.hasCallbackQuery()) {
processionCallback(callbackQuery);
return;
}
if (update.hasMyChatMember()) {
final ChatMemberUpdated chatMember = update.getMyChatMember();
if ("kicked".equals(chatMember.getNewChatMember().getStatus())) {
getHandler(Unsubscribe.TYPE).ifPresent(providers -> providers.forEach(provider -> provider.handle(UnsubscribeConvert.apply(chatMember))));
final Unsubscribe unsubscribe = UnsubscribeConvert.apply(chatMember);
eventDispatching.dispatch(new EventContainer<>(Unsubscribe.class, unsubscribe));
return;
}
if ("member".equals(chatMember.getNewChatMember().getStatus())) {
getHandler(Subscribe.TYPE).ifPresent(eventProviders -> eventProviders.forEach(eventProvider -> eventProvider.handle(SubscribeConvert.apply(chatMember))));
final Subscribe subscribe = SubscribeConvert.apply(chatMember);
eventDispatching.dispatch(new EventContainer<>(Subscribe.class, subscribe));
return;
}
}
}
private void processionCallback(CallbackQuery callbackQuery) {
final MaybeInaccessibleMessage maybeInaccessibleMessage = callbackQuery.getMessage();
if (checkNotBlank(callbackQuery.getInlineMessageId())) {
return;
}
if (checkNotNull(maybeInaccessibleMessage) && maybeInaccessibleMessage.isUserMessage()) {
final Mail mail = CallbackQueryConvert.apply(callbackQuery);
eventDispatching.dispatch(new EventContainer<>(Mail.class, mail));
}
}
private void processionMessage(Message message) {
if (message.isUserMessage()) {
final Mail mail = MessageMailConvert.apply(message);
eventDispatching.dispatch(new EventContainer<>(Mail.class, mail));
} else {
final ChatMail chatMail = MessageChatMailConvert.apply(message);
eventDispatching.dispatch(new EventContainer<>(ChatMail.class, chatMail));
}
}
private boolean isEvent(Message message) {
return message.getChannelChatCreated() != null
|| message.getDeleteChatPhoto() != null
@ -84,8 +129,4 @@ public class EventDistributorService implements EventDistributor {
}
}
private Optional<List<EventHandler>> getHandler(String type) {
return Optional.ofNullable(eventProviderMap.get(type));
}
}

View File

@ -4,7 +4,7 @@
<parent>
<artifactId>telegram-bot</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-context</artifactId>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-context-main</artifactId>
@ -22,7 +22,7 @@
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context-simple</artifactId>
<artifactId>bot-context-main</artifactId>
</dependency>
<dependency>

View File

@ -2,11 +2,16 @@ package dev.struchkov.godfather.telegram.main.context;
import dev.struchkov.haiti.utils.Exceptions;
import dev.struchkov.haiti.utils.container.ContextKey;
import org.telegram.telegrambots.meta.api.methods.invoices.SendInvoice;
public final class BoxAnswerPayload {
public static final ContextKey<Boolean> DISABLE_WEB_PAGE_PREVIEW = ContextKey.of("DISABLE_WEB_PAGE_PREVIEW", Boolean.class);
public static final ContextKey<Boolean> DISABLE_NOTIFICATION = ContextKey.of("DISABLE_NOTIFICATION", Boolean.class);
public static final ContextKey<Boolean> ENABLE_MARKDOWN = ContextKey.of("ENABLE_MARKDOWN", Boolean.class);
public static final ContextKey<Boolean> ENABLE_HTML = ContextKey.of("ENABLE_HTML", Boolean.class);
public static final ContextKey<SendInvoice> INVOICE = ContextKey.of("INVOICE", SendInvoice.class);
public static final ContextKey<Integer> THREAD_ID = ContextKey.of("THREAD_ID", Integer.class);
private BoxAnswerPayload() {
Exceptions.utilityClass();

View File

@ -1,8 +1,10 @@
package dev.struchkov.godfather.telegram.main.consumer;
package dev.struchkov.godfather.telegram.main.context.convert;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.MaybeInaccessibleMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.User;
import java.time.LocalDateTime;
@ -18,13 +20,15 @@ public class CallbackQueryConvert {
final String callbackData = callbackQuery.getData();
final Mail mail = new Mail();
mail.setId(callbackQuery.getMessage().getMessageId().toString());
final MaybeInaccessibleMessage maybeInaccessibleMessage = callbackQuery.getMessage();
mail.setId(maybeInaccessibleMessage.getMessageId().toString());
mail.setCreateDate(LocalDateTime.now());
mail.setText(callbackData);
mail.addAttachment(convertToButtonClick(callbackData, callbackQuery.getMessage().getMessageId()));
mail.addAttachment(convertToButtonClick(callbackData, maybeInaccessibleMessage));
final Long chatId = callbackQuery.getMessage().getChatId();
mail.setPersonId(chatId != null ? chatId.toString() : null);
final Long chatId = callbackQuery.getFrom().getId();
mail.setFromPersonId(chatId.toString());
final User user = callbackQuery.getFrom();
mail.setFirstName(user.getFirstName());
@ -32,10 +36,14 @@ public class CallbackQueryConvert {
return mail;
}
private static ButtonClickAttachment convertToButtonClick(String callbackData, Integer messageId) {
private static ButtonClickAttachment convertToButtonClick(String callbackData, MaybeInaccessibleMessage maybeInaccessibleMessage) {
final ButtonClickAttachment buttonClickAttachment = new ButtonClickAttachment();
buttonClickAttachment.setRawCallBackData(callbackData);
buttonClickAttachment.setMessageId(messageId.toString());
buttonClickAttachment.setMessageId(maybeInaccessibleMessage.getMessageId().toString());
if (maybeInaccessibleMessage instanceof Message message) {
buttonClickAttachment.setMaybeInaccessibleMessage(MessageMailConvert.apply(message));
}
if (callbackData.charAt(0) == '[' && callbackData.charAt(callbackData.length() - 1) == ']') {
final String[] args = callbackData.substring(1, callbackData.length() - 1).split(";");
for (String arg : args) {

View File

@ -1,22 +1,24 @@
package dev.struchkov.godfather.telegram.main.consumer;
package dev.struchkov.godfather.telegram.main.context.convert;
import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.main.domain.content.ChatMail;
import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.ContactAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.LinkAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.attachment.PictureGroupAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.VideoAttachment;
import dev.struchkov.godfather.telegram.main.context.MailPayload;
import dev.struchkov.haiti.utils.Checker;
import dev.struchkov.haiti.utils.Strings;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.Contact;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.PhotoSize;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.Video;
import java.time.Instant;
import java.time.LocalDateTime;
@ -32,28 +34,31 @@ import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
*
* @author upagge [18.08.2019]
*/
public final class MessageMailConvert {
public final class MessageChatMailConvert {
private MessageMailConvert() {
private MessageChatMailConvert() {
utilityClass();
}
public static Mail apply(Message message) {
final Mail mail = new Mail();
public static ChatMail apply(Message message) {
final ChatMail mail = new ChatMail();
final Long chatId = message.getChatId();
mail.setId(message.getMessageId().toString());
mail.setPersonId(chatId != null ? chatId.toString() : null);
mail.setChatId(chatId.toString());
mail.setText(message.getText());
mail.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), ZoneId.systemDefault()));
final Chat chat = message.getChat();
mail.setFirstName(chat.getFirstName());
mail.setLastName(chat.getLastName());
mail.setPayload(MailPayload.USERNAME, chat.getUserName());
final User fromUser = message.getFrom();
mail.setFirstName(fromUser.getFirstName());
mail.setLastName(fromUser.getLastName());
mail.addPayload(MailPayload.USERNAME, fromUser.getUserName());
mail.setFromPersonId(fromUser.getId().toString());
convertDocument(message.getDocument()).ifPresent(mail::addAttachment);
convertContact(message.getContact()).ifPresent(mail::addAttachment);
convertPhoto(message.getPhoto()).ifPresent(mail::addAttachment);
convertVideo(message.getVideo()).ifPresent(mail::addAttachment);
final List<MessageEntity> entities = message.getEntities();
if (entities != null) {
@ -74,15 +79,14 @@ public final class MessageMailConvert {
final List<Picture> pictures = photoSizes.stream()
.map(photoSize -> {
final Picture picture = new Picture();
picture.setFileSize(photoSize.getFileSize());
picture.setFileSize(photoSize.getFileSize().longValue());
picture.setFileId(photoSize.getFileId());
picture.setHeight(photoSize.getHeight());
picture.setWeight(photoSize.getWidth());
picture.setFileUniqueId(photoSize.getFileUniqueId());
return picture;
}).toList();
attachment.setPictureSizes(pictures);
attachment.setPictures(pictures);
return Optional.of(attachment);
}
@ -119,6 +123,17 @@ public final class MessageMailConvert {
return Optional.empty();
}
private static Optional<VideoAttachment> convertVideo(Video video) {
if (video != null) {
final VideoAttachment attachment = new VideoAttachment();
attachment.setFileId(video.getFileId());
attachment.setFileSize(video.getFileSize());
attachment.setFileName(video.getFileName());
return Optional.of(attachment);
}
return Optional.empty();
}
private static List<Attachment> convertAttachments(Message message) {
final List<MessageEntity> entities = message.getEntities();
if (Checker.checkNotEmpty(entities)) {

View File

@ -0,0 +1,244 @@
package dev.struchkov.godfather.telegram.main.context.convert;
import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.godfather.main.domain.content.EditedMail;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.ContactAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.LinkAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.attachment.PictureGroupAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.StickerAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.VideoAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.VoiceAttachment;
import dev.struchkov.godfather.telegram.main.context.MailPayload;
import dev.struchkov.haiti.utils.Checker;
import dev.struchkov.haiti.utils.Strings;
import org.glassfish.grizzly.http.util.MimeType;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.Contact;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.PhotoSize;
import org.telegram.telegrambots.meta.api.objects.Video;
import org.telegram.telegrambots.meta.api.objects.Voice;
import org.telegram.telegrambots.meta.api.objects.stickers.Sticker;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static dev.struchkov.haiti.utils.Checker.checkNotBlank;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
/**
* TODO: Добавить описание класса.
*
* @author upagge [18.08.2019]
*/
public final class MessageMailConvert {
private MessageMailConvert() {
utilityClass();
}
public static EditedMail applyEdited(Message message) {
return EditedMail.builder()
.editDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getEditDate()), ZoneId.systemDefault()))
.newMail(apply(message))
.build();
}
public static Mail apply(Message message) {
final Mail mail = new Mail();
final Long chatId = message.getChatId();
mail.setId(message.getMessageId().toString());
mail.setFromPersonId(chatId != null ? chatId.toString() : null);
mail.setText(getText(message));
mail.setCreateDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(message.getDate()), ZoneId.systemDefault()));
final Chat chat = message.getChat();
mail.setFirstName(chat.getFirstName());
mail.setLastName(chat.getLastName());
mail.addPayload(MailPayload.USERNAME, chat.getUserName());
convertDocument(message.getDocument()).ifPresent(mail::addAttachment);
convertContact(message.getContact()).ifPresent(mail::addAttachment);
convertPhoto(message.getPhoto()).ifPresent(mail::addAttachment);
convertVideo(message.getVideo()).ifPresent(mail::addAttachment);
convertVoice(message.getVoice()).ifPresent(mail::addAttachment);
convertSticker(message.getSticker()).ifPresent(mail::addAttachment);
final List<MessageEntity> entities = message.getEntities();
if (entities != null) {
mail.addAttachments(convertAttachments(message));
}
if (message.getReplyToMessage() != null) {
mail.setReplayMail(apply(message.getReplyToMessage()));
}
return mail;
}
private static String getText(Message message) {
if (checkNotBlank(message.getText())) {
return message.getText();
}
if (checkNotBlank(message.getCaption())) {
return message.getCaption();
}
return null;
}
private static Optional<Attachment> convertPhoto(List<PhotoSize> photoSizes) {
if (photoSizes != null && !photoSizes.isEmpty()) {
final PictureGroupAttachment attachment = new PictureGroupAttachment();
final List<Picture> pictures = photoSizes.stream()
.map(photoSize -> {
final Picture picture = new Picture();
picture.setFileSize(photoSize.getFileSize().longValue());
picture.setFileId(photoSize.getFileId());
picture.setHeight(photoSize.getHeight());
picture.setWeight(photoSize.getWidth());
picture.setMimeType("image/jpeg");
picture.setFileName(generateFileName("image/jpeg"));
return picture;
}).toList();
attachment.setPictures(pictures);
return Optional.of(attachment);
}
return Optional.empty();
}
private static Optional<ContactAttachment> convertContact(Contact contact) {
if (contact != null) {
final ContactAttachment attachment = new ContactAttachment();
attachment.setPhoneNumber(contact.getPhoneNumber());
attachment.setUserId(contact.getUserId());
attachment.setFirstName(contact.getFirstName());
attachment.setLastName(contact.getLastName());
if (contact.getVCard() != null) {
attachment.setOwner(false);
attachment.setVCard(contact.getVCard());
} else {
attachment.setOwner(true);
}
return Optional.of(attachment);
}
return Optional.empty();
}
private static Optional<DocumentAttachment> convertDocument(Document document) {
if (document != null) {
final DocumentAttachment attachment = new DocumentAttachment();
attachment.setFileId(document.getFileId());
attachment.setFileSize(document.getFileSize());
attachment.setFileName(document.getFileName());
attachment.setMimeType(document.getMimeType());
return Optional.of(attachment);
}
return Optional.empty();
}
private static Optional<VoiceAttachment> convertVoice(Voice voice) {
if (voice != null) {
final VoiceAttachment attachment = new VoiceAttachment();
attachment.setFileId(voice.getFileId());
attachment.setFileSize(voice.getFileSize());
attachment.setMimeType(voice.getMimeType());
attachment.setDuration(Duration.ofSeconds(voice.getDuration()));
attachment.setFileName(generateFileName(voice.getMimeType()));
return Optional.of(attachment);
}
return Optional.empty();
}
private static Optional<StickerAttachment> convertSticker(Sticker sticker) {
if (sticker != null) {
final StickerAttachment attachment = new StickerAttachment();
attachment.setFileId(sticker.getFileId());
attachment.setFileSize(sticker.getFileSize().longValue());
attachment.setAnimated(sticker.getIsAnimated());
attachment.setVideo(sticker.getIsVideo());
attachment.setFileName(UUID.randomUUID().toString());
attachment.setEmoji(sticker.getEmoji());
return Optional.of(attachment);
}
return Optional.empty();
}
private static String generateFileName(String mimeType) {
final StringBuilder builder = new StringBuilder(UUID.randomUUID().toString());
switch (mimeType) {
case "audio/ogg" -> builder.append(".ogg");
case "image/png" -> builder.append(".png");
case "image/jpeg" -> builder.append(".jpg");
default -> {}
}
return builder.toString();
}
private static Optional<VideoAttachment> convertVideo(Video video) {
if (video != null) {
final VideoAttachment attachment = new VideoAttachment();
attachment.setFileId(video.getFileId());
attachment.setFileSize(video.getFileSize());
attachment.setFileName(video.getFileName());
attachment.setMimeType(video.getMimeType());
return Optional.of(attachment);
}
return Optional.empty();
}
private static List<Attachment> convertAttachments(Message message) {
final List<MessageEntity> entities = message.getEntities();
if (Checker.checkNotEmpty(entities)) {
return entities.stream()
.map(entity -> convertEntity(message, entity))
.filter(Optional::isPresent)
.map(Optional::get)
.toList();
}
return Collections.emptyList();
}
private static Optional<Attachment> convertEntity(Message message, MessageEntity entity) {
switch (entity.getType()) {
case "text_link" -> {
return Optional.of(entity.getUrl())
.map(LinkAttachment::new);
}
case "url" -> {
return Optional.of(entity.getText())
.map(LinkAttachment::new);
}
case "bot_command" -> {
final String commandValue = entity.getText();
String commandArg = message.getText().replace(commandValue, "");
if (Checker.checkNotEmpty(commandArg)) {
commandArg = commandArg.substring(1);
}
final CommandAttachment commandAttachment = new CommandAttachment();
commandAttachment.setValue(commandValue);
commandAttachment.setCommandType(commandValue.replace("/", ""));
commandAttachment.setArg(Strings.EMPTY.equals(commandArg) ? null : commandArg);
commandAttachment.setRawValue(message.getText());
return Optional.of(commandAttachment);
}
}
return Optional.empty();
}
}

View File

@ -0,0 +1,41 @@
package dev.struchkov.godfather.telegram.main.context.convert;
import dev.struchkov.godfather.telegram.domain.event.Subscribe;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.User;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class SubscribeConvert {
private SubscribeConvert() {
utilityClass();
}
public static Subscribe apply(ChatMemberUpdated updated) {
final User user = updated.getFrom();
final Subscribe subscribe = new Subscribe();
subscribe.setTelegramId(user.getId().toString());
subscribe.setLastName(user.getLastName());
subscribe.setFirstName(user.getFirstName());
subscribe.setSubscriptionDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(updated.getDate()), ZoneId.systemDefault()));
subscribe.setLogin(user.getUserName());
subscribe.setLanguageCode(user.getLanguageCode());
subscribe.setPremium(convert(user.getIsPremium()));
return subscribe;
}
private static boolean convert(Boolean isPremium) {
if (checkNotNull(isPremium)) {
return isPremium;
}
return false;
}
}

View File

@ -0,0 +1,41 @@
package dev.struchkov.godfather.telegram.main.context.convert;
import dev.struchkov.godfather.telegram.domain.event.Unsubscribe;
import org.telegram.telegrambots.meta.api.objects.ChatMemberUpdated;
import org.telegram.telegrambots.meta.api.objects.User;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class UnsubscribeConvert {
private UnsubscribeConvert() {
utilityClass();
}
public static Unsubscribe apply(ChatMemberUpdated updated) {
final User user = updated.getFrom();
final Unsubscribe unsubscribe = new Unsubscribe();
unsubscribe.setTelegramId(user.getId().toString());
unsubscribe.setLogin(user.getUserName());
unsubscribe.setFirstName(user.getFirstName());
unsubscribe.setUnsubscriptionDate(LocalDateTime.ofInstant(Instant.ofEpochSecond(updated.getDate()), ZoneId.systemDefault()));
unsubscribe.setPremium(convert(user.getIsPremium()));
unsubscribe.setLastName(user.getLastName());
unsubscribe.setLanguageCode(user.getLanguageCode());
return unsubscribe;
}
private static boolean convert(Boolean isPremium) {
if (checkNotNull(isPremium)) {
return isPremium;
}
return false;
}
}

View File

@ -0,0 +1,9 @@
package dev.struchkov.godfather.telegram.main.context.exception;
public class TelegramBanBotException extends TelegramSenderException{
public TelegramBanBotException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,16 @@
package dev.struchkov.godfather.telegram.main.context.exception;
public class TelegramBotException extends RuntimeException {
public TelegramBotException() {
}
public TelegramBotException(String message) {
super(message);
}
public TelegramBotException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,9 @@
package dev.struchkov.godfather.telegram.main.context.exception;
public class TelegramReplaceSenderException extends TelegramSenderException {
public TelegramReplaceSenderException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,9 @@
package dev.struchkov.godfather.telegram.main.context.exception;
public class TelegramSenderException extends TelegramBotException {
public TelegramSenderException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-context-quarkus</artifactId>
@ -24,6 +24,10 @@
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context-main</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain-quarkus</artifactId>
</dependency>
<dependency>
<groupId>org.telegram</groupId>

View File

@ -1,7 +1,6 @@
package dev.struchkov.godfather.telegram.quarkus.context.service;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.attachment.FileAttachment;
import dev.struchkov.godfather.telegram.domain.files.ByteContainer;
import dev.struchkov.godfather.telegram.domain.files.FileContainer;
import io.smallrye.mutiny.Uni;
@ -9,10 +8,8 @@ import org.jetbrains.annotations.NotNull;
public interface AttachmentService {
Uni<FileContainer> uploadFile(@NotNull DocumentAttachment documentAttachment);
Uni<FileContainer> uploadFile(@NotNull FileAttachment documentAttachment);
Uni<ByteContainer> uploadBytes(@NotNull DocumentAttachment documentAttachment);
Uni<ByteContainer> uploadBytes(@NotNull Picture picture);
Uni<ByteContainer> uploadBytes(@NotNull FileAttachment fileAttachment);
}

View File

@ -3,11 +3,9 @@ package dev.struchkov.godfather.telegram.quarkus.context.service;
import io.smallrye.mutiny.Uni;
import org.telegram.telegrambots.meta.api.objects.Update;
import javax.validation.constraints.NotNull;
public interface EventDistributor {
Uni<Void> processing(@NotNull Update update);
Uni<Void> processing(Update update);
}

View File

@ -2,8 +2,6 @@ package dev.struchkov.godfather.telegram.quarkus.context.service;
import org.telegram.telegrambots.meta.bots.AbsSender;
import javax.validation.constraints.NotNull;
/**
* TODO: Добавить описание интерфейса.
*
@ -13,6 +11,6 @@ public interface TelegramBot {
AbsSender getAdsSender();
void initEventDistributor(@NotNull EventDistributor eventDistributor);
void initEventDistributor(EventDistributor eventDistributor);
}

View File

@ -0,0 +1,13 @@
package dev.struchkov.godfather.telegram.quarkus.context.service;
import org.telegram.telegrambots.meta.bots.AbsSender;
public interface TelegramConnect {
AbsSender getAbsSender();
String getToken();
void initEventDistributor(EventDistributor eventDistributorService);
}

View File

@ -10,4 +10,6 @@ public interface TelegramSending extends SendingService {
Uni<SentBox> sendNotSave(@NotNull BoxAnswer boxAnswer);
Uni<Void> replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer);
}

View File

@ -1,9 +1,12 @@
package dev.struchkov.godfather.telegram.quarkus.context.service;
import dev.struchkov.godfather.telegram.domain.ChatAction;
import dev.struchkov.godfather.telegram.domain.ClientBotCommand;
import io.smallrye.mutiny.Uni;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public interface TelegramService {
Uni<Void> executeAction(@NotNull String personId, ChatAction chatAction);
@ -12,4 +15,8 @@ public interface TelegramService {
Uni<Void> unPinMessage(@NotNull String personId, @NotNull String messageId);
Uni<Void> addCommand(@NotNull Collection<ClientBotCommand> botCommands);
Uni<Boolean> checkChatMember(@NotNull String personId, @NotNull String chatIdOrChannelId);
}

View File

@ -4,7 +4,7 @@
<parent>
<artifactId>telegram-context</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-context-simple</artifactId>
@ -16,6 +16,10 @@
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-context-simple</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context-main</artifactId>

View File

@ -1,9 +1,8 @@
package dev.struchkov.godfather.telegram.simple.context.service;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.api.objects.Update;
import javax.validation.constraints.NotNull;
public interface EventDistributor {
void processing(@NotNull Update update);

View File

@ -1,9 +1,8 @@
package dev.struchkov.godfather.telegram.simple.context.service;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.meta.bots.AbsSender;
import javax.validation.constraints.NotNull;
/**
* TODO: Добавить описание интерфейса.
*

View File

@ -1,4 +1,4 @@
package dev.struchkov.godfather.telegram.main.context;
package dev.struchkov.godfather.telegram.simple.context.service;
import org.telegram.telegrambots.meta.bots.AbsSender;
@ -8,4 +8,6 @@ public interface TelegramConnect {
String getToken();
void initEventDistributor(EventDistributor eventDistributorService);
}

View File

@ -3,12 +3,13 @@ package dev.struchkov.godfather.telegram.simple.context.service;
import dev.struchkov.godfather.simple.context.service.SendingService;
import dev.struchkov.godfather.simple.domain.BoxAnswer;
import dev.struchkov.godfather.simple.domain.SentBox;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
public interface TelegramSending extends SendingService {
Optional<SentBox> sendNotSave(@NotNull BoxAnswer boxAnswer);
Optional<SentBox> sendNotSave(BoxAnswer boxAnswer);
void replaceInlineMessage(String inlineMessageId, BoxAnswer boxAnswer);
}

View File

@ -1,8 +1,11 @@
package dev.struchkov.godfather.telegram.simple.context.service;
import dev.struchkov.godfather.telegram.domain.ChatAction;
import dev.struchkov.godfather.telegram.domain.ClientBotCommand;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public interface TelegramService {
void executeAction(@NotNull String personId, ChatAction chatAction);
@ -11,4 +14,8 @@ public interface TelegramService {
void unPinMessage(@NotNull String personId, @NotNull String messageId);
void addCommand(@NotNull Collection<ClientBotCommand> botCommands);
boolean checkChatMember(@NotNull String personId, @NotNull String chatIdOrChannelId);
}

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<modules>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-core-main</artifactId>

View File

@ -8,7 +8,10 @@ import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.LinkAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.attachment.PictureGroupAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.StickerAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.TelegramAttachmentType;
import dev.struchkov.godfather.telegram.domain.attachment.VideoAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.VoiceAttachment;
import java.util.Collection;
import java.util.Collections;
@ -46,6 +49,28 @@ public final class Attachments {
return Optional.empty();
}
public static Optional<VoiceAttachment> findFirstVoice(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
if (isVoice(attachment)) {
return Optional.of((VoiceAttachment) attachment);
}
}
}
return Optional.empty();
}
public static Optional<StickerAttachment> findFirstSticker(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
if (isSticker(attachment)) {
return Optional.of((StickerAttachment) attachment);
}
}
}
return Optional.empty();
}
public static Optional<ButtonClickAttachment> findFirstButtonClick(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
@ -57,6 +82,17 @@ public final class Attachments {
return Optional.empty();
}
public static Optional<VideoAttachment> findFirstVideo(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
if (isVideo(attachment)) {
return Optional.of((VideoAttachment) attachment);
}
}
}
return Optional.empty();
}
public static Optional<PictureGroupAttachment> findFirstPictureGroup(Collection<Attachment> attachments) {
if (checkNotEmpty(attachments)) {
for (Attachment attachment : attachments) {
@ -133,17 +169,17 @@ public final class Attachments {
return TelegramAttachmentType.DOCUMENT.name().equals(attachment.getType());
}
private static boolean isContact(Attachment attachment) {
public static boolean isContact(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.CONTACT.name().equals(attachment.getType());
}
private static boolean isPictureGroup(Attachment attachment) {
public static boolean isPictureGroup(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.PICTURE.name().equals(attachment.getType());
return TelegramAttachmentType.PICTURE_GROUP.name().equals(attachment.getType());
}
private static boolean isLink(Attachment attachment) {
public static boolean isLink(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.LINK.name().equals(attachment.getType());
}
@ -153,4 +189,19 @@ public final class Attachments {
return TelegramAttachmentType.BUTTON_CLICK.name().equals(attachment.getType());
}
public static boolean isVideo(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.VIDEO.name().equals(attachment.getType());
}
public static boolean isVoice(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.VOICE.name().equals(attachment.getType());
}
public static boolean isSticker(Attachment attachment) {
isNotNull(attachment);
return TelegramAttachmentType.STICKER.name().equals(attachment.getType());
}
}

View File

@ -1,16 +1,15 @@
package dev.struchkov.godfather.telegram.main.core.util;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardButton;
import dev.struchkov.godfather.main.domain.keyboard.button.SimpleButton;
import dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoard;
import dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoardLine;
import dev.struchkov.godfather.telegram.domain.keyboard.InlineKeyBoard;
import dev.struchkov.godfather.telegram.domain.keyboard.SimpleKeyBoardLine;
import dev.struchkov.godfather.telegram.domain.keyboard.button.SimpleButton;
import java.util.Arrays;
import java.util.List;
import static dev.struchkov.godfather.main.domain.keyboard.button.SimpleButton.simpleButton;
import static dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoardLine.simpleLine;
import static dev.struchkov.godfather.telegram.domain.keyboard.SimpleKeyBoardLine.keyBoardLine;
import static dev.struchkov.godfather.telegram.domain.keyboard.button.SimpleButton.simpleButton;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public final class InlineKeyBoards {
@ -24,23 +23,21 @@ public final class InlineKeyBoards {
/**
* Возвращает клавиатуру формата 1х2, с кнопками "Да | Нет"
*
* @return {@link SimpleKeyBoard}
*/
public static SimpleKeyBoardLine lineYesOrNo() {
return simpleLine(YES_BUTTON, NO_BUTTON);
public static InlineKeyBoard lineYesOrNo() {
return InlineKeyBoard.inlineKeyBoard(keyBoardLine(YES_BUTTON, NO_BUTTON));
}
/**
* Возвращает клавиатуру формата 1хN, где N - это количество элементов в переданном списке
*
* @param labelButtons Список названий для кнопок
* @return {@link SimpleKeyBoard}
* @return {@link InlineKeyBoard}
*/
public static InlineKeyBoard verticalMenuString(List<String> labelButtons) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
final InlineKeyBoard.InlineKeyBoardBuilder keyBoard = InlineKeyBoard.builder();
for (String labelButton : labelButtons) {
keyBoard.line(simpleLine(simpleButton(labelButton, labelButton)));
keyBoard.line(keyBoardLine(simpleButton(labelButton, labelButton)));
}
return keyBoard.build();
}
@ -49,7 +46,7 @@ public final class InlineKeyBoards {
* Возвращает клавиатуру формата 1хN, где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link SimpleKeyBoard}
* @return {@link InlineKeyBoard}
*/
public static InlineKeyBoard verticalMenuString(String... labelButton) {
return verticalMenuString(Arrays.asList(labelButton));
@ -59,7 +56,7 @@ public final class InlineKeyBoards {
* Возвращает клавиатуру формата 2х(N/2), где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link SimpleKeyBoard}
* @return {@link InlineKeyBoard}
*/
public static InlineKeyBoard verticalDuoMenuString(String... labelButton) {
return verticalDuoMenuString(Arrays.asList(labelButton));
@ -69,12 +66,12 @@ public final class InlineKeyBoards {
* Возвращает клавиатуру формата 2х(N/2), где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link SimpleKeyBoard}
* @return {@link InlineKeyBoard}
*/
public static InlineKeyBoard verticalDuoMenuString(List<String> labelButton) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
final InlineKeyBoard.InlineKeyBoardBuilder keyBoard = InlineKeyBoard.builder();
boolean flag = true;
SimpleKeyBoardLine.Builder keyBoardLine = SimpleKeyBoardLine.builder();
SimpleKeyBoardLine.SimpleKeyBoardLineBuilder keyBoardLine = SimpleKeyBoardLine.builder();
for (int i = 0; i <= labelButton.size() - 1; i++) {
String label = labelButton.get(i);
keyBoardLine.button(simpleButton(label));
@ -93,9 +90,9 @@ public final class InlineKeyBoards {
return keyBoard.build();
}
public static void verticalDuoMenu(InlineKeyBoard.Builder builder, List<? extends KeyBoardButton> buttons) {
public static void verticalDuoMenu(InlineKeyBoard.InlineKeyBoardBuilder builder, List<? extends KeyBoardButton> buttons) {
boolean flag = true;
SimpleKeyBoardLine.Builder keyBoardLine = SimpleKeyBoardLine.builder();
SimpleKeyBoardLine.SimpleKeyBoardLineBuilder keyBoardLine = SimpleKeyBoardLine.builder();
for (int i = 0; i <= buttons.size() - 1; i++) {
keyBoardLine.button(buttons.get(i));
if (flag) {
@ -113,7 +110,7 @@ public final class InlineKeyBoards {
}
public static InlineKeyBoard verticalDuoMenu(List<? extends KeyBoardButton> buttons) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
final InlineKeyBoard.InlineKeyBoardBuilder keyBoard = InlineKeyBoard.builder();
verticalDuoMenu(keyBoard, buttons);
return keyBoard.build();
}
@ -126,12 +123,12 @@ public final class InlineKeyBoards {
* Возвращает клавиатуру формата 1xN сформированную из списка кнопок, где N - количество кнопок в списке
*
* @param buttons Список кнопок
* @return {@link SimpleKeyBoard}
* @return {@link InlineKeyBoard}
*/
public static InlineKeyBoard verticalMenuButton(KeyBoardButton... buttons) {
final InlineKeyBoard.Builder keyBoard = InlineKeyBoard.builder();
final InlineKeyBoard.InlineKeyBoardBuilder keyBoard = InlineKeyBoard.builder();
for (KeyBoardButton simpleButton : buttons) {
keyBoard.line(simpleLine(simpleButton));
keyBoard.line(keyBoardLine(simpleButton));
}
return keyBoard.build();
}

View File

@ -0,0 +1,112 @@
package dev.struchkov.godfather.telegram.main.core.util;
import dev.struchkov.godfather.telegram.domain.keyboard.MarkupKeyBoard;
import dev.struchkov.godfather.telegram.domain.keyboard.SimpleKeyBoardLine;
import dev.struchkov.godfather.telegram.domain.keyboard.button.SimpleButton;
import java.util.Arrays;
import java.util.List;
/**
* Используется для быстрого создания клавиаутр {@link MarkupKeyBoard}.
*
* @author upagge [08/07/2019]
*/
public class SimpleKeyBoards {
public static final SimpleButton YES_BUTTON = SimpleButton.simpleButton("Да", "{\"button\": \"yes\"}");
public static final SimpleButton NO_BUTTON = SimpleButton.simpleButton("Нет", "{\"button\": \"no\"}");
private SimpleKeyBoards() {
throw new IllegalStateException();
}
/**
* Возвращает клавиатуру формата 1х2, с кнопками "Да | Нет"
*
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard keyBoardYesNo() {
return MarkupKeyBoard.builder().line(
SimpleKeyBoardLine.builder().button(YES_BUTTON).button(NO_BUTTON).build()
).build();
}
/**
* Возвращает клавиатуру формата 1хN, где N - это количество элементов в переданном списке
*
* @param labelButtons Список названий для кнопок
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard verticalMenuString(List<String> labelButtons) {
final MarkupKeyBoard.MarkupKeyBoardBuilder keyBoard = MarkupKeyBoard.builder();
for (String labelButton : labelButtons) {
final SimpleButton simpleButton = SimpleButton.simpleButton(labelButton, "{\"button\": \"" + labelButton + "\"}");
keyBoard.line(SimpleKeyBoardLine.builder().button(simpleButton).build());
}
return keyBoard.build();
}
/**
* Возвращает клавиатуру формата 1хN, где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard verticalMenuString(String... labelButton) {
return verticalMenuString(Arrays.asList(labelButton));
}
/**
* Возвращает клавиатуру формата 2х(N/2), где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard verticalDuoMenuString(String... labelButton) {
return verticalDuoMenuString(Arrays.asList(labelButton));
}
/**
* Возвращает клавиатуру формата 2х(N/2), где N - это количество элементов в переданном списке
*
* @param labelButton Список названий для кнопок
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard verticalDuoMenuString(List<String> labelButton) {
final MarkupKeyBoard.MarkupKeyBoardBuilder keyBoard = MarkupKeyBoard.builder();
boolean flag = true;
SimpleKeyBoardLine.SimpleKeyBoardLineBuilder keyBoardLine = SimpleKeyBoardLine.builder();
for (int i = 0; i <= labelButton.size() - 1; i++) {
String label = labelButton.get(i);
keyBoardLine.button(SimpleButton.simpleButton(label));
if (flag) {
if (i == labelButton.size() - 1) {
keyBoard.line(keyBoardLine.build());
} else {
flag = false;
}
} else {
keyBoard.line(keyBoardLine.build());
keyBoardLine = SimpleKeyBoardLine.builder();
flag = true;
}
}
return keyBoard.build();
}
/**
* Возвращает клавиатуру формата 1xN сформированную из списка кнопок, где N - количество кнопок в списке
*
* @param simpleButtons Список кнопок
* @return {@link MarkupKeyBoard}
*/
public static MarkupKeyBoard verticalMenuButton(List<SimpleButton> simpleButtons) {
final MarkupKeyBoard.MarkupKeyBoardBuilder keyBoard = MarkupKeyBoard.builder();
for (SimpleButton simpleButton : simpleButtons) {
keyBoard.line(SimpleKeyBoardLine.builder().button(simpleButton).build());
}
return keyBoard.build();
}
}

View File

@ -0,0 +1,68 @@
package dev.struchkov.godfather.telegram.main.core.util;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.CommandAttachment;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public class UnitTrigger {
private UnitTrigger() {
utilityClass();
}
public static Predicate<Mail> clickButtonRaw(String rawCallBackData) {
return mail -> {
final Optional<ButtonClickAttachment> optButtonClick = Attachments.findFirstButtonClick(mail.getAttachments());
if (optButtonClick.isPresent()) {
final ButtonClickAttachment buttonClick = optButtonClick.get();
final String rawData = buttonClick.getRawCallBackData();
return rawData.equals(rawCallBackData);
}
return false;
};
}
public static Predicate<Mail> isCommandByType(String commandType) {
return mail -> {
final Optional<CommandAttachment> optCommand = Attachments.findFirstCommand(mail.getAttachments());
if (optCommand.isPresent()) {
final CommandAttachment command = optCommand.get();
final String type = command.getCommandType();
return type.equals(commandType);
}
return false;
};
}
public static Predicate<Mail> isButtonClick() {
return mail -> Attachments.findFirstButtonClick(mail.getAttachments()).isPresent();
}
public static Predicate<Mail> isLinks() {
return mail -> Attachments.findFirstLink(mail.getAttachments()).isPresent();
}
public static Predicate<Mail> isButtonClickArg(String argType) {
return mail -> Attachments.findFirstButtonClick(mail.getAttachments())
.flatMap(click -> click.getArgByType(argType))
.isPresent();
}
public static Predicate<Mail> isButtonClickArgValue(String argType, String argValue) {
return mail -> Attachments.findFirstButtonClick(mail.getAttachments())
.flatMap(click -> click.getArgByType(argType))
.filter(buttonArg -> argValue.equals(buttonArg.getValue()))
.isPresent();
}
public static Predicate<Mail> isPersonId(String... personId) {
return mail -> Arrays.stream(personId).anyMatch(id -> id.equals(mail.getFromPersonId()));
}
}

View File

@ -4,7 +4,7 @@
<parent>
<artifactId>telegram-core</artifactId>
<groupId>dev.struchkov.godfather.telegram</groupId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-core-quarkus</artifactId>
@ -16,6 +16,10 @@
</properties>
<dependencies>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core-quarkus</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-context-quarkus</artifactId>
@ -25,10 +29,6 @@
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core-main</artifactId>
</dependency>
<dependency>
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-core-quarkus</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,10 +1,8 @@
package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.quarkus.context.service.PersonSettingService;
import dev.struchkov.godfather.quarkus.core.GeneralAutoResponder;
import dev.struchkov.godfather.quarkus.core.service.StorylineService;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramSending;
/**
* TODO: Добавить описание класса.
@ -13,12 +11,8 @@ import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramSending;
*/
public class MailAutoresponderTelegram extends GeneralAutoResponder<Mail> {
public MailAutoresponderTelegram(
TelegramSending sending,
PersonSettingService personSettingService,
StorylineService<Mail> storyLineService
) {
super(sending, personSettingService, storyLineService);
public MailAutoresponderTelegram(StorylineService<Mail> storyLineService) {
super(storyLineService);
}
}

View File

@ -0,0 +1,89 @@
package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.bots.AbsSender;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
public class TelegramDefaultConnect implements TelegramConnect {
private final String botToken;
private final AbsSender absSender;
public TelegramDefaultConnect(TelegramBotConfig connectConfig) {
this.botToken = connectConfig.getToken();
this.absSender = createAbsSender(connectConfig);
}
@NotNull
private DefaultAbsSender createAbsSender(TelegramBotConfig connectConfig) {
final DefaultBotOptions botOptions = new DefaultBotOptions();
final ProxyConfig proxyConfig = connectConfig.getProxyConfig();
if (checkNotNull(proxyConfig) && proxyConfig.isEnable()) {
if (checkNotNull(proxyConfig.getPassword())) {
try {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
proxyConfig.getUser(),
proxyConfig.getPassword().toCharArray()
);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
if (checkNotNull(proxyConfig.getHost())) {
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
// System.setProperty("javax.net.debug", "all");
botOptions.setProxyHost(proxyConfig.getHost());
botOptions.setProxyPort(proxyConfig.getPort());
botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
}
}
return new DefaultAbsSender(botOptions) {
@Override
public String getBotToken() {
return botToken;
}
};
}
private DefaultBotOptions.ProxyType convertProxyType(ProxyConfig.Type type) {
return switch (type) {
case SOCKS5 -> DefaultBotOptions.ProxyType.SOCKS5;
case SOCKS4 -> DefaultBotOptions.ProxyType.SOCKS4;
case HTTP -> DefaultBotOptions.ProxyType.HTTP;
};
}
@Override
public AbsSender getAbsSender() {
return absSender;
}
@Override
public String getToken() {
return botToken;
}
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
throw new IllegalStateException();
}
}

View File

@ -3,12 +3,17 @@ package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramBot;
import io.smallrye.mutiny.infrastructure.Infrastructure;
import io.vertx.core.Vertx;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.bots.AbsSender;
import java.lang.reflect.Field;
/**
* TODO: Добавить описание класса.
*
@ -16,20 +21,35 @@ import org.telegram.telegrambots.meta.bots.AbsSender;
*/
public class TelegramPollingBot extends TelegramLongPollingBot implements TelegramBot {
private final Vertx vertx;
private final TelegramBotConfig telegramBotConfig;
private EventDistributor eventDistributor;
public TelegramPollingBot(TelegramBotConfig telegramBotConfig, DefaultBotOptions defaultBotOptions) {
@SneakyThrows
public TelegramPollingBot(Vertx vertx, TelegramBotConfig telegramBotConfig, DefaultBotOptions defaultBotOptions) {
super(defaultBotOptions);
this.telegramBotConfig = telegramBotConfig;
this.vertx = vertx;
final Field field = this.getClass().getSuperclass().getSuperclass().getDeclaredField("exe");
// Делаем поле exe доступным для изменений
field.setAccessible(true);
// Заменяем поле exe в экземпляре наследника
field.set(this, Infrastructure.getDefaultExecutor());
// Закрываем доступ к полю exe
field.setAccessible(false);
}
public TelegramPollingBot(TelegramBotConfig telegramBotConfig) {
public TelegramPollingBot(Vertx vertx, TelegramBotConfig telegramBotConfig) {
this.vertx = vertx;
this.telegramBotConfig = telegramBotConfig;
}
@Override
public void onUpdateReceived(Update update) {
vertx.runOnContext(v -> handleUpdate(update));
}
private void handleUpdate(Update update) {
if (update != null && eventDistributor != null) {
eventDistributor.processing(update)
.subscribe().asCompletionStage();

View File

@ -3,11 +3,10 @@ package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig.Type;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramBot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.vertx.core.Vertx;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.bots.AbsSender;
@ -19,40 +18,17 @@ import java.net.PasswordAuthentication;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/**
* TODO: Добавить описание класса.
*
* @author upagge [30.01.2020]
*/
public class TelegramConnectBot implements TelegramConnect {
@Slf4j
public class TelegramPollingConnect implements TelegramConnect {
private static final Logger log = LoggerFactory.getLogger(TelegramConnectBot.class);
private TelegramPollingBot pollingBot;
private TelegramBot telegramBot;
private final TelegramBotConfig telegramBotConfig;
public TelegramConnectBot(TelegramBotConfig telegramBotConfig) {
this.telegramBotConfig = telegramBotConfig;
initLongPolling(telegramBotConfig);
public TelegramPollingConnect(Vertx vertx, TelegramBotConfig telegramBotConfig) {
initLongPolling(vertx, telegramBotConfig);
}
// public TelegramConnect(TelegramWebHookConfig telegramWebHookConfig) {
// initWebHook(telegramWebHookConfig);
// }
//
// private void initWebHook(TelegramWebHookConfig telegramWebHookConfig) {
// TelegramBotsApi botapi = new TelegramBotsApi();
// final TelegramWebhookBot telegramWebhookBot = new TelegramHookBot(telegramWebHookConfig);
// try {
// botapi.registerBot(telegramWebhookBot);
// this.telegramBot = (TelegramBot) telegramWebhookBot;
// } catch (TelegramApiRequestException e) {
// e.printStackTrace();
// }
// }
private void initLongPolling(TelegramBotConfig telegramBotConfig) {
private void initLongPolling(Vertx vertx, TelegramBotConfig telegramBotConfig) {
log.info("Initializing Telegram Long Polling...");
final ProxyConfig proxyConfig = telegramBotConfig.getProxyConfig();
if (checkNotNull(proxyConfig) && proxyConfig.isEnable() && checkNotNull(proxyConfig.getPassword()) && !"".equals(proxyConfig.getPassword())) {
try {
@ -66,8 +42,9 @@ public class TelegramConnectBot implements TelegramConnect {
}
});
} catch (Exception e) {
e.printStackTrace();
log.error("Error setting default authenticator for telegram proxy", e);
}
log.info("Telegram proxy with authentication enabled");
}
final TelegramBotsApi botapi;
@ -75,26 +52,29 @@ public class TelegramConnectBot implements TelegramConnect {
if (checkNotNull(proxyConfig) && proxyConfig.isEnable() && checkNotNull(proxyConfig.getHost()) && !"".equals(proxyConfig.getHost())) {
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
// System.setProperty("javax.net.debug", "all");
log.info(System.getProperty("https.protocols"));
// log.info(System.getProperty("https.protocols"));
DefaultBotOptions botOptions = new DefaultBotOptions();
botOptions.setProxyHost(proxyConfig.getHost());
botOptions.setProxyPort(proxyConfig.getPort());
botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
log.info("Telegram proxy configuration set for bot");
final TelegramPollingBot bot = new TelegramPollingBot(telegramBotConfig, botOptions);
final TelegramPollingBot bot = new TelegramPollingBot(vertx, telegramBotConfig, botOptions);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
this.pollingBot = bot;
log.info("Telegram Bot registered with proxy settings");
} else {
final TelegramPollingBot bot = new TelegramPollingBot(telegramBotConfig);
final TelegramPollingBot bot = new TelegramPollingBot(vertx, telegramBotConfig);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
this.pollingBot = bot;
log.info("Telegram Bot registered without proxy settings");
}
} catch (TelegramApiException e) {
log.error(e.getMessage());
log.error("Error registering telegram bot", e);
}
}
@ -106,17 +86,19 @@ public class TelegramConnectBot implements TelegramConnect {
};
}
public void initEventDistributor(EventDistributor eventDistributor) {
telegramBot.initEventDistributor(eventDistributor);
@Override
public String getToken() {
return pollingBot.getBotToken();
}
public String getToken() {
return telegramBotConfig.getToken();
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
pollingBot.initEventDistributor(eventDistributorService);
}
@Override
public AbsSender getAbsSender() {
return telegramBot.getAdsSender();
return pollingBot.getAdsSender();
}
}

View File

@ -0,0 +1,65 @@
package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramBot;
import io.smallrye.mutiny.infrastructure.Infrastructure;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.bots.AbsSender;
import java.lang.reflect.Field;
@Slf4j
public class TelegramWebhookBot extends org.telegram.telegrambots.bots.TelegramWebhookBot implements TelegramBot {
private final TelegramBotConfig telegramBotConfig;
private EventDistributor eventDistributor;
@SneakyThrows
public TelegramWebhookBot(TelegramBotConfig telegramBotConfig) {
this.telegramBotConfig = telegramBotConfig;
final Field field = this.getClass().getSuperclass().getSuperclass().getDeclaredField("exe");
// Делаем поле exe доступным для изменений
field.setAccessible(true);
// Заменяем поле exe в экземпляре наследника
field.set(this, Infrastructure.getDefaultExecutor());
// Закрываем доступ к полю exe
field.setAccessible(false);
}
@Override
public String getBotUsername() {
return telegramBotConfig.getUsername();
}
@Override
public String getBotToken() {
return telegramBotConfig.getToken();
}
@Override
public BotApiMethod<?> onWebhookUpdateReceived(Update update) {
eventDistributor.processing(update).subscribe().with(v -> {
});
return null;
}
@Override
public String getBotPath() {
return "bot";
}
@Override
public AbsSender getAdsSender() {
return this;
}
@Override
public void initEventDistributor(EventDistributor eventDistributor) {
this.eventDistributor = eventDistributor;
}
}

View File

@ -0,0 +1,54 @@
package dev.struchkov.godfather.telegram.quarkus.core;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.domain.config.WebhookConfig;
import dev.struchkov.godfather.telegram.quarkus.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@Slf4j
public class TelegramWebhookConnect implements TelegramConnect {
private TelegramWebhookBot webhookBot;
public TelegramWebhookConnect(TelegramBotConfig telegramBotConfig) {
log.info("Initializing Webhook Polling...");
try {
final TelegramWebhookBot bot = new TelegramWebhookBot(telegramBotConfig);
final WebhookConfig webhookConfig = telegramBotConfig.getWebhookConfig();
if (webhookConfig.isEnable()) {
log.info("Инициализация webhook соединения. {}", telegramBotConfig.getWebhookConfig());
final SetWebhook setWebhook = SetWebhook.builder()
.secretToken(webhookConfig.getSecretToken())
.url(webhookConfig.getUrl())
.build();
bot.setWebhook(setWebhook);
webhookBot = bot;
log.info("Инициализация webhook соединения прошла успешно.");
} else {
log.debug("Webhook соединение не устанавливалось.");
}
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
}
@Override
public AbsSender getAbsSender() {
return webhookBot.getAdsSender();
}
@Override
public String getToken() {
return webhookBot.getBotToken();
}
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
webhookBot.initEventDistributor(eventDistributorService);
}
}

View File

@ -0,0 +1,53 @@
package dev.struchkov.godfather.telegram.quarkus.core.handler;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.quarkus.context.service.EventHandler;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.smallrye.mutiny.Uni;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
@Slf4j
@RequiredArgsConstructor
public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
private final TelegramConnect telegramConnect;
@Override
public Uni<Void> handle(EventContainer<PreCheckoutQuery> event) {
final PreCheckoutQuery preCheckoutQuery = event.getObject();
final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery();
answerPreCheckoutQuery.setPreCheckoutQueryId(preCheckoutQuery.getId());
answerPreCheckoutQuery.setOk(true);
try {
answerPreCheckoutQuery.validate();
} catch (TelegramApiValidationException e) {
log.error(e.getMessage(), e);
}
return Uni.createFrom().completionStage(
execAsync(answerPreCheckoutQuery)
).replaceWithVoid();
}
public CompletionStage<Object> execAsync(AnswerPreCheckoutQuery answerShippingQuery) {
try {
telegramConnect.getAbsSender().executeAsync(answerShippingQuery);
} catch (TelegramApiException e) {
log.error(e.getMessage(), e);
}
return CompletableFuture.completedStage(null);
}
@Override
public Class<PreCheckoutQuery> getEventClass() {
return PreCheckoutQuery.class;
}
}

View File

@ -1,11 +1,13 @@
package dev.struchkov.godfather.telegram.quarkus.core.service;
import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.FileAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.attachment.TelegramAttachmentType;
import dev.struchkov.godfather.telegram.domain.files.ByteContainer;
import dev.struchkov.godfather.telegram.domain.files.FileContainer;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.quarkus.context.service.AttachmentService;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import io.smallrye.mutiny.Uni;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
@ -62,31 +64,20 @@ public class AttachmentServiceImpl implements AttachmentService {
}
@Override
public Uni<FileContainer> uploadFile(@NotNull DocumentAttachment documentAttachment) {
isNotNull(documentAttachment);
return downloadFile(documentAttachment)
.onItem().ifNotNull().transform(file -> new FileContainer(documentAttachment.getFileName(), documentAttachment.getMimeType(), file));
public Uni<FileContainer> uploadFile(@NotNull FileAttachment fileAttachment) {
isNotNull(fileAttachment);
return downloadFile(fileAttachment)
.onItem().ifNotNull().transform(file -> new FileContainer(fileAttachment.getFileName(), fileAttachment.getMimeType(), file));
}
@Override
public Uni<ByteContainer> uploadBytes(@NotNull DocumentAttachment documentAttachment) {
isNotNull(documentAttachment);
return downloadBytes(documentAttachment)
.onItem().ifNotNull().transform(bytes -> new ByteContainer(documentAttachment.getFileName(), documentAttachment.getMimeType(), bytes));
public Uni<ByteContainer> uploadBytes(@NotNull FileAttachment fileAttachment) {
isNotNull(fileAttachment);
return downloadBytes(fileAttachment)
.onItem().ifNotNull().transform(bytes -> new ByteContainer(fileAttachment.getFileName(), fileAttachment.getMimeType(), bytes));
}
@Override
public Uni<ByteContainer> uploadBytes(@NotNull Picture picture) {
isNotNull(picture);
return downloadBytes(picture)
.onItem().ifNotNull().transform(bytes -> new ByteContainer(null, "image/jpeg", bytes));
}
private Uni<byte[]> downloadBytes(Picture picture) {
return telegramDownloadBytes(picture.getFileId());
}
private Uni<byte[]> downloadBytes(DocumentAttachment documentAttachment) {
private Uni<byte[]> downloadBytes(FileAttachment documentAttachment) {
return telegramDownloadBytes(documentAttachment.getFileId());
}
@ -110,15 +101,15 @@ public class AttachmentServiceImpl implements AttachmentService {
);
}
private Uni<File> downloadFile(DocumentAttachment documentAttachment) {
return getFileUrl(documentAttachment.getFileId())
private Uni<File> downloadFile(FileAttachment fileAttachment) {
return getFileUrl(fileAttachment.getFileId())
.onItem().ifNotNull().transformToUni(fileUrl -> Uni.createFrom().completionStage(
CompletableFuture.supplyAsync(() -> {
final StringBuilder filePath = new StringBuilder();
if (folderPathForFiles != null) {
filePath.append(folderPathForFiles);
}
filePath.append(UUID.randomUUID()).append("_").append(documentAttachment.getFileName());
filePath.append(UUID.randomUUID()).append("_").append(fileAttachment.getFileName());
final File localFile = new File(filePath.toString());
final InputStream is;
try {

View File

@ -4,14 +4,14 @@ import dev.struchkov.godfather.telegram.quarkus.context.repository.SenderReposit
import io.smallrye.mutiny.Uni;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static dev.struchkov.haiti.utils.Inspector.isNotNull;
public class SenderMapRepository implements SenderRepository {
private final Map<String, String> lastMessageId = new HashMap<>();
private final Map<String, String> lastMessageId = new ConcurrentHashMap<>();
@Override
public Uni<String> getLastSendMessage(String telegramId) {

View File

@ -1,22 +1,38 @@
package dev.struchkov.godfather.telegram.quarkus.core.service;
import dev.struchkov.godfather.telegram.domain.ChatAction;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.domain.ClientBotCommand;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramConnect;
import dev.struchkov.godfather.telegram.quarkus.context.service.TelegramService;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.meta.api.methods.ActionType;
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.pinnedmessages.PinChatMessage;
import org.telegram.telegrambots.meta.api.methods.pinnedmessages.UnpinChatMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendChatAction;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotEmpty;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
import static dev.struchkov.haiti.utils.Checker.checkNull;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
public class TelegramServiceImpl implements TelegramService {
@ -58,6 +74,80 @@ public class TelegramServiceImpl implements TelegramService {
.replaceWithVoid();
}
@Override
public Uni<Void> addCommand(@NotNull Collection<ClientBotCommand> botCommands) {
return Uni.combine().all()
.unis(
Uni.createFrom().item(
botCommands.stream()
.filter(command -> checkNotNull(command.getLang()))
.collect(
Collectors.groupingBy(
ClientBotCommand::getLang,
mapping(clientCommand -> BotCommand.builder().command(clientCommand.getKey()).description(clientCommand.getDescription()).build(), toList())
)
)
),
Uni.createFrom().item(
botCommands.stream()
.filter(command -> checkNull(command.getLang()))
.map(clientCommand -> BotCommand.builder().command(clientCommand.getKey()).description(clientCommand.getDescription()).build())
.toList()
)
).asTuple()
.call(t -> {
final List<BotCommand> noLangCommands = t.getItem2();
if (checkNotEmpty(noLangCommands)) {
return Uni.createFrom().completionStage(
getExecuteAsync(
SetMyCommands.builder().commands(noLangCommands).build()
)
);
}
return Uni.createFrom().voidItem();
})
.call(t -> {
final Map<String, List<BotCommand>> commandMap = t.getItem1();
return Multi.createFrom().iterable(commandMap.entrySet())
.call(entry -> Uni.createFrom().completionStage(getExecuteAsync(SetMyCommands.builder().languageCode(entry.getKey()).commands(entry.getValue()).build())))
.collect().asList().replaceWithVoid();
})
.replaceWithVoid();
}
@Override
public Uni<Boolean> checkChatMember(@NotNull String personId, @NotNull String chatIdOrChannelId) {
final GetChatMember getChatMember = GetChatMember.builder()
.userId(Long.parseLong(personId))
.chatId(chatIdOrChannelId)
.build();
return Uni.createFrom().completionStage(getExecuteAsync(getChatMember))
.onItem().ifNotNull().transform(chatMember -> "member".equals(chatMember.getStatus()))
.onItem().ifNull().continueWith(false);
}
private CompletableFuture<ChatMember> getExecuteAsync(GetChatMember myCommands) {
try {
return absSender.executeAsync(myCommands);
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
return CompletableFuture.completedFuture(null);
}
private CompletableFuture<Boolean> getExecuteAsync(SetMyCommands myCommands) {
try {
return absSender.executeAsync(myCommands);
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
return CompletableFuture.completedFuture(null);
}
private CompletableFuture<Boolean> getExecuteAsync(UnpinChatMessage unpinChatMessage) {
try {
return absSender.executeAsync(unpinChatMessage);

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-core</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-core-simple</artifactId>

View File

@ -0,0 +1,20 @@
package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.main.domain.content.ChatMail;
import dev.struchkov.godfather.simple.core.GeneralAutoResponder;
import dev.struchkov.godfather.simple.core.service.StorylineService;
/**
* TODO: Добавить описание класса.
*
* @author upagge [18.08.2019]
*/
public class ChatMailAutoresponderTelegram extends GeneralAutoResponder<ChatMail> {
public ChatMailAutoresponderTelegram(
StorylineService<ChatMail> storyLineService
) {
super(storyLineService);
}
}

View File

@ -1,10 +1,8 @@
package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.simple.context.service.PersonSettingService;
import dev.struchkov.godfather.simple.core.GeneralAutoResponder;
import dev.struchkov.godfather.simple.core.service.StorylineService;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramSending;
/**
* TODO: Добавить описание класса.
@ -14,11 +12,9 @@ import dev.struchkov.godfather.telegram.simple.context.service.TelegramSending;
public class MailAutoresponderTelegram extends GeneralAutoResponder<Mail> {
public MailAutoresponderTelegram(
TelegramSending sending,
PersonSettingService personSettingService,
StorylineService<Mail> storyLineService
) {
super(sending, personSettingService, storyLineService);
super(storyLineService);
}
}

View File

@ -1,8 +1,9 @@
package dev.struchkov.godfather.telegram.main.core;
package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.simple.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import org.jetbrains.annotations.NotNull;
import org.telegram.telegrambots.bots.DefaultAbsSender;
import org.telegram.telegrambots.bots.DefaultBotOptions;
@ -80,4 +81,9 @@ public class TelegramDefaultConnect implements TelegramConnect {
return botToken;
}
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
throw new IllegalStateException();
}
}

View File

@ -11,11 +11,6 @@ import org.telegram.telegrambots.meta.bots.AbsSender;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/**
* TODO: Добавить описание класса.
*
* @author upagge [15/07/2019]
*/
public class TelegramPollingBot extends TelegramLongPollingBot implements TelegramBot {
private final TelegramBotConfig telegramBotConfig;

View File

@ -3,11 +3,9 @@ package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig;
import dev.struchkov.godfather.telegram.domain.config.ProxyConfig.Type;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.simple.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramBot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.bots.AbsSender;
@ -19,26 +17,19 @@ import java.net.PasswordAuthentication;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
/**
* TODO: Добавить описание класса.
*
* @author upagge [30.01.2020]
*/
public class TelegramConnectBot implements TelegramConnect {
@Slf4j
public class TelegramPollingConnect implements TelegramConnect {
private static final Logger log = LoggerFactory.getLogger(TelegramConnectBot.class);
private TelegramPollingBot pollingBot;
private TelegramBot telegramBot;
private final TelegramBotConfig telegramBotConfig;
public TelegramConnectBot(TelegramBotConfig telegramBotConfig) {
this.telegramBotConfig = telegramBotConfig;
public TelegramPollingConnect(TelegramBotConfig telegramBotConfig) {
initLongPolling(telegramBotConfig);
}
private void initLongPolling(TelegramBotConfig telegramBotConfig) {
log.info("Initializing Telegram Long Polling...");
final ProxyConfig proxyConfig = telegramBotConfig.getProxyConfig();
if (checkNotNull(proxyConfig) && checkNotNull(proxyConfig.getPassword()) && !"".equals(proxyConfig.getPassword())) {
if (checkNotNull(proxyConfig) && proxyConfig.isEnable() && checkNotNull(proxyConfig.getPassword()) && !"".equals(proxyConfig.getPassword())) {
try {
Authenticator.setDefault(new Authenticator() {
@Override
@ -50,8 +41,9 @@ public class TelegramConnectBot implements TelegramConnect {
}
});
} catch (Exception e) {
e.printStackTrace();
log.error("Error setting default authenticator for telegram proxy", e);
}
log.info("Telegram proxy with authentication enabled");
}
final TelegramBotsApi botapi;
@ -59,25 +51,29 @@ public class TelegramConnectBot implements TelegramConnect {
if (checkNotNull(proxyConfig) && proxyConfig.isEnable() && checkNotNull(proxyConfig.getHost()) && !"".equals(proxyConfig.getHost())) {
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
// System.setProperty("javax.net.debug", "all");
log.info(System.getProperty("https.protocols"));
// log.info(System.getProperty("https.protocols"));
DefaultBotOptions botOptions = new DefaultBotOptions();
botOptions.setProxyHost(proxyConfig.getHost());
botOptions.setProxyPort(proxyConfig.getPort());
botOptions.setProxyType(convertProxyType(proxyConfig.getType()));
log.info("Telegram proxy configuration set for bot");
final TelegramPollingBot bot = new TelegramPollingBot(telegramBotConfig, botOptions);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
this.pollingBot = bot;
log.info("Telegram Bot registered with proxy settings");
} else {
final TelegramPollingBot bot = new TelegramPollingBot(telegramBotConfig);
botapi = new TelegramBotsApi(DefaultBotSession.class);
botapi.registerBot(bot);
this.telegramBot = bot;
this.pollingBot = bot;
log.info("Telegram Bot registered without proxy settings");
}
} catch (TelegramApiException e) {
log.error(e.getMessage());
log.error("Error registering telegram bot", e);
}
}
@ -89,17 +85,19 @@ public class TelegramConnectBot implements TelegramConnect {
};
}
public void initEventDistributor(EventDistributor eventDistributor) {
telegramBot.initEventDistributor(eventDistributor);
@Override
public String getToken() {
return pollingBot.getBotToken();
}
public String getToken() {
return telegramBotConfig.getToken();
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
pollingBot.initEventDistributor(eventDistributorService);
}
@Override
public AbsSender getAbsSender() {
return telegramBot.getAdsSender();
return pollingBot.getAdsSender();
}
}

View File

@ -0,0 +1,52 @@
package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.simple.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramBot;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.bots.AbsSender;
@Slf4j
public class TelegramWebhookBot extends org.telegram.telegrambots.bots.TelegramWebhookBot implements TelegramBot {
private final TelegramBotConfig telegramBotConfig;
private EventDistributor eventDistributor;
public TelegramWebhookBot(TelegramBotConfig telegramBotConfig) {
this.telegramBotConfig = telegramBotConfig;
}
@Override
public String getBotUsername() {
return telegramBotConfig.getUsername();
}
@Override
public String getBotToken() {
return telegramBotConfig.getToken();
}
@Override
public BotApiMethod<?> onWebhookUpdateReceived(Update update) {
eventDistributor.processing(update);
return null;
}
@Override
public String getBotPath() {
return null;
}
@Override
public AbsSender getAdsSender() {
return this;
}
@Override
public void initEventDistributor(EventDistributor eventDistributor) {
this.eventDistributor = eventDistributor;
}
}

View File

@ -0,0 +1,57 @@
package dev.struchkov.godfather.telegram.simple.core;
import dev.struchkov.godfather.telegram.domain.config.TelegramBotConfig;
import dev.struchkov.godfather.telegram.domain.config.WebhookConfig;
import dev.struchkov.godfather.telegram.simple.context.service.EventDistributor;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@Slf4j
public class TelegramWebhookConnect implements TelegramConnect {
private TelegramWebhookBot webhookBot;
public TelegramWebhookConnect(TelegramBotConfig telegramBotConfig) {
initWebHook(telegramBotConfig);
}
private void initWebHook(TelegramBotConfig telegramBotConfig) {
try {
final TelegramWebhookBot bot = new TelegramWebhookBot(telegramBotConfig);
final WebhookConfig webhookConfig = telegramBotConfig.getWebhookConfig();
if (webhookConfig.isEnable()) {
log.info("Инициализация webhook соединения. {}", telegramBotConfig.getWebhookConfig());
final SetWebhook setWebhook = SetWebhook.builder()
.secretToken(webhookConfig.getSecretToken())
.url(webhookConfig.getUrl())
.build();
bot.setWebhook(setWebhook);
webhookBot = bot;
log.info("Инициализация webhook соединения прошла успешно.");
} else {
log.debug("Webhook соединение не устанавливалось.");
}
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
}
@Override
public AbsSender getAbsSender() {
return webhookBot.getAdsSender();
}
@Override
public String getToken() {
return webhookBot.getBotToken();
}
@Override
public void initEventDistributor(EventDistributor eventDistributorService) {
webhookBot.initEventDistributor(eventDistributorService);
}
}

View File

@ -0,0 +1,38 @@
package dev.struchkov.godfather.telegram.simple.core.handler;
import dev.struchkov.godfather.main.domain.EventContainer;
import dev.struchkov.godfather.simple.context.service.EventHandler;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery;
import org.telegram.telegrambots.meta.api.objects.payments.PreCheckoutQuery;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
@Slf4j
@RequiredArgsConstructor
public class PreCheckoutQueryHandler implements EventHandler<PreCheckoutQuery> {
private final TelegramConnect telegramConnect;
@Override
public void handle(EventContainer<PreCheckoutQuery> event) {
final PreCheckoutQuery preCheckoutQuery = event.getObject();
final AnswerPreCheckoutQuery answerPreCheckoutQuery = new AnswerPreCheckoutQuery();
answerPreCheckoutQuery.setPreCheckoutQueryId(preCheckoutQuery.getId());
answerPreCheckoutQuery.setOk(true);
try {
answerPreCheckoutQuery.validate();
telegramConnect.getAbsSender().execute(answerPreCheckoutQuery);
} catch (TelegramApiException e) {
log.error(e.getMessage(), e);
}
}
@Override
public Class<PreCheckoutQuery> getEventClass() {
return PreCheckoutQuery.class;
}
}

View File

@ -4,7 +4,7 @@ import dev.struchkov.godfather.telegram.domain.attachment.DocumentAttachment;
import dev.struchkov.godfather.telegram.domain.attachment.Picture;
import dev.struchkov.godfather.telegram.domain.files.ByteContainer;
import dev.struchkov.godfather.telegram.domain.files.FileContainer;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import dev.struchkov.godfather.telegram.simple.context.service.AttachmentService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

View File

@ -1,19 +1,35 @@
package dev.struchkov.godfather.telegram.simple.core.service;
import dev.struchkov.godfather.telegram.domain.ChatAction;
import dev.struchkov.godfather.telegram.main.context.TelegramConnect;
import dev.struchkov.godfather.telegram.domain.ClientBotCommand;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramConnect;
import dev.struchkov.godfather.telegram.simple.context.service.TelegramService;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.meta.api.methods.ActionType;
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands;
import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.meta.api.methods.pinnedmessages.PinChatMessage;
import org.telegram.telegrambots.meta.api.methods.pinnedmessages.UnpinChatMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendChatAction;
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static dev.struchkov.haiti.utils.Checker.checkNotEmpty;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
import static dev.struchkov.haiti.utils.Checker.checkNull;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
public class TelegramServiceImpl implements TelegramService {
private static final Logger log = LoggerFactory.getLogger(TelegramServiceImpl.class);
@ -29,6 +45,7 @@ public class TelegramServiceImpl implements TelegramService {
final SendChatAction sendChatAction = new SendChatAction();
sendChatAction.setChatId(personId);
sendChatAction.setAction(ActionType.valueOf(chatAction.name()));
try {
absSender.execute(sendChatAction);
} catch (TelegramApiRequestException e) {
@ -66,4 +83,59 @@ public class TelegramServiceImpl implements TelegramService {
}
}
@Override
public void addCommand(@NotNull Collection<ClientBotCommand> botCommands) {
final Map<String, List<BotCommand>> commandMap = botCommands.stream()
.filter(command -> checkNotNull(command.getLang()))
.collect(
Collectors.groupingBy(
ClientBotCommand::getLang,
mapping(clientCommand -> BotCommand.builder().command(clientCommand.getKey()).description(clientCommand.getDescription()).build(), toList())
)
);
final List<@NotNull BotCommand> noLangCommands = botCommands.stream()
.filter(command -> checkNull(command.getLang()))
.map(clientCommand -> BotCommand.builder()
.command(clientCommand.getKey())
.description(clientCommand.getDescription())
.build())
.toList();
try {
if (checkNotEmpty(noLangCommands)) {
absSender.execute(SetMyCommands.builder().commands(noLangCommands).build());
}
for (Map.Entry<String, List<BotCommand>> entry : commandMap.entrySet()) {
absSender.execute(SetMyCommands.builder().languageCode(entry.getKey()).commands(entry.getValue()).build());
}
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
}
@Override
public boolean checkChatMember(@NotNull String personId, @NotNull String chatIdOrChannelId) {
final GetChatMember chatMember = GetChatMember.builder()
.userId(Long.parseLong(personId))
.chatId(chatIdOrChannelId)
.build();
try {
final ChatMember member = absSender.execute(chatMember);
if (checkNotNull(member)) {
final String status = member.getStatus();
return "member".equals(status);
}
return false;
} catch (TelegramApiRequestException e) {
log.error(e.getApiResponse());
} catch (TelegramApiException e) {
log.error(e.getMessage());
}
return false;
}
}

View File

@ -1,38 +0,0 @@
package dev.struchkov.godfather.telegram.simple.core.util;
import dev.struchkov.godfather.main.domain.content.Mail;
import dev.struchkov.godfather.telegram.domain.attachment.ButtonClickAttachment;
import dev.struchkov.godfather.telegram.main.core.util.Attachments;
import java.util.Optional;
import java.util.function.Predicate;
import static dev.struchkov.haiti.utils.Exceptions.utilityClass;
public class TriggerChecks {
private TriggerChecks() {
utilityClass();
}
public static Predicate<Mail> clickButtonRaw(String rawCallBackData) {
return mail -> {
final Optional<ButtonClickAttachment> optButtonClick = Attachments.findFirstButtonClick(mail.getAttachments());
if (optButtonClick.isPresent()) {
final ButtonClickAttachment buttonClick = optButtonClick.get();
final String rawData = buttonClick.getRawCallBackData();
return rawData.equals(rawCallBackData);
}
return false;
};
}
public static Predicate<Mail> isClickButton() {
return mail -> Attachments.findFirstButtonClick(mail.getAttachments()).isPresent();
}
public static Predicate<Mail> isLinks() {
return mail -> Attachments.findFirstLink(mail.getAttachments()).isPresent();
}
}

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-bot</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-domain</artifactId>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>dev.struchkov.godfather.telegram</groupId>
<artifactId>telegram-domain</artifactId>
<version>0.0.51-SNAPSHOT</version>
<version>1.5.3-SNAPSHOT</version>
</parent>
<artifactId>telegram-domain-main</artifactId>
@ -20,6 +20,10 @@
<groupId>dev.struchkov.godfather</groupId>
<artifactId>bot-domain-main</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package dev.struchkov.godfather.telegram.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ClientBotCommand {
private String key;
private String description;
private String lang;
}

View File

@ -2,13 +2,13 @@ package dev.struchkov.godfather.telegram.domain;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardButton;
import dev.struchkov.godfather.main.domain.keyboard.KeyBoardLine;
import dev.struchkov.godfather.main.domain.keyboard.simple.SimpleKeyBoardLine;
import dev.struchkov.godfather.telegram.domain.keyboard.SimpleKeyBoardLine;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static dev.struchkov.godfather.main.domain.keyboard.button.SimpleButton.simpleButton;
import static dev.struchkov.godfather.telegram.domain.keyboard.button.SimpleButton.simpleButton;
public final class UnitPaginationUtil {
@ -48,7 +48,7 @@ public final class UnitPaginationUtil {
* @param countElements - общее количество элементов которое может вернуть запрос
*/
public static Optional<KeyBoardLine> navigableLine(Integer currentOffset, Integer countElements) {
final SimpleKeyBoardLine.Builder lineBuilder = SimpleKeyBoardLine.builder();
final SimpleKeyBoardLine.SimpleKeyBoardLineBuilder lineBuilder = SimpleKeyBoardLine.builder();
final Optional<KeyBoardButton> optPrevButton = getPrevPageButton(currentOffset);
final Optional<KeyBoardButton> optNextButton = getNextPageButton(currentOffset, countElements);

View File

@ -0,0 +1,24 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ButtonArg {
private String type;
private String value;
public static ButtonArg buttonArg(String type, String value) {
return new ButtonArg(type, value);
}
}

View File

@ -1,6 +1,10 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import com.fasterxml.jackson.annotation.JsonIgnore;
import dev.struchkov.godfather.main.domain.content.Attachment;
import dev.struchkov.godfather.main.domain.content.Mail;
import lombok.Getter;
import lombok.Setter;
import java.util.Collection;
import java.util.HashMap;
@ -10,77 +14,46 @@ import java.util.Optional;
import static dev.struchkov.haiti.context.exception.NotFoundException.notFoundException;
import static dev.struchkov.haiti.utils.Inspector.isNotNull;
@Getter
@Setter
public class ButtonClickAttachment extends Attachment {
/**
* Идентификатор сообщения, под которым пользователь нажал кнопку.
*/
private String messageId;
private Mail maybeInaccessibleMessage;
private String rawCallBackData;
private final Map<String, Arg> args = new HashMap<>();
public String getRawCallBackData() {
return rawCallBackData;
private Map<String, ButtonArg> args = new HashMap<>();
public ButtonClickAttachment() {
super(TelegramAttachmentType.BUTTON_CLICK.name());
}
public void setRawCallBackData(String rawCallBackData) {
this.rawCallBackData = rawCallBackData;
@JsonIgnore
public Optional<Mail> getMessage() {
return Optional.ofNullable(maybeInaccessibleMessage);
}
@JsonIgnore
public void addClickArg(String type, String value) {
isNotNull(type, value);
args.put(type, new Arg(type, value));
args.put(type, ButtonArg.buttonArg(type, value));
}
public Optional<Arg> getArgByType(String type) {
@JsonIgnore
public Optional<ButtonArg> getArgByType(String type) {
isNotNull(type);
return Optional.ofNullable(args.get(type));
}
public Arg getArgByTypeOrThrow(String type) {
@JsonIgnore
public Collection<ButtonArg> getClickArgs() {
return args.values();
}
@JsonIgnore
public ButtonArg getArgByTypeOrThrow(String type) {
isNotNull(type);
return Optional.of(args.get(type)).orElseThrow(notFoundException("Аргумент типа {0} не найден.", type));
}
public Collection<Arg> getClickArgs() {
return args.values();
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public Map<String, Arg> getArgs() {
return args;
}
@Override
public String getType() {
return TelegramAttachmentType.BUTTON_CLICK.name();
}
public static class Arg {
private final String type;
private final String value;
private Arg(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
}
}

View File

@ -1,11 +1,15 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
import java.util.Optional;
import static dev.struchkov.haiti.utils.Checker.checkNotNull;
@Getter
@Setter
public class CommandAttachment extends Attachment {
private String value;
@ -13,34 +17,14 @@ public class CommandAttachment extends Attachment {
private String arg;
private String rawValue;
public void setValue(String value) {
this.value = value;
}
public void setCommandType(String commandType) {
this.commandType = commandType;
}
public void setArg(String arg) {
this.arg = arg;
}
public void setRawValue(String rawValue) {
this.rawValue = rawValue;
}
public String getValue() {
return value;
public CommandAttachment() {
super(TelegramAttachmentType.COMMAND.name());
}
public Optional<String> getArg() {
return Optional.ofNullable(arg);
}
public String getCommandType() {
return commandType;
}
public boolean isCommandType(String type) {
if (checkNotNull(type)) {
return type.equals(commandType);
@ -48,12 +32,4 @@ public class CommandAttachment extends Attachment {
return false;
}
public String getRawValue() {
return rawValue;
}
@Override
public String getType() {
return TelegramAttachmentType.COMMAND.name();
}
}

View File

@ -1,7 +1,11 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ContactAttachment extends Attachment {
private String phoneNumber;
@ -15,57 +19,8 @@ public class ContactAttachment extends Attachment {
*/
private boolean owner;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public boolean isOwner() {
return owner;
}
public void setOwner(boolean owner) {
this.owner = owner;
}
public String getVCard() {
return vCard;
}
public void setVCard(String vCard) {
this.vCard = vCard;
}
@Override
public String getType() {
return TelegramAttachmentType.CONTACT.name();
public ContactAttachment() {
super(TelegramAttachmentType.CONTACT.name());
}
}

View File

@ -1,49 +1,14 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
public class DocumentAttachment extends Attachment {
@Getter
@Setter
public class DocumentAttachment extends FileAttachment {
private String fileId;
private Long fileSize;
private String fileName;
private String mimeType;
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Override
public String getType() {
return TelegramAttachmentType.DOCUMENT.name();
public DocumentAttachment() {
super(TelegramAttachmentType.DOCUMENT.name());
}
}

View File

@ -0,0 +1,20 @@
package dev.struchkov.godfather.telegram.domain.attachment;
import dev.struchkov.godfather.main.domain.content.Attachment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class FileAttachment extends Attachment {
protected String fileId;
protected Long fileSize;
protected String mimeType;
private String fileName;
protected FileAttachment(String type) {
super(type);
}
}

Some files were not shown because too many files have changed in this diff Show More