Compare commits
130 Commits
57120eb461
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cec2f2f875 | ||
|
|
a4d0afab5d | ||
|
|
75d0e07c6d | ||
|
|
b503fec769 | ||
|
|
c9e664b4e5 | ||
|
|
e552ecbf00 | ||
|
|
ea634710f1 | ||
|
|
e784a78979 | ||
|
|
b992698b9b | ||
|
|
8d21991af6 | ||
|
|
f223ba04ae | ||
|
|
8d35bb2452 | ||
|
|
71a2471725 | ||
|
|
e93c9f9131 | ||
|
|
1abb95622a | ||
|
|
bb399a5051 | ||
|
|
c5014a8f77 | ||
|
|
f83a2d3436 | ||
|
|
2134edd841 | ||
|
|
3dd565c658 | ||
|
|
7147b785e7 | ||
|
|
f1ad32d5ae | ||
|
|
66f64da5c6 | ||
|
|
cf71cd7f6f | ||
|
|
eddbcc6277 | ||
|
|
30fb568de0 | ||
|
|
9c9e67e0a2 | ||
|
|
47e82449e7 | ||
|
|
b6ec09c5de | ||
|
|
dca58a3deb | ||
|
|
6d439a1b44 | ||
|
|
096877bee2 | ||
|
|
095cb57a18 | ||
|
|
36c79eb46c | ||
|
|
dd693bf5fb | ||
|
|
b8c3f4957c | ||
|
|
ec6c63a954 | ||
|
|
62650bd8ad | ||
|
|
8d5b5df194 | ||
|
|
0befdf6327 | ||
|
|
8e2414288b | ||
|
|
fbab0a4d88 | ||
|
|
a3f8b43f07 | ||
|
|
615213ee41 | ||
|
|
e7ef39366b | ||
|
|
3c721b905f | ||
|
|
8665a6ddda | ||
|
|
f7634a26d1 | ||
|
|
729489236f | ||
|
|
cec3ed66fb | ||
|
|
57dee8b168 | ||
|
|
5d17018490 | ||
|
|
b8fb89358e | ||
|
|
c6ce5b1421 | ||
|
|
36208a35d5 | ||
|
|
23471ee185 | ||
|
|
3a39cf8513 | ||
|
|
bca6ee8512 | ||
|
|
2af166e3e6 | ||
|
|
6735d6217a | ||
|
|
3eb3e2126d | ||
|
|
c58a571da5 | ||
|
|
efea02972c | ||
|
|
d55d35f877 | ||
|
|
c8a766881e | ||
|
|
f669186787 | ||
|
|
1991edc803 | ||
|
|
bdcd3b56e5 | ||
|
|
5d14f08084 | ||
|
|
dd67f33ec5 | ||
|
|
f4651ff915 | ||
|
|
9fc11c7cf4 | ||
|
|
04cb3d2357 | ||
|
|
e38726a1f2 | ||
|
|
79004942bd | ||
|
|
52724accee | ||
|
|
4bdaea0a42 | ||
|
|
041ab3efeb | ||
|
|
5d0fe793fd | ||
|
|
4616470584 | ||
|
|
9732e71775 | ||
|
|
626feed7db | ||
|
|
f043fe5d78 | ||
|
|
054809ad3e | ||
|
|
35148838f9 | ||
|
|
a1d238949f | ||
|
|
8a521d3f3b | ||
|
|
d32a25f93b | ||
|
|
94f37408d7 | ||
|
|
a108ebd701 | ||
|
|
f58046599c | ||
|
|
380bff679e | ||
|
|
7d3d17f807 | ||
|
|
a9c049da13 | ||
|
|
ade7cefe5a | ||
|
|
6d7830024c | ||
|
|
33616284ca | ||
|
|
d8728b383e | ||
|
|
59e8fa525a | ||
|
|
afe50154ab | ||
|
|
252bb86eb8 | ||
|
|
2b06abdbf4 | ||
|
|
083ae88386 | ||
|
|
3787bb3073 | ||
|
|
0cfecd72b3 | ||
|
|
07275c5b43 | ||
|
|
8bbe3b5d18 | ||
|
|
10fc353924 | ||
|
|
4a312e23d1 | ||
|
|
cc43141d20 | ||
|
|
642aadfd84 | ||
|
|
0327130a5d | ||
|
|
e861f5420b | ||
|
|
a9193faf12 | ||
|
|
0256f6b45b | ||
|
|
1031fe9242 | ||
|
|
63304d6bb9 | ||
|
|
ad37a349c1 | ||
|
|
25b25ade5c | ||
|
|
e448225a7b | ||
|
|
48c07b0073 | ||
|
|
ac8c0f17de | ||
|
|
4bf814c473 | ||
|
|
ba56ea72a2 | ||
|
|
c6c53d6ebf | ||
|
|
c71ba14bdc | ||
|
|
8cb69e554d | ||
|
|
97434d511b | ||
|
|
05f8990f5e | ||
|
|
621d19486d |
21
.gitignore
vendored
21
.gitignore
vendored
@@ -1,7 +1,16 @@
|
|||||||
vendor_perl
|
_Deparsed_XSubs.pm
|
||||||
data/config.json
|
.idea/**
|
||||||
data/cache
|
.vscode/**
|
||||||
data/telegrambot-brains
|
.vstags
|
||||||
data/lat
|
|
||||||
aleesa-telegram-bot.pid
|
aleesa-telegram-bot.pid
|
||||||
TODO
|
data/cache/**
|
||||||
|
data/config.json
|
||||||
|
data/fortune/**
|
||||||
|
data/friday/**
|
||||||
|
data/gamestat/**
|
||||||
|
data/image/**
|
||||||
|
data/karma/**
|
||||||
|
data/lat/**
|
||||||
|
data/proverb/**
|
||||||
|
data/telegrambot-brains/**
|
||||||
|
vendor_perl/**
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ verbose = 8
|
|||||||
|
|
||||||
[-ValuesAndExpressions::ProhibitEmptyQuotes]
|
[-ValuesAndExpressions::ProhibitEmptyQuotes]
|
||||||
# cause we consider following correct and useful: my $var = '';
|
# cause we consider following correct and useful: my $var = '';
|
||||||
# the recomended use of q{} looks too complex: my $var = q{};
|
# the recommended use of q{} looks too complex: my $var = q{};
|
||||||
|
|
||||||
[-ValuesAndExpressions::ProhibitNoisyQuotes]
|
[-ValuesAndExpressions::ProhibitNoisyQuotes]
|
||||||
# Other people, other opinions: "," is better readable than qw(,)
|
# Other people, other opinions: "," is better readable than qw(,)
|
||||||
@@ -86,3 +86,9 @@ verbose = 8
|
|||||||
# Considering this as "soft" requirement. For modules that is (or will be)
|
# Considering this as "soft" requirement. For modules that is (or will be)
|
||||||
# stand-alone libs well formed documentation is highly desired.
|
# stand-alone libs well formed documentation is highly desired.
|
||||||
lib_sections = NAME | VERSION | DESCRIPTION | AUTHOR | LICENSE AND COPYRIGHT
|
lib_sections = NAME | VERSION | DESCRIPTION | AUTHOR | LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
[-InputOutput::RequireBriefOpen]
|
||||||
|
# Yes, i do!
|
||||||
|
|
||||||
|
[-ControlStructures::ProhibitDeepNests]
|
||||||
|
# Have to use it, so fuckoff
|
||||||
|
|||||||
30
Migration.txt
Normal file
30
Migration.txt
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
Migration procedure.
|
||||||
|
|
||||||
|
When you require to perform this procedure?
|
||||||
|
- When perl version is changed
|
||||||
|
- When migration to other OS or distribution occurs
|
||||||
|
|
||||||
|
Why do i have to perform this procedure?
|
||||||
|
- Some modules are vendored with bot
|
||||||
|
- BDB can vary its on-disk format depending on dbd version that linked with
|
||||||
|
perl interpreter itself and its appropriate module.
|
||||||
|
|
||||||
|
How can i guess that i miss to perform this procedure?
|
||||||
|
Most notable symptom is 'BDB0091 DB_VERSION_MISMATCH' in logs and bot admin settings are lost.
|
||||||
|
|
||||||
|
|
||||||
|
Procedure steps.
|
||||||
|
|
||||||
|
On source system perform following steps:
|
||||||
|
1. stop the bot, to unlock and close all files.
|
||||||
|
2. make a backup
|
||||||
|
3. prepare target system and copy bot to target system
|
||||||
|
|
||||||
|
On target system perform these steps:
|
||||||
|
1. remove vendor_perl dir in bot' directory
|
||||||
|
2. run "bash bootstrap.sh" (no quotes) and wait until it successfully build and
|
||||||
|
install required modules.
|
||||||
|
3. run perl bin/cache_import.pl script. It should create cache and exit
|
||||||
|
silently.
|
||||||
|
|
||||||
|
Now it is possible to run bot without settings loss.
|
||||||
104
README.md
104
README.md
@@ -1,51 +1,99 @@
|
|||||||
# Aleesa-Telegram-bot - Simple Telegram chatty bot
|
# Aleesa-Telegram-bot - Telegram chatty bot
|
||||||
|
|
||||||
|
## Disclaimer
|
||||||
|
|
||||||
|
This version - 3 (something) - considered stable. It means that further development of new features kind of frosen.
|
||||||
|
Most effort will be targeted to future 4-th version development. If you have some ideas or fixes to this version
|
||||||
|
feel free PR them, they will be merged as soon as being reviewed.
|
||||||
|
|
||||||
## About
|
## About
|
||||||
|
|
||||||
It is based on Perl modules [Telegram::Bot][1] and [Hailo][2] as conversation
|
It is based on Perl modules [Telegram::Bot][1] and [Hailo][2] as conversation generator.
|
||||||
generator.
|
|
||||||
|
|
||||||
Config located in **data/config.json**, sample config provided as
|
I have to fork [Telegram::Bot][1] and update it according to features appeared in [Telegram Bot API v5][3]. Also,
|
||||||
**data/sample_config.json**.
|
I decide to rename it to avoid collision in the future, now it is Teapot::Bot and is bundled with bot. When lib becomes
|
||||||
|
mature enough, maybe I release it separately.
|
||||||
|
|
||||||
Bot can be run via **bin/aleesa-telegam-bot** and acts as daemon.
|
Bot config located in **data/config.json**, sample config provided as **data/sample_config.json**.
|
||||||
|
|
||||||
|
Bot can be run via **bin/aleesa-telegram-bot** and acts as daemon (double fork() and detaches stdio).
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
In order to run this application, you need to "bootstrap" it - download and build
|
Application have been tested on alpine linux x86_64 3.12, with perl-5.32.1 builtin.
|
||||||
all required dependencies and libraries.
|
|
||||||
|
|
||||||
You'll need "Development Tools" or similar group of packages, perl, perl-devel,
|
In order to run this application, you need to "bootstrap" it - download and build all required dependencies and
|
||||||
perl-local-lib, perl-app-cpanm, sqlite-devel, zlib-devel, openssl-devel,
|
libraries.
|
||||||
libdb4-devel (Berkeley DB devel), make.
|
|
||||||
|
|
||||||
After installng required dependencies it is possible to run:
|
You'll need perl-5.18 or newer, "Development Tools" or similar group of packages, perl, perl-devel, perl-local-lib,
|
||||||
|
perl-app-cpanm, sqlite-devel, zlib-devel, openssl-devel, libdb4-devel (Berkeley DB devel), make.
|
||||||
|
|
||||||
|
After installing required dependencies it is possible to run:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
||||||
bash bootstrap.sh
|
bash bootstrap.sh
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
and all libraries should be downloaded, built, tested and installed.
|
and all libraries should be downloaded, built, tested and installed.
|
||||||
|
|
||||||
## N.B.
|
## Running
|
||||||
|
|
||||||
If bot is unable to post to channel due to limited permissions, it will die.
|
This bot does not [ultilize][4] webhooks, so in order to run it only well internet connection is required, no
|
||||||
It is possible to change this behavior by patching Telegram/Bot/Brain.pm:
|
public-available ip address is needed.
|
||||||
|
|
||||||
```diff
|
### Additional Settings to be performed in order to run bot as it designed
|
||||||
--- Brain.pm 2019-07-01 04:04:17.000000000 +0300
|
|
||||||
+++ Brain.pm.new 2020-09-05 22:25:20.941373455 +0300
|
|
||||||
@@ -237,8 +237,9 @@
|
|
||||||
|
|
||||||
my $res = $self->ua->post($url, form => $form_args)->result;
|
There are some "plugins" that requires registration on third party services and API keys and secrets in order to work.
|
||||||
if ($res->is_success) { return $res->json->{result}; }
|
|
||||||
- elsif ($res->is_error) { die "Failed to post: " . $res->message; }
|
#### OpenWeatherMap
|
||||||
- else { die "Not sure what went wrong"; }
|
|
||||||
+ elsif ($res->is_error) { warn "Failed to post: " . $res->message; }
|
You should [register][5], [login][6] and [create][7] api key. Free plan have all required features to run this "plugin".
|
||||||
+ else { warn "Not sure what went wrong"; }
|
|
||||||
+ return "";
|
Once key is created you should put it in **config.json** under openweathermap section as appid. Thats it.
|
||||||
}
|
|
||||||
```
|
It is still impossible to disable this plugin, but "I'm working on it".
|
||||||
|
|
||||||
|
#### Imgur
|
||||||
|
|
||||||
|
This plugin "just exists" and is actually used nowhere around the code. Anyway, to make use of it besides registering
|
||||||
|
appropriate handler in code, you should sign in imgur and get access token.
|
||||||
|
|
||||||
|
Actually at this time this "plugin" can be stub-ed with default config values.
|
||||||
|
|
||||||
|
Anyway, to fetch access token you should [login][8] and perform [registration][9] of your app. Then you should
|
||||||
|
authorize your app according to [this][10] manual. Or [this][11] one.
|
||||||
|
|
||||||
|
#### Flickr
|
||||||
|
|
||||||
|
This "plugin" is really used to implement random picture link retrival plugins.
|
||||||
|
|
||||||
|
There is helper script in **bin/flickr_init.pl** that helps to get all required keys and secrets from flickr api.
|
||||||
|
|
||||||
|
Before using it bot must be bootstrapped via **`bootstrap.sh`**.
|
||||||
|
|
||||||
|
[Login][11] and create an [app][12] in your flickr account. Then *logout* flickr account. (It is required in order to
|
||||||
|
properly get "verifier" parameter later).
|
||||||
|
|
||||||
|
Put your [app key and secret][13] to **config.json**. Ensure that "verifier" parameter in Flickr-related part of config
|
||||||
|
either absent or commented out.
|
||||||
|
|
||||||
|
Run **bin/flickr_init.pl** first time and follow on screen instructions - copy and paste given link to browser login to
|
||||||
|
flickr account and you'll be redirected to example.com. Check address bar in browser to get so-called "verifier", put
|
||||||
|
it in **config.json**. Then run **bin/flickr_init.pl** again to store API access token in db under data/image directory
|
||||||
|
(in default config). You're done.
|
||||||
|
|
||||||
[1]: https://metacpan.org/pod/Telegram::Bot
|
[1]: https://metacpan.org/pod/Telegram::Bot
|
||||||
[2]: https://metacpan.org/pod/Hailo
|
[2]: https://metacpan.org/pod/Hailo
|
||||||
|
[3]: https://core.telegram.org/bots/api
|
||||||
|
[4]: https://core.telegram.org/bots/api#getting-updates
|
||||||
|
[5]: https://home.openweathermap.org/users/sign_up
|
||||||
|
[6]: https://home.openweathermap.org/users/sign_in
|
||||||
|
[7]: https://home.openweathermap.org/api_keys
|
||||||
|
[8]: https://imgur.com/signin
|
||||||
|
[9]: https://api.imgur.com/oauth2/addclient
|
||||||
|
[10]: https://apidocs.imgur.com/#authorization-and-oauth
|
||||||
|
[11]: https://identity.flickr.com/login
|
||||||
|
[12]: https://www.flickr.com/services/apps/create/apply/
|
||||||
|
[13]: https://www.flickr.com/services/api/keys/
|
||||||
|
|||||||
104
README_RU.md
Normal file
104
README_RU.md
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
# Aleesa-Telegram-bot - Болтливый бот для Telegram
|
||||||
|
|
||||||
|
## Дисклеймер
|
||||||
|
|
||||||
|
Эта версия бота за номером 3 (с мелочью) стабильная. Сие означает, что дальнейшего развития функций в этой версии не
|
||||||
|
предполагается. Конечно, возможны исключения, но основной план - переключиться на 4-ю версию, куда планируется
|
||||||
|
перенести большинство функций 3-й версии.
|
||||||
|
|
||||||
|
Если у кого-то возникнут идеи относительно этой версии бота - ставьте PR, я только рад. Т.к. несмотря на то, что
|
||||||
|
развитие этой версии "слегка" заморожено, поддерживать её планируется как минимум до выхода в свет 4-й версии бота.
|
||||||
|
|
||||||
|
## Что это такое
|
||||||
|
|
||||||
|
Это бот, основанный на перловых модулях [Telegram::Bot][1] для работы в мессенджере Telegram и [Hailo][2] для генерации
|
||||||
|
"умной" беседы.
|
||||||
|
|
||||||
|
Для корректной работы, пришлось форкнуть [Telegram::Bot][1], чтобы обновить интерфейс API до [Telegram Bot API v5][3].
|
||||||
|
Для избежания неоднозначностей, модуль пришлось переименовать и теперь он идёт в составе бота. Возможно, когда модуль
|
||||||
|
отлежится и будет похож на стабильный, он стнет самостоятельным и поселится на metacpan.org
|
||||||
|
|
||||||
|
Конфиг бота должен лежать в **data/config.json**. Пример конфига расположен в **data/sample_config.json**.
|
||||||
|
|
||||||
|
Бота можно запустить через **bin/aleesa-telegram-bot** и он взлетит, как юниксовый демон (сделает двойной fork() и
|
||||||
|
отцепится от stdio).
|
||||||
|
|
||||||
|
## Установка
|
||||||
|
|
||||||
|
Приложение тестировалось на alpine linux x86_64 3.12, со встроенным perl-5.32.1.
|
||||||
|
|
||||||
|
Чтобы запустить приложение, его надо "забурстрапить" - загрузить и собрать все необходимые зависимости.
|
||||||
|
|
||||||
|
Понадобится perl-5.18, а желательно новее, "Development Tools" или подобная группа пакетов , perl, perl-devel,
|
||||||
|
perl-local-lib, perl-app-cpanm, sqlite-devel, zlib-devel, openssl-devel, libdb4-devel (Berkeley DB devel), make.
|
||||||
|
|
||||||
|
После установки этих пакетов, можно будет запустить:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
|
||||||
|
bash bootstrap.sh
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
и, по идее, всё что нужно будет выкачено, собрано и разложено куда надо.
|
||||||
|
|
||||||
|
## Запуск и работа
|
||||||
|
|
||||||
|
Бот не использует [вебхуки][4], поэтому ничего дополнительного, кроме хорошего подключения к интернету ему не нужно.
|
||||||
|
|
||||||
|
### Дополнительные настройки
|
||||||
|
|
||||||
|
Некоторые "плагины" требуют регистрации в сторонних сервисах (API keys, secrets итд), чтобы бот не сыпал ошибками в
|
||||||
|
логи (возможно, в дальнейшем возможно будет отключить эти плагины).
|
||||||
|
|
||||||
|
#### OpenWeatherMap
|
||||||
|
|
||||||
|
Для работы погодного плагина, надо [заргистрироваться][5], [залогиниться][6] и [создать][7] api key. Free plan
|
||||||
|
предлагает всё необхдимое для работы "плагина".
|
||||||
|
|
||||||
|
Когда api key будет создан, его нужно вписать в **config.json** "секцию" openweathermap в качестве appid. На этом всё.
|
||||||
|
|
||||||
|
#### Imgur
|
||||||
|
|
||||||
|
Этот плагин "просто есть" и его на самом деле ничто и никто не использует. И в этой связи все настройки плагина можно
|
||||||
|
оставить "как есть" в примере конфига.
|
||||||
|
|
||||||
|
Тем не менее, если есть большое желание, то можно [залогиниться][8] и [зарегистрировать][9] бота как приложение, а
|
||||||
|
потом разрешить приложению пользоваться API-шкой, как описано в [этом][10] или [этом][11] мануале.
|
||||||
|
|
||||||
|
#### Flickr
|
||||||
|
|
||||||
|
Этот "плагин" действительно используется для добычи ссылок на картинки в разных "картиночных" командах бота.
|
||||||
|
|
||||||
|
Есть скрипт, который поможет с регистрацией приложения в api Flickr - **bin/flickr_init.pl**, он достанет все нужные
|
||||||
|
ключи и секреты к ним.
|
||||||
|
|
||||||
|
До запуска этого скрипта, бот должен быть забутстраплен через **`bootstrap.sh`**.
|
||||||
|
|
||||||
|
[Залогиньтесь][11] и создайте [app][12] in своём Flicker-овском аккаунте. Далее, *разлогиньтесь*, это нужно, чтобы
|
||||||
|
потом проще было достать параметр verifier.
|
||||||
|
|
||||||
|
Запишите [app key и secret][13] в **config.json**. Удостоверьтесь, что параметр "verifier" в конфиге либо закоменчен,
|
||||||
|
либо отсутствует.
|
||||||
|
|
||||||
|
Запустите **bin/flickr_init.pl** и следуте предлагаемым инструкциям - в итоге будет дана ссылка, которую надо
|
||||||
|
скопипастить в браузер. По ссылке предложат залогиниться, далее надо будет разрешить приложению просматривать профиль
|
||||||
|
и, через один-два редиректа, вы попадёте на example.com. Из адресной строки браузера надо скопировать параметр
|
||||||
|
"verifier" и вписать его в **config.json**.
|
||||||
|
|
||||||
|
Чтобы сохранить в бд плагина API access token для нормальной работы "плагина", второй раз запустите
|
||||||
|
**bin/flickr_init.pl**. На этом всё.
|
||||||
|
|
||||||
|
[1]: https://metacpan.org/pod/Telegram::Bot
|
||||||
|
[2]: https://metacpan.org/pod/Hailo
|
||||||
|
[3]: https://core.telegram.org/bots/api
|
||||||
|
[4]: https://core.telegram.org/bots/api#getting-updates
|
||||||
|
[5]: https://home.openweathermap.org/users/sign_up
|
||||||
|
[6]: https://home.openweathermap.org/users/sign_in
|
||||||
|
[7]: https://home.openweathermap.org/api_keys
|
||||||
|
[8]: https://imgur.com/signin
|
||||||
|
[9]: https://api.imgur.com/oauth2/addclient
|
||||||
|
[10]: https://apidocs.imgur.com/#authorization-and-oauth
|
||||||
|
[11]: https://identity.flickr.com/login
|
||||||
|
[12]: https://www.flickr.com/services/apps/create/apply/
|
||||||
|
[13]: https://www.flickr.com/services/api/keys/
|
||||||
@@ -4,40 +4,55 @@ use 5.018;
|
|||||||
use strict;
|
use strict;
|
||||||
use warnings;
|
use warnings;
|
||||||
use utf8;
|
use utf8;
|
||||||
use open qw(:std :utf8);
|
use open qw (:std :utf8);
|
||||||
use English qw( -no_match_vars );
|
use English qw ( -no_match_vars );
|
||||||
|
|
||||||
use version; our $VERSION = qw(1.0);
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
my $workdir;
|
my $workdir;
|
||||||
|
|
||||||
# before we run, change working dir
|
# before we run, change working dir
|
||||||
BEGIN {
|
BEGIN {
|
||||||
use Cwd qw(chdir abs_path);
|
use Cwd qw (chdir abs_path);
|
||||||
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
|
||||||
|
if ($#CWD > 1) {
|
||||||
|
$#CWD = $#CWD - 2;
|
||||||
|
}
|
||||||
|
|
||||||
$workdir = join '/', @CWD;
|
$workdir = join '/', @CWD;
|
||||||
chdir $workdir;
|
chdir $workdir;
|
||||||
}
|
}
|
||||||
|
|
||||||
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
no Cwd;
|
no Cwd;
|
||||||
use Cwd::utf8 qw(chdir abs_path);
|
use Cwd::utf8 qw (chdir abs_path);
|
||||||
use POSIX qw(setgid setuid setsid);
|
use File::Basename qw (basename dirname);
|
||||||
use File::Path qw(make_path);
|
use File::Path qw (make_path);
|
||||||
use File::Basename qw(basename dirname);
|
use Log::Any qw ($log);
|
||||||
use conf qw(loadConf);
|
use Log::Any::Adapter;
|
||||||
use botlib qw(logger);
|
use Log::Any::For::Std;
|
||||||
use telegrambot qw(run_telegrambot);
|
use POSIX qw (setgid setuid setsid);
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use TelegramBot qw (RunTelegramBot);
|
||||||
|
|
||||||
sub daemonize;
|
sub daemonize;
|
||||||
sub __fork;
|
sub __fork;
|
||||||
|
sub __signal_handler;
|
||||||
|
|
||||||
local $OUTPUT_AUTOFLUSH = 1;
|
local $OUTPUT_AUTOFLUSH = 1;
|
||||||
my $runAsUid = $UID;
|
my $runAsUid = $UID;
|
||||||
|
|
||||||
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
|
my $piddir = '/var/run/' . basename (abs_path ($PROGRAM_NAME));
|
||||||
my $C = loadConf ();
|
my $C = LoadConf ();
|
||||||
|
my $loglevel = $C->{'loglevel'} // 'notice';
|
||||||
|
my $logfile;
|
||||||
|
|
||||||
|
if (defined $C->{'log'}) {
|
||||||
|
$logfile = $C->{'log'};
|
||||||
|
} elsif (defined $C->{'debug_log'}) {
|
||||||
|
$logfile = $C->{'debug_log'};
|
||||||
|
}
|
||||||
|
|
||||||
# if we run under root, create pid dir and set correct owner for it, same for debug log if it is defined
|
# if we run under root, create pid dir and set correct owner for it, same for debug log if it is defined
|
||||||
if ($UID == 0) {
|
if ($UID == 0) {
|
||||||
@@ -58,14 +73,16 @@ if ($UID == 0) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($C->{'debug_log'}) {
|
if (defined $logfile) {
|
||||||
unless (-d dirname ($C->{'debug_log'})) {
|
my $logdir = dirname $logfile;
|
||||||
|
|
||||||
|
unless (-d $logdir) {
|
||||||
make_path (
|
make_path (
|
||||||
dirname ($C->{'debug_log'}), {
|
$logdir, {
|
||||||
uid => $uid,
|
uid => $uid,
|
||||||
group => $gid
|
group => $gid
|
||||||
}
|
}
|
||||||
);
|
) or die "Unable to create $logdir: $OS_ERROR\n";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +93,24 @@ if ($UID == 0) {
|
|||||||
$piddir = $workdir;
|
$piddir = $workdir;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (defined $logfile) {
|
||||||
|
Log::Any::Adapter->set ('File', $logfile, log_level => $loglevel);
|
||||||
|
|
||||||
|
# Some annoying CHI logging events come with category set to CHI::Driver and log_level set to debug.
|
||||||
|
# Until we use start using Log::Any native features and set whole loglevel accordingly, lets lower
|
||||||
|
# verbosity paticulary for CHI.
|
||||||
|
Log::Any::Adapter->set (
|
||||||
|
{
|
||||||
|
category => 'CHI::Driver'
|
||||||
|
},
|
||||||
|
'File',
|
||||||
|
$logfile,
|
||||||
|
log_level => 'warn'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
Log::Any::Adapter->set ('File', '/dev/null');
|
||||||
|
}
|
||||||
|
|
||||||
# double fork attach to /dev/null all stdio and go background
|
# double fork attach to /dev/null all stdio and go background
|
||||||
daemonize ();
|
daemonize ();
|
||||||
|
|
||||||
@@ -83,22 +118,34 @@ daemonize ();
|
|||||||
my $apath = abs_path $PROGRAM_NAME;
|
my $apath = abs_path $PROGRAM_NAME;
|
||||||
|
|
||||||
unless (defined $apath) {
|
unless (defined $apath) {
|
||||||
logger "Unable to get abs_path: $OS_ERROR";
|
$log->fatal ("[FATAL] Unable to get abs_path: $OS_ERROR\n");
|
||||||
die "Unable to get abs_path: $OS_ERROR\n";
|
exit 1;
|
||||||
};
|
};
|
||||||
|
|
||||||
# write pidfile
|
# write pidfile
|
||||||
my $pidfile = sprintf '%s/%s.pid', $piddir, basename $apath;
|
my $pidfile = sprintf '%s/%s.pid', $piddir, basename $apath;
|
||||||
logger "Creating pidfile at $pidfile";
|
$log->info ("[INFO] Creating pidfile at $pidfile");
|
||||||
open my $MYPID, '>', $pidfile or die "Error opening $pidfile: $OS_ERROR\n";
|
|
||||||
print {$MYPID} $PID or die "Error writing to $pidfile: $OS_ERROR\n";
|
open my $MYPID, '>', $pidfile or do {
|
||||||
|
$log->fatal ("[FATAL] Error opening $pidfile: $OS_ERROR");
|
||||||
|
exit 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
print {$MYPID} $PID or do {
|
||||||
|
$log->fatal ("[FATAL] Error writing to $pidfile: $OS_ERROR");
|
||||||
|
exit 1;
|
||||||
|
};
|
||||||
|
|
||||||
close $MYPID; ## no critic (InputOutput::RequireCheckedSyscalls
|
close $MYPID; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
|
|
||||||
|
local $SIG{INT} = \&__signal_handler;
|
||||||
|
local $SIG{TERM} = \&__signal_handler;
|
||||||
|
|
||||||
# set correct proctitle
|
# set correct proctitle
|
||||||
$PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars)
|
$PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars)
|
||||||
|
|
||||||
# run bot, at last
|
# run bot, at last
|
||||||
run_telegrambot ();
|
RunTelegramBot ();
|
||||||
|
|
||||||
if (-f $pidfile) {
|
if (-f $pidfile) {
|
||||||
unlink $pidfile;
|
unlink $pidfile;
|
||||||
@@ -110,8 +157,9 @@ sub daemonize {
|
|||||||
__fork ();
|
__fork ();
|
||||||
POSIX::setsid ();
|
POSIX::setsid ();
|
||||||
open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
open STDOUT, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
# we handle STDOUT && STDERR via Log::Any::For::Std, so do not close them explicitly
|
||||||
open STDERR, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
#open STDOUT, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
|
#open STDERR, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
__fork ();
|
__fork ();
|
||||||
umask 0;
|
umask 0;
|
||||||
return;
|
return;
|
||||||
@@ -119,10 +167,28 @@ sub daemonize {
|
|||||||
|
|
||||||
sub __fork {
|
sub __fork {
|
||||||
my $pid = fork;
|
my $pid = fork;
|
||||||
unless (defined $pid) { die "Can't fork: $OS_ERROR\n"; }
|
|
||||||
exit if ($pid != 0);
|
unless (defined $pid) {
|
||||||
|
$log->fatal ("[FATAL] Can't fork: $OS_ERROR");
|
||||||
|
exit 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($pid != 0) {
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sub __signal_handler {
|
||||||
|
$log->info ("[INFO] Caught a signal $OS_ERROR");
|
||||||
|
|
||||||
|
if (-f $pidfile) {
|
||||||
|
unlink $pidfile;
|
||||||
|
}
|
||||||
|
|
||||||
|
exit 0;
|
||||||
|
}
|
||||||
|
|
||||||
__END__
|
__END__
|
||||||
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
|
|||||||
106
bin/cache_export.pl
Normal file
106
bin/cache_export.pl
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use File::Basename qw (dirname);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use JSON::XS;
|
||||||
|
use Encode;
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
my $datadir = dirname $cachedir;
|
||||||
|
my $export = 0;
|
||||||
|
my $exportInst = 0;
|
||||||
|
|
||||||
|
sub dumpCache {
|
||||||
|
my $namespace = shift;
|
||||||
|
my $cacheExportDir = sprintf '%s/cacheexport', $datadir;
|
||||||
|
|
||||||
|
unless (-d $cacheExportDir) {
|
||||||
|
make_path ($cacheExportDir) || die "Unable to create $cacheExportDir: $OS_ERROR\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
my $filename = sprintf '%s/%s', $cacheExportDir, $exportInst;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => $namespace
|
||||||
|
);
|
||||||
|
|
||||||
|
my $j;
|
||||||
|
my $writefile = 0;
|
||||||
|
|
||||||
|
foreach my $k ($cache->get_keys ()) {
|
||||||
|
$k = decode ('UTF-8', $k);
|
||||||
|
$j->{$k} = decode ('UTF-8', $cache->get ($k));
|
||||||
|
$writefile = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($writefile) {
|
||||||
|
say "Dumping $namespace"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
my $jsonencoder = JSON::XS->new->pretty ();
|
||||||
|
open (my $FILE, '>', $filename) or die "Unable to dump cache namespace $namespace to $filename: $OS_ERROR\n";
|
||||||
|
print $FILE $jsonencoder->encode ($j) or die "Unable to dump cache namespace $namespace to $filename: $OS_ERROR\n";;
|
||||||
|
close $FILE; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
my $EXPORTFD;
|
||||||
|
|
||||||
|
if ($export) {
|
||||||
|
open ($EXPORTFD, '>>', "$cacheExportDir/exportfiles.txt") or die "Unable to open for appending $cacheExportDir/exportfiles.txt: $OS_ERROR\n";
|
||||||
|
} else {
|
||||||
|
open ($EXPORTFD, '>', "$cacheExportDir/exportfiles.txt") or die "Unable to create $cacheExportDir/exportfiles.txt: $OS_ERROR\n";
|
||||||
|
$export = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf ($EXPORTFD "%s,%s\n", $namespace, $filename) or die "Unable to write to $cacheExportDir/exportfiles.txt: $OS_ERROR\n";
|
||||||
|
close $EXPORTFD; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
$exportInst++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
opendir (my $DIR, $cachedir) or die "Unable to open $cachedir: $OS_ERROR\n";
|
||||||
|
|
||||||
|
while (readdir $DIR) {
|
||||||
|
if (/^BotLib\+3a\+3aAdmin_censor_(.+)\.db$/) {
|
||||||
|
dumpCache ("BotLib::Admin_censor_$1");
|
||||||
|
} elsif (/^BotLib\+3a\+3aAdmin_fortune.db$/) {
|
||||||
|
dumpCache ('BotLib::Admin_fortune');
|
||||||
|
} elsif (/BotLib\+3a\+3aAdmin_plugin_(.+)\.db$/) {
|
||||||
|
dumpCache ("BotLib::Admin_plugin_$1");
|
||||||
|
} elsif (/BotLib\+3a\+3aAdmin_(.+)\.db$/) {
|
||||||
|
dumpCache ("BotLib::Admin_$1");
|
||||||
|
} elsif (/^BotLib\+3a\+3aImage\+3a\+3aFlickr\.db$/) {
|
||||||
|
dumpCache ('BotLib::Image::Flickr');
|
||||||
|
} elsif (/^BotLib\+3a\+3aKarma_(.+)\.db$/) {
|
||||||
|
dumpCache ("BotLib::Karma_$1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
closedir $DIR;
|
||||||
|
exit 0;
|
||||||
|
|
||||||
86
bin/cache_import.pl
Normal file
86
bin/cache_import.pl
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use File::Basename qw (dirname);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use JSON::XS;
|
||||||
|
use Encode;
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
my $datadir = dirname $cachedir;
|
||||||
|
my $export = 0;
|
||||||
|
|
||||||
|
sub createCache {
|
||||||
|
my $namespace = shift;
|
||||||
|
my $filename = shift;
|
||||||
|
say "Creating $namespace from $filename"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => $namespace
|
||||||
|
);
|
||||||
|
|
||||||
|
open my $FH, '<', $filename or die "Unable to open $filename: $OS_ERROR\n";
|
||||||
|
binmode $FH;
|
||||||
|
my $len = (stat $filename) [7];
|
||||||
|
my $json;
|
||||||
|
use bytes;
|
||||||
|
my $readlen = read $FH, $json, $len;
|
||||||
|
no bytes;
|
||||||
|
|
||||||
|
unless ($readlen) {
|
||||||
|
close $FH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
|
die "Unable to read $filename: $OS_ERROR\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($readlen != $len) {
|
||||||
|
close $FH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
|
die "File $filename is $len bytes on disk, but we read only $readlen bytes\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
close $FH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
|
my $j = JSON::XS->new->utf8->relaxed;
|
||||||
|
my $dump = $j->decode ($json);
|
||||||
|
|
||||||
|
foreach my $key (keys (%{$dump})) {
|
||||||
|
$cache->set ($key, $dump->{$key}, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
open (my $FH, '<', "$datadir/cacheexport/exportfiles.txt") or die "Unable to open $datadir/cacheexport/exportfiles.txt: $OS_ERROR\n";
|
||||||
|
|
||||||
|
while (<$FH>) {
|
||||||
|
chomp;
|
||||||
|
my ($namespace, $filename) = split /\,/, $_, 2;
|
||||||
|
createCache ($namespace, $filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
close $FH; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
exit 0;
|
||||||
32
bin/flickr.pl
Normal file
32
bin/flickr.pl
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Image::Flickr qw (FlickrByTags);
|
||||||
|
|
||||||
|
my $url = FlickrByTags ('bird,owl');
|
||||||
|
|
||||||
|
if ($url) {
|
||||||
|
say $url; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
exit 0;
|
||||||
|
} else {
|
||||||
|
exit 1;
|
||||||
|
}
|
||||||
29
bin/flickr_init.pl
Normal file
29
bin/flickr_init.pl
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Image::Flickr qw (FlickrInit);
|
||||||
|
|
||||||
|
if (FlickrInit ()) {
|
||||||
|
exit 0;
|
||||||
|
} else {
|
||||||
|
exit 1;
|
||||||
|
}
|
||||||
29
bin/flickr_test.pl
Normal file
29
bin/flickr_test.pl
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Image::Flickr qw (FlickrTestLogin);
|
||||||
|
|
||||||
|
if (FlickrTestLogin ()) {
|
||||||
|
exit 0;
|
||||||
|
} else {
|
||||||
|
exit 1;
|
||||||
|
}
|
||||||
26
bin/fortune_seed.pl
Normal file
26
bin/fortune_seed.pl
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Fortune qw (Seed);
|
||||||
|
|
||||||
|
Seed ();
|
||||||
|
exit 0;
|
||||||
26
bin/friday_seed.pl
Normal file
26
bin/friday_seed.pl
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Friday qw (Seed);
|
||||||
|
|
||||||
|
Seed ();
|
||||||
|
exit 0;
|
||||||
26
bin/gamedata_seed.pl
Normal file
26
bin/gamedata_seed.pl
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Gamestat qw (SeedArtifacts);
|
||||||
|
|
||||||
|
SeedArtifacts ();
|
||||||
|
exit 0;
|
||||||
26
bin/proverb_seed.pl
Normal file
26
bin/proverb_seed.pl
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/perl
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
|
my $workdir;
|
||||||
|
|
||||||
|
# before we run, change working dir
|
||||||
|
BEGIN {
|
||||||
|
use Cwd qw (chdir abs_path);
|
||||||
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
|
$workdir = join '/', @CWD;
|
||||||
|
chdir $workdir;
|
||||||
|
}
|
||||||
|
|
||||||
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
|
use BotLib::Proverb qw (Seed);
|
||||||
|
|
||||||
|
Seed ();
|
||||||
|
exit 0;
|
||||||
@@ -4,16 +4,15 @@ use 5.018;
|
|||||||
use strict;
|
use strict;
|
||||||
use warnings;
|
use warnings;
|
||||||
use utf8;
|
use utf8;
|
||||||
use open qw(:std :utf8);
|
use open qw (:std :utf8);
|
||||||
use English qw( -no_match_vars );
|
use English qw ( -no_match_vars );
|
||||||
use vars qw/$VERSION/;
|
use version; our $VERSION = qw (1.0);
|
||||||
$VERSION = '1.0';
|
|
||||||
|
|
||||||
my $workdir;
|
my $workdir;
|
||||||
|
|
||||||
# before we run, change working dir
|
# before we run, change working dir
|
||||||
BEGIN {
|
BEGIN {
|
||||||
use Cwd qw(chdir abs_path);
|
use Cwd qw (chdir abs_path);
|
||||||
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
|
||||||
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
if ($#CWD > 1) { $#CWD = $#CWD - 2; }
|
||||||
$workdir = join '/', @CWD;
|
$workdir = join '/', @CWD;
|
||||||
@@ -21,7 +20,7 @@ BEGIN {
|
|||||||
}
|
}
|
||||||
|
|
||||||
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
use lib ("$workdir/lib", "$workdir/vendor_perl", "$workdir/vendor_perl/lib/perl5");
|
||||||
use lat qw(train);
|
use BotLib::Lat qw (Train);
|
||||||
|
|
||||||
train ();
|
Train ();
|
||||||
exit 0;
|
exit 0;
|
||||||
|
|||||||
21
confcheck.pl
21
confcheck.pl
@@ -4,16 +4,16 @@ use 5.018;
|
|||||||
use strict;
|
use strict;
|
||||||
use warnings;
|
use warnings;
|
||||||
use utf8;
|
use utf8;
|
||||||
use open qw(:std :utf8);
|
use open qw (:std :utf8);
|
||||||
use English qw( -no_match_vars );
|
use English qw ( -no_match_vars );
|
||||||
use lib qw(./lib ./vendor_perl ./vendor_perl/lib/perl5);
|
use lib qw (./lib ./vendor_perl ./vendor_perl/lib/perl5);
|
||||||
use JSON::PP;
|
use JSON::XS;
|
||||||
|
|
||||||
use version; our $VERSION = qv(1.0);
|
use version; our $VERSION = qw (1.0);
|
||||||
|
|
||||||
my $c = 'data/config.json';
|
my $c = 'data/config.json';
|
||||||
open (my $C, '<', $c) or die "No conf at $c: $OS_ERROR\n"; ## no critic (InputOutput::RequireBriefOpen)
|
open (my $C, '<', $c) or die "No conf at $c: $OS_ERROR\n";
|
||||||
my $len = (stat ($c)) [7];
|
my $len = (stat $c) [7];
|
||||||
my $json;
|
my $json;
|
||||||
my $readlen = read ($C, $json, $len);
|
my $readlen = read ($C, $json, $len);
|
||||||
|
|
||||||
@@ -28,9 +28,10 @@ if ($readlen != $len) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
close C; ## no critic (InputOutput::RequireCheckedSyscalls)
|
close C; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
$c = decode_json ($json);
|
$c = JSON::XS->new->utf8->relaxed;
|
||||||
|
my $data = $c->decode ($json);
|
||||||
|
|
||||||
my $j = JSON::PP->new->pretty->canonical->indent_length (4); ## no critic (ValuesAndExpressions::ProhibitLongChainsOfMethodCalls)
|
my $j = JSON::XS->new->pretty();
|
||||||
print $j->encode ($c); ## no critic (InputOutput::RequireCheckedSyscalls)
|
print $j->encode ($data); ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
|
||||||
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
|
|||||||
61
cpanfile
61
cpanfile
@@ -1,22 +1,39 @@
|
|||||||
requires 'Carp';
|
## no critic (TestingAndDebugging::RequireUseStrict,Modules::RequireVersionVar)
|
||||||
requires 'Cwd::utf8';
|
## no critic (TestingAndDebugging::RequireUseWarnings,Modules::RequireExplicitPackage)
|
||||||
requires 'DB_File';
|
## no critic (Modules::RequireEndWithOne)
|
||||||
requires 'Digest::MD5';
|
requires 'Carp', '==1.50';
|
||||||
requires 'Data::Dumper';
|
requires 'CHI', '==0.61';
|
||||||
requires 'File::Basename';
|
requires 'CHI::Driver::BerkeleyDB', '==0.05';
|
||||||
requires 'File::Path';
|
requires 'Cwd::utf8', '==0.011';
|
||||||
requires 'Hailo';
|
requires 'DateTime', '==1.55';
|
||||||
requires 'HTTP::Tiny';
|
requires 'DB_File', '==1.856';
|
||||||
requires 'IO::Socket::SSL';
|
requires 'SQLite_File', '==0.1006';
|
||||||
requires 'JSON';
|
requires 'DBI', '==1.643';
|
||||||
requires 'JSON::PP';
|
requires 'DBD::SQLite', '==1.70';
|
||||||
requires 'JSON::XS';
|
requires 'Digest::HMAC_SHA1', '==1.04';
|
||||||
requires 'List::Util';
|
requires 'Digest::MD5', '==2.58';
|
||||||
requires 'local::lib';
|
requires 'Data::Dumper', '==2.183';
|
||||||
requires 'Log::Any';
|
requires 'Digest::SHA', '==6.02';
|
||||||
requires 'Mojo::Base';
|
requires 'File::Basename', '==2.85';
|
||||||
requires 'Mojo::IOLoop';
|
requires 'File::Path', '==2.18';
|
||||||
requires 'Mojo::UserAgent';
|
requires 'Hailo', '==0.75';
|
||||||
#requires 'Telegram::Bot';
|
requires 'HTML::TokeParser', '==3.76';
|
||||||
#requires 'Test::Exception';
|
requires 'IO::Socket::SSL', '==2.074';
|
||||||
requires 'URI::URL';
|
requires 'JSON', '==4.05';
|
||||||
|
requires 'JSON::PP', '==4.07';
|
||||||
|
requires 'JSON::XS', '==4.03';
|
||||||
|
requires 'List::Util', '==1.60';
|
||||||
|
requires 'local::lib', '==2.000028';
|
||||||
|
requires 'Log::Any', '==1.710';
|
||||||
|
requires 'Log::Any::Adapter', '==1.710';
|
||||||
|
requires 'Log::Any::For::Std', '==0.05';
|
||||||
|
requires 'Math::Random::Secure', '==0.080001';
|
||||||
|
requires 'Mojolicious', '==9.22';
|
||||||
|
requires 'Mojo::Base', '0';
|
||||||
|
requires 'Mojo::IOLoop', '0';
|
||||||
|
requires 'Mojo::UserAgent', '0';
|
||||||
|
requires 'Mojo::UserAgent::Cached', '==1.18';
|
||||||
|
requires 'String::Random', '==0.32';
|
||||||
|
requires 'Text::Fuzzy', '==0.29';
|
||||||
|
requires 'URI::Encode::XS', '==0.11';
|
||||||
|
requires 'URI::URL', '==5.10';
|
||||||
|
|||||||
54
data/archeologic_artifacts.txt
Normal file
54
data/archeologic_artifacts.txt
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
амулет Мерлина
|
||||||
|
библиотеку Ивана Грозного
|
||||||
|
деревянную плошку
|
||||||
|
диплока
|
||||||
|
доски Ноева Ковчега
|
||||||
|
древний презерватив из бараньей кишки
|
||||||
|
икону
|
||||||
|
инсталятор Windows 3.11
|
||||||
|
истлевший гроб
|
||||||
|
каменный топор
|
||||||
|
клад со златом-серебром
|
||||||
|
кривой нож
|
||||||
|
ледяную глыбу
|
||||||
|
лунный грунт
|
||||||
|
мамонта
|
||||||
|
мамонтёнка
|
||||||
|
метеорит
|
||||||
|
мумию фараона Тутанхамона
|
||||||
|
носки прапорщика (поставит в угол)
|
||||||
|
обломки грузинской керамики
|
||||||
|
птеродактиля
|
||||||
|
рубль с Лениным
|
||||||
|
рыцарские доспехи
|
||||||
|
синий мох
|
||||||
|
скелет
|
||||||
|
скелет собаки по кличке Беня
|
||||||
|
тиранозавтра
|
||||||
|
тотем индейцев
|
||||||
|
трубу с туркменским газом
|
||||||
|
скорбь еврейского народа
|
||||||
|
залежи активированного угля
|
||||||
|
не очень новый завет
|
||||||
|
мать леннарта поттеринга
|
||||||
|
руководство "начинающему археологу"
|
||||||
|
слово о полку игореве и дело о полку игореве, вместе с игорем
|
||||||
|
телепрограмму канала A-one
|
||||||
|
могилу искателя могил
|
||||||
|
заплесневевший кусок хлеба
|
||||||
|
преемник радиоприемника
|
||||||
|
глушитель от ВАЗ-2106
|
||||||
|
чувство удовлетворения
|
||||||
|
крота
|
||||||
|
воспоминания о былой любви
|
||||||
|
грязистор
|
||||||
|
египетское мумиё
|
||||||
|
окаменелый камень
|
||||||
|
кладку яиц рептилоида
|
||||||
|
яму
|
||||||
|
чеснок и стрелы
|
||||||
|
доллар по 30
|
||||||
|
несмазанные скрижали
|
||||||
|
четырелобита
|
||||||
|
чучело тролля
|
||||||
|
целое ничего
|
||||||
47
data/fisher_artifacts.txt
Normal file
47
data/fisher_artifacts.txt
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
семикрылого чешуйчатого пятихуя
|
||||||
|
разумного конденсатора
|
||||||
|
сальмонеллу
|
||||||
|
селёдку
|
||||||
|
желтоперого тунца
|
||||||
|
розовую сальмонеллу
|
||||||
|
голавля
|
||||||
|
барбуса
|
||||||
|
окуня
|
||||||
|
верхоплавку
|
||||||
|
коричневую форель
|
||||||
|
полярника
|
||||||
|
плотву
|
||||||
|
зубатку
|
||||||
|
солнечную рыбу
|
||||||
|
старую шину
|
||||||
|
скользкую корягу
|
||||||
|
лампу джина
|
||||||
|
любовное послание в бутылке
|
||||||
|
старое бревно
|
||||||
|
резиновый сапог
|
||||||
|
труп
|
||||||
|
Лох-Несское чудовище
|
||||||
|
старую рыбацкую приманку
|
||||||
|
кусок Титаника
|
||||||
|
обломок Атлантиды
|
||||||
|
кита
|
||||||
|
кальмара
|
||||||
|
дельфина
|
||||||
|
ската
|
||||||
|
подводную лодку
|
||||||
|
медузу
|
||||||
|
морскую звезду
|
||||||
|
электрического угря
|
||||||
|
большую белую акулу
|
||||||
|
аквалангиста
|
||||||
|
монстра
|
||||||
|
вируса
|
||||||
|
сырую пачку сигарет
|
||||||
|
водоросли
|
||||||
|
якорь от лодки
|
||||||
|
водяного
|
||||||
|
русалку
|
||||||
|
палтуса
|
||||||
|
труп собаки по кличке Беня
|
||||||
|
олигофрена Проню
|
||||||
|
огеймера Фишкина
|
||||||
521
data/fortune_src/citates
Normal file
521
data/fortune_src/citates
Normal file
@@ -0,0 +1,521 @@
|
|||||||
|
Что сказал Берлиоз своей музыкой? - ничего; но как потрясающе он это
|
||||||
|
сказал.
|
||||||
|
-- Джеймс Гиббонз Хьюнекер
|
||||||
|
%
|
||||||
|
Музыка будет по-немецки, вы не поймете.
|
||||||
|
-- Оскар Уайльд
|
||||||
|
%
|
||||||
|
Четвертый раз смотрю этот фильм и должна вам сказать, что сегодня актеры
|
||||||
|
играли как никогда.
|
||||||
|
-- Фаина Раневская
|
||||||
|
%
|
||||||
|
Продолжительность фильма определяется выносливостью мочевого пузыря
|
||||||
|
обычного зрителя.
|
||||||
|
-- Альфред Хичкок
|
||||||
|
%
|
||||||
|
А что, если наша Земля - ад какой-нибудь другой планеты?
|
||||||
|
-- Олдос Хаксли
|
||||||
|
%
|
||||||
|
Если видишь женщину голой достаточно долго, опять начинаешь обращать
|
||||||
|
внимание на ее лицо.
|
||||||
|
-- Генри Миллер
|
||||||
|
%
|
||||||
|
Самое главное - выглядеть совершенно естественно; но для этого нужно очень
|
||||||
|
много косметики.
|
||||||
|
-- Кельвин Кляйн
|
||||||
|
%
|
||||||
|
Любовь - лучшая косметика. Но косметику купить легче.
|
||||||
|
-- Ив Сен-Лоран
|
||||||
|
%
|
||||||
|
Людей без лишнего веса больше всего на кладбище.
|
||||||
|
-- Биверли Силлз
|
||||||
|
%
|
||||||
|
Лучше быть молодым навозным жуков, чем старой райской птицей.
|
||||||
|
-- Марк Твен
|
||||||
|
%
|
||||||
|
К старости недостатки ума становятся все заметнее, как и недостатки
|
||||||
|
внешности.
|
||||||
|
-- Франсуа Ларошфуко
|
||||||
|
%
|
||||||
|
Лучше быть старой, чем мертвой.
|
||||||
|
-- Бриджит Бардо
|
||||||
|
%
|
||||||
|
Вечеринка с коктейлями: место, где можно встретить людей, которые пьют так
|
||||||
|
много, что вы не можете вспомнить их имена.
|
||||||
|
-- Космо Сардо
|
||||||
|
%
|
||||||
|
Средство от похмелья: выжать сок из двух бутылок виски...
|
||||||
|
-- Эдди Кондон
|
||||||
|
%
|
||||||
|
Дважды два уже четыре, а будет еще лучше.
|
||||||
|
-- Хенрик Ягодзинский
|
||||||
|
%
|
||||||
|
Я сидел на диете 14 дней и потерял всего две недели.
|
||||||
|
-- Тоти Филдс
|
||||||
|
%
|
||||||
|
В жизни можно полагаться только на себя самого. Да и то не советую!
|
||||||
|
-- Тристан Бернар
|
||||||
|
%
|
||||||
|
Источник нашей мудрости - наш опыт. Источник нашего опыта - наша глупость.
|
||||||
|
-- Саша Гитри
|
||||||
|
%
|
||||||
|
Уходя на тот свет, не забудь выключить этот.
|
||||||
|
-- Виктор Коваль
|
||||||
|
%
|
||||||
|
Я не верю ни единому слову из того, что вы говорите... или я вам.
|
||||||
|
-- Оскар Уайльд
|
||||||
|
%
|
||||||
|
Я думаю, мы должны говорить правду или хотя бы говорить то, что мы думаем.
|
||||||
|
-- Юрий Лужков
|
||||||
|
%
|
||||||
|
Нельзя иметь все. Куда вы это положите?
|
||||||
|
-- Стивен Райт
|
||||||
|
%
|
||||||
|
Сначала забываешь имена, потом забываешь лица, потом забываешь застегивать
|
||||||
|
ширинку, потом забываешь расстегивать ширинку.
|
||||||
|
-- Лео Розенберг
|
||||||
|
%
|
||||||
|
Время - лучший учитель, но, к сожалению, оно убивает своих учеников.
|
||||||
|
-- Гектор Берлиоз
|
||||||
|
%
|
||||||
|
Прошлое - чужая страна, там все по-другому.
|
||||||
|
-- Лесли Хартли
|
||||||
|
%
|
||||||
|
Помните о бедняках - это не требует никаких расходов.
|
||||||
|
-- Генри Уиллер Шоу
|
||||||
|
%
|
||||||
|
Я люблю своих детей, но некоторые мне не нравятся.
|
||||||
|
-- Лилиан Картер, мать президента США Д.Картера
|
||||||
|
%
|
||||||
|
Дружба - это когда можно ни с того ни с сего приехать к человеку
|
||||||
|
и поселиться у него.
|
||||||
|
-- Давид Самойлов
|
||||||
|
%
|
||||||
|
Врагов я забрасываю цветами - в гробу!
|
||||||
|
-- Сальвадор Дали
|
||||||
|
%
|
||||||
|
Я не боюсь умереть. Я просто не хочу при этом присутствовать.
|
||||||
|
-- Вуди Аллен
|
||||||
|
%
|
||||||
|
Какой замечательный некролог! С таким бы жить и жить!
|
||||||
|
-- М.Генин
|
||||||
|
%
|
||||||
|
Твои шансы выиграть в лотерею возрастут, если ты купишь билет.
|
||||||
|
-- Уинстон Грум из "Правил Фореста Гампа"
|
||||||
|
%
|
||||||
|
Пока вы ищете, кого бы стоило полюбить, вам нужен кто-то, кто любит вас.
|
||||||
|
-- Шейла Делейни
|
||||||
|
%
|
||||||
|
Если двое любят друг друга, это не может счастливо кончиться.
|
||||||
|
-- Э.Хемингуэй
|
||||||
|
%
|
||||||
|
Я порвала с ним через три года. Это была типичная любовь-ненависть. Мы оба
|
||||||
|
любили его и ненавидели меня.
|
||||||
|
-- Кэрол Зискинд
|
||||||
|
%
|
||||||
|
В тех кругах, в которых я вращаюсь, переспать с женщиной - недостаточный
|
||||||
|
повод для того, чтобы быть ей представленным.
|
||||||
|
-- Вирджиния Маклауд
|
||||||
|
%
|
||||||
|
Она говорила на восемнадцати языках и ни на одном из них не умела сказать
|
||||||
|
"нет".
|
||||||
|
-- Дороти Паркер
|
||||||
|
%
|
||||||
|
Помни: в пяти случаях из шести свет в конце туннеля - это свет
|
||||||
|
надвигающегося поезда.
|
||||||
|
-- Пол Диксон
|
||||||
|
%
|
||||||
|
Все соседи плохи, но верхние хуже нижних.
|
||||||
|
-- Константин Мелихан
|
||||||
|
%
|
||||||
|
Америка - единственный матриархат, под сенью которого женщины ведут борьбу
|
||||||
|
за равные права.
|
||||||
|
-- А. Рот
|
||||||
|
%
|
||||||
|
Брак - это лотерея, но в случае проигрыша вы не можете порвать свой билет.
|
||||||
|
-- Ф. Ноулз
|
||||||
|
%
|
||||||
|
Британский солдат устоит против кого угодно, только не против Британского
|
||||||
|
министерства обороны.
|
||||||
|
-- Бернард Шоу
|
||||||
|
%
|
||||||
|
Век наш таков, что он гордится машинами, умеющими думать, и побаивается
|
||||||
|
людей, которые пытаются проявить ту же способность.
|
||||||
|
-- Г.Мамфорд Джонс
|
||||||
|
%
|
||||||
|
Военная мудрость есть понятие, заключающее противоречие в самом себе.
|
||||||
|
Война - слишком серьезное дело, чтобы доверять его военным.
|
||||||
|
-- Талейран
|
||||||
|
%
|
||||||
|
Выход из беды найти не столь просто, как попасть в нее.
|
||||||
|
-- Эд Хау
|
||||||
|
%
|
||||||
|
Граница в политической географии - воображаемая линия между двумя
|
||||||
|
государствами, отделяющая воображаемые права одного от воображаемых прав
|
||||||
|
другого.
|
||||||
|
-- А.Бирс
|
||||||
|
%
|
||||||
|
Да не устрашит тебя величие: одни рождаются великими, другие достигают
|
||||||
|
величия, третьим его навязывают.
|
||||||
|
-- Уильям Шекспир
|
||||||
|
%
|
||||||
|
Две тысячи лет нам поставляли примеры для подражания, и теперь ничто нас
|
||||||
|
не извиняет, если мы, воюя, воем плохо.
|
||||||
|
-- Т.Э. Лоуренс
|
||||||
|
%
|
||||||
|
Дипломная работа среднего выпускника университета есть не что иное, как
|
||||||
|
кости, перенесенные из одной могилы в другую.
|
||||||
|
-- Дж. Фрэнк Доуби
|
||||||
|
%
|
||||||
|
Для любой волнующей человека проблемы всегда легко найти решение -
|
||||||
|
простое, достижимое и ошибочное.
|
||||||
|
-- Г.Л. Менкен
|
||||||
|
%
|
||||||
|
Добрым словом и револьвером вы можете добиться гораздо большего, чем одним
|
||||||
|
только добрым словом.
|
||||||
|
-- Аль Капоне
|
||||||
|
%
|
||||||
|
Если вы не восходящий, значит, вы ниспадающий.
|
||||||
|
-- Стивен Поттер
|
||||||
|
%
|
||||||
|
Если честолюбивая мечта не заставляет вас страдать, значит, ее у вас нет.
|
||||||
|
-- К. Норрис
|
||||||
|
%
|
||||||
|
Идеалист тот, кто, заметив, что роза пахнет лучше капусты, заключает, что
|
||||||
|
и суп из нее будет лучше.
|
||||||
|
-- Г. Менкен
|
||||||
|
%
|
||||||
|
Жизнь что луковица - вы чистите ее, снимая слой за слоем, и иногда
|
||||||
|
плачете.
|
||||||
|
-- С. Сандберг
|
||||||
|
%
|
||||||
|
Когда люди вольны поступать как угодно, они обычно подражают друг другу.
|
||||||
|
-- Э. Хоффер
|
||||||
|
%
|
||||||
|
Коли все думают одинаково, значит, никто особенно и не думает.
|
||||||
|
-- У.Липпман
|
||||||
|
%
|
||||||
|
Компьютеры бесподобны: за несколько минут они могут совершить такую
|
||||||
|
грандиозную ошибку, какую не в состоянии сделать множество людей за многие
|
||||||
|
месяцы.
|
||||||
|
-- М. Мичэм
|
||||||
|
%
|
||||||
|
Логика - это искусство ошибаться с уверенностью в своей правоте.
|
||||||
|
-- Дж. У. Крач
|
||||||
|
%
|
||||||
|
Любовь - вещь идеальная, супружество - реальная; смешение реального с
|
||||||
|
идеальным никогда не проходит безнаказанно.
|
||||||
|
-- И. Гете
|
||||||
|
%
|
||||||
|
Любое ваше решение - это ошибка.
|
||||||
|
-- Эдуард Далберг
|
||||||
|
%
|
||||||
|
Мой способ шутить - это говорить правду. На свете нет ничего
|
||||||
|
смешнее.
|
||||||
|
-- Бернард Шоу
|
||||||
|
%
|
||||||
|
На моем веку было очень много прогресса, но, боюсь, не в том направлении.
|
||||||
|
-- О. Нэш
|
||||||
|
%
|
||||||
|
Нам мало добиться успеха. Надо еще, чтобы друзья наши потерпели крах.
|
||||||
|
-- Ларошфуко
|
||||||
|
%
|
||||||
|
Невеста - женщина, у которой виды на счастье остались позади.
|
||||||
|
-- А. Бирс
|
||||||
|
%
|
||||||
|
Нужно учредить Нобелевскую премию за остроумие. Без физиков, химиков,
|
||||||
|
экономистов мы, если прижмет, как-нибудь обойдемся. Без мира обычно тоже
|
||||||
|
обходимся. Без остроумия - пропадем.
|
||||||
|
-- Джордж Ф. Уилл
|
||||||
|
%
|
||||||
|
О несчастном случае мой подзащитный впервые узнал лишь тогда, когда этот
|
||||||
|
случай произошел.
|
||||||
|
-- Из речи адвоката
|
||||||
|
%
|
||||||
|
Первый и наихудший из всех подвохов - обмануть самого себя. Потом уже
|
||||||
|
легко впасть в любой грех.
|
||||||
|
-- Дж. Бэйли
|
||||||
|
%
|
||||||
|
По самой своей природе человек, чем старше он становится, тем больше
|
||||||
|
противится переменам, особенно переменам к лучшему.
|
||||||
|
-- Дж. Стейнбек
|
||||||
|
%
|
||||||
|
Поиск истины способен изрядно позабавить.
|
||||||
|
-- Вернон Говард
|
||||||
|
%
|
||||||
|
Полицейский находится на своем месте не для того, чтобы создавать
|
||||||
|
беспорядок; полицейский находится там, чтобы поддерживать беспорядок.
|
||||||
|
-- Ричард Дж. Дейли, мэр Чикаго
|
||||||
|
%
|
||||||
|
Посредственность - добродетель в глазах посредственных людей.
|
||||||
|
-- Ж. Жобер
|
||||||
|
%
|
||||||
|
Посредственный учитель излагает. Хороший учитель объясняет. Выдающийся
|
||||||
|
учитель показывает. Великий учитель вдохновляет.
|
||||||
|
-- Уильям Артур Уорд
|
||||||
|
%
|
||||||
|
Президенту в его окружении не нужны мужчины и женщины, умеющие только
|
||||||
|
поддакивать. Если он говорит "нет", мы все говорим "нет".
|
||||||
|
-- Элизабет Доул, помощница президента Рейгана
|
||||||
|
%
|
||||||
|
"Радость моя, мы живем в переходную эпоху", говорил Адам Еве по дороге из
|
||||||
|
рая.
|
||||||
|
-- У. Инге
|
||||||
|
%
|
||||||
|
"С нами такого случиться не может" - это фраза номер один в списке
|
||||||
|
знаменитых последних слов.
|
||||||
|
-- Дэвид Кросби
|
||||||
|
%
|
||||||
|
Самая большая ложь - это неверно понятая правда.
|
||||||
|
-- Уильям Джеймс
|
||||||
|
%
|
||||||
|
Скрипка - инструмент для щекотания человеческих ушей при помощи трения
|
||||||
|
лошадиного хвоста о внутренности кошки.
|
||||||
|
-- Амброз Бирс
|
||||||
|
%
|
||||||
|
Среди преподавателей большинство составляют те, кто не прервет чтение
|
||||||
|
своих лекций по навигации, даже если корабль уже тонет. Следствие:
|
||||||
|
путешествие длиною в тысячу миль завершается одним-единственным шагом.
|
||||||
|
-- Джеймс Г. Борен
|
||||||
|
%
|
||||||
|
Творческое мышление, возможно, означает всего-навсего понимание, что нет
|
||||||
|
никакой особой добродетели в том, чтобы вести дела так, как их всегда вели до
|
||||||
|
нас.
|
||||||
|
-- Рудольф Флеш
|
||||||
|
%
|
||||||
|
Технический прогресс лишь снабдил нас действенными средствами для движения
|
||||||
|
назад.
|
||||||
|
-- О. Хаксли
|
||||||
|
%
|
||||||
|
То, что мы называем прогрессом, представляет собой замену одной
|
||||||
|
неприятности другою.
|
||||||
|
-- Г. Эллис
|
||||||
|
%
|
||||||
|
Учитель прикасается к вечности: никто не может сказать, где кончается его
|
||||||
|
влияние.
|
||||||
|
-- Генри Адамс
|
||||||
|
%
|
||||||
|
Человеку надлежит жить с самим собой и постоянно заботиться, чтобы это
|
||||||
|
была хорошая кампания.
|
||||||
|
-- С.И. Хьюз
|
||||||
|
%
|
||||||
|
Эксперт - это человек, знающий все больше и больше о все меньшем и
|
||||||
|
меньшем. Следствие: колледж не может обеспечить компетентность; он может
|
||||||
|
обеспечить диплом.
|
||||||
|
-- Николас Батлер
|
||||||
|
%
|
||||||
|
Эксперт - это человек, который больше уже не думает; он знает.
|
||||||
|
-- К. Хаббард
|
||||||
|
%
|
||||||
|
Я не верю в коллективную мудрость невежественных индивидуумов.
|
||||||
|
-- Т. Карлейль
|
||||||
|
%
|
||||||
|
Я не против полиции, я просто боюсь ее.
|
||||||
|
-- Альфред Хичкок
|
||||||
|
%
|
||||||
|
Я никогда не мог взять в толк, почему из-за того только, что я выражаюсь
|
||||||
|
невразумительно, никто меня не понимает.
|
||||||
|
-- Милтон Мейер
|
||||||
|
%
|
||||||
|
Пожилые люди думают, что с тех пор, как они постарели, мир только теряет,
|
||||||
|
но ничего не приобретает.
|
||||||
|
-- Жеремена Сталь
|
||||||
|
%
|
||||||
|
Меня интересует мнение не тех людей, которые разбираются в данном вопросе,
|
||||||
|
а тех, которые сами кое-что сделали в одной из областей знания.
|
||||||
|
-- Hорберт Винер
|
||||||
|
%
|
||||||
|
Случайные открытия совершают только подготовленные умы.
|
||||||
|
-- Паскаль
|
||||||
|
%
|
||||||
|
Бывают услуги настолько большие, что рассчитаться за них можно только
|
||||||
|
неблагодарностью.
|
||||||
|
-- Дюма-отец
|
||||||
|
%
|
||||||
|
"Тоже неплохо!" - сказал зять, бросив камнем в собаку, а попав в тещу.
|
||||||
|
-- Плутарх. "Пир семи мудрецов".
|
||||||
|
%
|
||||||
|
Не ковыряй в носу перочинным ножиком. Лезвие легко ржавеет.
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
Очень много - иногда вполне достаточно для женщины.
|
||||||
|
-- Из книги "Ву"
|
||||||
|
%
|
||||||
|
В жизни можно рассчитывать только на самих себя. И то не всегда.
|
||||||
|
-- Тристан Бернар
|
||||||
|
%
|
||||||
|
Все было бы очень хорошо, если бы все наши поступки можно было бы совершать
|
||||||
|
дважды.
|
||||||
|
-- Гете
|
||||||
|
%
|
||||||
|
E = mC
|
||||||
|
-- Альберт Эйнштейн
|
||||||
|
%
|
||||||
|
Человек бывает таким, каким его создал бог, но преимущественно немного хуже.
|
||||||
|
-- Сервантес
|
||||||
|
%
|
||||||
|
Две параллельных линии полюбили друг друга. Трагедия!
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
Я знаток всех "и т. д., и т. п." и я знаю, когда за ними ничего больше
|
||||||
|
не скрывается.
|
||||||
|
-- Гомес де ля Серна
|
||||||
|
%
|
||||||
|
Одна туча может погрузить в темноту весь парк, одно слово может затемнить
|
||||||
|
самое большое счастье.
|
||||||
|
-- Гомес де ля Серна
|
||||||
|
%
|
||||||
|
Тот факт, что будильник не прозвенел, изменило уже много человеческих судеб.
|
||||||
|
-- Агата Кристи
|
||||||
|
%
|
||||||
|
Заполнять жизнь - это еще не значит обогащать ее.
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
Самым серьезным достоинством современного искусства является то, что, когда
|
||||||
|
эти произведения смотрят дети, они не задают таких вопросов, на которые
|
||||||
|
обычно бывает трудно отвечать.
|
||||||
|
-- Лорд Галлюкс
|
||||||
|
%
|
||||||
|
Замужних женщин значительно больше, чем женатых мужчин.
|
||||||
|
-- По данным американской статистики
|
||||||
|
%
|
||||||
|
Совесть - это тот голос, который говорит тебе, что не надо делать именно то,
|
||||||
|
что ты только что сделал.
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
И мелкие неприятности могут отравить жизнь, если нет крупных.
|
||||||
|
-- Р. Гомес де ля Серна
|
||||||
|
%
|
||||||
|
Счастлив тот, кто ни о чем не думает.
|
||||||
|
-- Софокл
|
||||||
|
%
|
||||||
|
Я не читаю газет. Все, о чем там стоит знать, всегда кто-нибудь расскажет.
|
||||||
|
-- Лорд Галлюкс
|
||||||
|
%
|
||||||
|
Недостаточно встать рано, надо еще и проснуться.
|
||||||
|
-- Из книги "Ву"
|
||||||
|
%
|
||||||
|
Высохшую реку не благодарят за ее прошлое.
|
||||||
|
-- Рабиндранат Тагор
|
||||||
|
%
|
||||||
|
Давать советы всегда плохо, но хорошего совета тебе никто не простит.
|
||||||
|
-- Оскар Уайльд
|
||||||
|
%
|
||||||
|
Устарели не только ответы, но даже сами вопросы.
|
||||||
|
-- Хемингуэй
|
||||||
|
%
|
||||||
|
Друзья, как арбузы: случается, что из десяти ни одного хорошего не выбрать.
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
Пока слушатели во время лекции поглядывают на часы, все в порядке. Страшно,
|
||||||
|
когда они начинают удивленно подносить часы к уху.
|
||||||
|
-- Из книги "Пи"
|
||||||
|
%
|
||||||
|
Нет правила, которого нельзя было бы нарушить ради более прекрасного.
|
||||||
|
-- Л. Бетховен
|
||||||
|
%
|
||||||
|
Прекрасна молодость, когда она в движении и знает, куда приложить свои силы.
|
||||||
|
-- Менандр
|
||||||
|
%
|
||||||
|
Простим горячке юных лет
|
||||||
|
И юный жар, и юный бред.
|
||||||
|
-- А. С. Пушкин
|
||||||
|
%
|
||||||
|
Грустно думать, что напрасно
|
||||||
|
Была нам молодость дана.
|
||||||
|
-- А. С. Пушкин
|
||||||
|
%
|
||||||
|
Всего больнее знать, что счастье было так близко - и ты сам его отверг.
|
||||||
|
-- Софокл
|
||||||
|
%
|
||||||
|
Настоящий художник настолько владеет искусством, насколько оно владеет им.
|
||||||
|
-- Г. Флобер
|
||||||
|
%
|
||||||
|
Великие люди сами сооружают себе пьедестал; статую воздвигнет будущее.
|
||||||
|
-- В. Гюго
|
||||||
|
%
|
||||||
|
...заслуги отца на сына не распространяются.
|
||||||
|
-- М. Сервантес
|
||||||
|
%
|
||||||
|
Давайте жить так, чтобы даже гробовщику стало жалко, когда мы умрем.
|
||||||
|
-- Марк Твен
|
||||||
|
%
|
||||||
|
- Обладаешь ли ты разумом?
|
||||||
|
- Обладаю.
|
||||||
|
- Почему же ты не пользуешься им?
|
||||||
|
-- Марк Авелий
|
||||||
|
%
|
||||||
|
Нет такой глупости, которой нельзя было бы исправить при помощи ума,
|
||||||
|
и нет такой мудрости, которой нельзя было бы испортить при помощи глупости.
|
||||||
|
-- В. Гёте
|
||||||
|
%
|
||||||
|
Оптимист верит, что мы живем в лучшем из миров.
|
||||||
|
Пессимист боится, что так оно и есть.
|
||||||
|
%
|
||||||
|
Пессимист видит темный туннель.
|
||||||
|
Оптимист видит свет в конце туннеля.
|
||||||
|
Реалист видит, что это на них мчится поезд.
|
||||||
|
И только машинист видит трех мудаков, тупящих на рельсах.
|
||||||
|
%
|
||||||
|
Мы познаем человека не по тому, что он знает, а по тому, чему он радуется.
|
||||||
|
-- Р.Тагор
|
||||||
|
%
|
||||||
|
Если вы уверены в победе вашей национальной сборной на Евро 2004, то вы либо
|
||||||
|
дурак, либо немец.
|
||||||
|
-- М.Задорнов
|
||||||
|
%
|
||||||
|
Нет некрасивых женщин - есть только женщины, не знающие, что они красивы.
|
||||||
|
-- Вивьен Ли
|
||||||
|
%
|
||||||
|
Любая сложная технология неотличима от волшебства.
|
||||||
|
-- Артур Кларк
|
||||||
|
%
|
||||||
|
Я люблю тебя не за то, кто ты, а за то, кто я, когда я с тобой.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Ни один человек не заслуживает твоих слез, а те, кто заслуживают,
|
||||||
|
не заставят тебя плакать.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Только потому что кто-то не любит тебя так, как тебе хочется, не значит,
|
||||||
|
что он не любит тебя всей душой.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Настоящий друг – это тот, кто будет держать тебя за руку
|
||||||
|
и чувствовать твоё сердце.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Худший способ скучать по человеку – это быть с ним и понимать,
|
||||||
|
что он никогда не будет твоим.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Никогда не переставай улыбаться, даже когда тебе грустно: кто-то может влюбиться
|
||||||
|
в твою улыбку.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Возможно, в этом мире ты всего лишь человек, но для кого-то ты – весь мир.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Не трать время на человека, который не стремится провести его с тобой.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Возможно, Бог хочет, чтобы мы встречали не тех людей до того, как встретим того
|
||||||
|
единственного человека. Чтобы, когда это случится, мы были благодарны.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Не плачь, потому что это закончилось. Улыбнись, потому что это было.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Всегда найдутся люди, которые причинят тебе боль. Нужно продолжать верить людям,
|
||||||
|
просто быть чуть осторожнее.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Стань лучше и сам пойми, кто ты, прежде чем встретишь нового человека и будешь
|
||||||
|
надеяться, что он тебя поймет.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Не прилагай столько усилий, все самое лучшее случается неожиданно.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
|
%
|
||||||
|
Всё, что случаеется, имеет причину.
|
||||||
|
-- Габриэль Гарсиа
|
||||||
106
data/friday.txt
Normal file
106
data/friday.txt
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
А пятница-то не настоящая!!! || 34
|
||||||
|
Спасибо, кэп! || 5
|
||||||
|
А за пивом сегодня идет user || 5
|
||||||
|
user, ты пиво купил? || 5
|
||||||
|
Пятница хоть и небольшой праздник, НО ЗАТО ПОСТОЯННЫЙ! || 45
|
||||||
|
Мечта о пятнице — самая распространенная среди работающего населения. Она начинается уже в понедельник и продолжается четыре дня в неделю || 123
|
||||||
|
Господи дай мне сил не напиться! А если напьюсь, то сделай так чтобы я не плясала, если сил твоих не хватит и я все-таки запляшу, постарайся хотя бы сделать так, что бы не пела! А если и это не удастся, сломай к чертям сервер Ю-тюба! || 5
|
||||||
|
К пятнице готова! Мобильный заряжен, баланс пополнен, в кармане записка с моим адресом || 5
|
||||||
|
ПРЕДУПРЕЖДЕНИЕ: Чрезмерное употребление… Алкоголя. делает ВАШУ пятницу… ОФИГИТЕЛЬНОЙ || 5
|
||||||
|
Сломай систему! Порви шаблоны! Начни новую жизнь с пятницы! || 5
|
||||||
|
В пятницу совесть доживает только до обеда… || 5
|
||||||
|
Сколько работнику не плати, всё равно пятницы ждёт || 1234
|
||||||
|
Робинзооон!!! || 5
|
||||||
|
В пятницу чаще всего хочется выпить. В понедельник чаще всего хочется пятницу. || 15
|
||||||
|
Здравствуй Пятница, здравствуй, любимая, наконец-то ты пришла! || 5
|
||||||
|
Зарплата в пятницу — удар по печени. || 5
|
||||||
|
Вот и пятница пришла, счастье, радость принесла! || 5
|
||||||
|
Все мы — пятницофилы и понедельникофобы. || 15
|
||||||
|
Люблю понедельник — всего три дня до пятницы. || 1
|
||||||
|
Ну здравствуй, пятница. Я дополз к тебе. || 5
|
||||||
|
Пятница. Улыбните Улыбальник. || 5
|
||||||
|
Чувствуете? Выходными пахнет! || 5
|
||||||
|
До пятницы осталось…. пережить четверг! || 4
|
||||||
|
Если пятый день подряд опаздываешь на работу, значит сегодня пятница. || 5
|
||||||
|
От понедельника до пятницы очень далеко, а от пятницы до понедельника рукой подать. || 123467
|
||||||
|
Жизнь начинается в пятницу вечером… В остальное время — выживание. || 5
|
||||||
|
Пятница… белочки следят за тобой. || 5
|
||||||
|
Примета: Если утром жена с вами не разговаривает, значит, вчера была пятница. || 6
|
||||||
|
Чем ближе пятница, тем добрее утро! || 1234
|
||||||
|
Пятница — лучший день недели, особенно её вечер, так как выходные еще не начались, а работа уже закончилась. || 5
|
||||||
|
Отличной была пятница! Особенно запомнились русские народные катания на полицейских бобиках! || 1
|
||||||
|
Четверг это маленькая пятница, а пятницу можно считать выходным. || 4
|
||||||
|
Пятница традиционно начиналась легким ужином в четверг и заканчивалась плотным завтраком в понедельник. || 4
|
||||||
|
Уже с пятницы начинаешь бояться, что скоро понедельник! || 67
|
||||||
|
Каждую пятницу жизнь начинается сначала. || 5
|
||||||
|
С пятницами надо быть осторожней. Они обещают слишком уж многое. Они словно рецензия на кинофильм: лишь в редких случаях предсказанное ими сбывается. || 5
|
||||||
|
Русские в понедельник не работают — у них тяжелый день. || 1
|
||||||
|
Все мы просто дети, изображающие на работе профессионалов, а на самом деле ждущие пятницы, чтобы быть сами собой! || 5
|
||||||
|
Почему-то в пятницу хочется ничего не делать. Хотя в другие дни тоже хочется, но в пятницу ничего не делать хочется особенно сильно. || 5
|
||||||
|
Хочешь жить завтрашним днем — устрой себе семь пятниц на неделе. || 5
|
||||||
|
Что мне снег, что мне зной, что мне вермут разливной, когда мои друзья со мной! || 5
|
||||||
|
Каждую пятницу количество довольных жизнью людей увеличивается на пару миллиардов. Этот эффект длится вплоть до понедельника. || 123467
|
||||||
|
Так, Понедельник, Вторник, Среда, Четверг, проходим, проходим, не задерживаем Пятницу! || 1234
|
||||||
|
Четверг. Смотрю на часы — 16.00. Еле сдерживаюсь, чтобы не закричать — Ура! Во Владивостоке Пятница! || 4
|
||||||
|
Пятница — друг человека! || 5
|
||||||
|
В пятницу вечером понимаешь, что в принципе — жить можно. || 5
|
||||||
|
Ничто так не портит пятницу, как новость о том, что сегодня четверг. || 4
|
||||||
|
Жить нужно так, как будто каждый день пятница. || 123467
|
||||||
|
Только настроился на работу ― и вдруг снова пятница, снова отдых… Вот так всегда! || 5
|
||||||
|
Хорошо, что пятница! Плохо, что еще только утро… || 5
|
||||||
|
Уходя вечером с работы, он был рад, что сегодня пятница и можно спрятаться в уикенде. Он накроется субботой и воскресеньем как двумя толстыми одеялами. Ему ничего не хотелось делать; у него даже не хватало мужества читать. || 5
|
||||||
|
Понедельник ― отходим от выходных, вторник ― готовимся к работе, среда ― работаем, четверг ― отдыхаем от работы, пятница ― готовимся к выходным. Вывод: может, хватит уже работать по средам! || 3
|
||||||
|
Неделя тянется со скоростью улитки. Но в пятницу вечером улитка превращается в Феррари. || 5
|
||||||
|
Прогноз погоды на пятницу: облачно, вечером осадки в виде алкоголя, возможен секс. || 5
|
||||||
|
А пятница всё ближе. Печень в ужасе, попа в предвкушении! || 5
|
||||||
|
Люди, с кем я вчера пила? Объясните, откуда у меня кот и почему люди в магазине мне хлопают… Кстати… никому кот не нужен? || 6
|
||||||
|
ПЯТНИЦА — это старинный народный праздник, который начинают праздновать в ПЯТНИЦУ, а заканчивают — в ПОНЕДЕЛЬНИК || 567
|
||||||
|
Вчера была пятница, завтра суббота, а сегодня тогда что? || 1
|
||||||
|
Сегодня… ПЯТНИЧКА !!! Из хороших новостей пока… ВСЁ… Всем ДОБРА!!! || 5
|
||||||
|
Надену-ка я сегодня красное платье… Под цвет глаз… || 5
|
||||||
|
Вчера был yesterday || 235
|
||||||
|
Вчера была yesterday || 467
|
||||||
|
Вчера было yesterday || 1
|
||||||
|
Никогда еще ожидание пятницы не было столь актуальным… || 4
|
||||||
|
Завтра будет tomorrow || 1234567
|
||||||
|
Четверг - это "завтра пятница". И помнить об этом надо в среду || 34
|
||||||
|
Понедельник - это не начало новой недели, это задница предыдущей( || 1
|
||||||
|
Я, признаться, очень завидую Робинзону Крузо. Живет на острове, никто мозги не е@ет и ПЯТНИЦА, ПЯТНИЦА, ПЯТНИЦА!!! Каждый день ПЯТНИЦА!!! || 1234
|
||||||
|
Наступила пятница — значит мечты начинают сбываться || 5
|
||||||
|
Вечером в пятницу девчонки должны быть алкоголенькими… || 5
|
||||||
|
Позвони мне в субботу рано утром, часов в пятнадцать || 5
|
||||||
|
Ну, вот и пятница пришла… Граждане и гражданки! Следите за своей белкой, чтобы она не разгорячилась! || 5
|
||||||
|
Ага, вчера был понедельник, а сегодня сразу ПЯТНИЦА! ЩАС! || 2
|
||||||
|
Вот пятница пролетела, наступил понедельник, но не все, не все вернулись на свои рабочие места || 1
|
||||||
|
Работа не волк… В лес не убежит?.. А вдруг убежит… Так, за раздумьями и мечтами, и проходит рабочий день… || 12345
|
||||||
|
Какой бы долгой и увлекательной ни была вечеринка, сделайте все, чтобы завтра проснуться в собственной спальне || 5
|
||||||
|
Тяжелое воскресное засыпание объясняется вполне объективной причиной — организм на подсознательном уровне пытается продлить выходной… || 7
|
||||||
|
Воскресенье — день недели с привкусом разочарования. Вроде и выходной, но все равно что-то не то || 7
|
||||||
|
У воскресного дня есть только один существенный недостаток — он почему-то кончается в два раза быстрее, чем любой понедельник или четверг. || 7
|
||||||
|
Первое правило хороших выходных - не вставать рано с постели || 67
|
||||||
|
Понедельник — это такой день, когда вместо бейджика хочется повесить табличку: "Осторожно, злая собака" || 1
|
||||||
|
Нас тупило утро понедельника || 1
|
||||||
|
Бедный понедельник. Его ж никто не любит! || 1
|
||||||
|
Вот выйду на пенсию — буду каждый понедельник выходить на улицу в семь утра и смотреть, как люди идут на работу и страдают || 1
|
||||||
|
Если бы понедельник имел лицо… я бы его… ударила... || 1
|
||||||
|
Завтра во всех домах страны: психологическая драма "утро понедельника" || 7
|
||||||
|
Надеюсь, когда-нибудь я проснусь утром, включу новости и услышу: "Понедельник отменен, продолжайте спать…" || 1
|
||||||
|
Хороший день словом Моndау не назовут! || 1
|
||||||
|
Люди, почему вы злитесь только на понедельник? Как будто в другие дни работать хочется || 1
|
||||||
|
Лучше утро пятницы, чем вечер понедельника || 15
|
||||||
|
Если вы проживете 70 лет, то проживете 10 лет понедельников… || 1
|
||||||
|
Берите пример с понедельника: его никто не ждёт, а ему по)(уй, он все равно приходит… || 1
|
||||||
|
Завтра будет лучше, чем вчера! А, нет, завтра ПОНЕДЕЛЬНИК || 7
|
||||||
|
Три ужасные новости: 1. Сегодня не пятница. 2. И даже завтра не пятница. 3. И даже послезавтра не пятница || 12
|
||||||
|
В понедельник утром, очень сильно завидуешь… безработным || 1
|
||||||
|
Понедельник — удобный повод чего-нибудь понеделать... || 1
|
||||||
|
Дамы и господа! Предлагаю почтить утро понедельника минутой ворчания || 1
|
||||||
|
Вот и начались трудо выебудни || 5
|
||||||
|
Каждый понедельник меня мучает вопрос: выходные, вы вообще были? || 1
|
||||||
|
На улице вторник, а на душе — вечер пятницы… || 2
|
||||||
|
Наступил долгожданный вторник — послезавтра предпоследний день рабочей недели… || 2
|
||||||
|
Если второй день не охота идти на работу, значит сегодня вторник || 2
|
||||||
|
Предлагаю переименовать четверг в "завтра пятница"! || 4
|
||||||
|
Говорят, при Сталине все субботы были рабочие, должно быть он и вправду был садист и тиран! || 6
|
||||||
|
Остановись, воскресенье! Ты прекрасно!!! || 7
|
||||||
|
Воскресенье — день трагичный. Суббота маячит далеко позади, а до понедельника уже рукой подать || 7
|
||||||
1719
data/proverb_src/proverb.txt
Normal file
1719
data/proverb_src/proverb.txt
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,73 @@
|
|||||||
{
|
{
|
||||||
"user" : "nobody",
|
# Cachedir used not only for caches but for some settings and stats too.
|
||||||
"debug_log" : "/var/log/aleesa-telegram-bot/debug.log",
|
"cachedir" : "data/cache",
|
||||||
"telegrambot" : {
|
|
||||||
"name" : "mybot",
|
"gamestat" : {
|
||||||
"tname" : "@my_bot",
|
"dir" : "data",
|
||||||
"csign" : "!",
|
"gamestatdir" : "data/gamestat"
|
||||||
"token" : "get_it_from_botfather",
|
|
||||||
"braindir": "data/telegrambot-brains"
|
|
||||||
},
|
},
|
||||||
"openweathermap" : {
|
|
||||||
"cachetime": "data/cache/openweathermap.Id-Timestamp.db",
|
"fortune" : {
|
||||||
"cachedata": "data/cache/openweathermap.Id-Data.db",
|
"dir" : "data/fortune",
|
||||||
"appid": "get_it_on_openweathermap.org"
|
"srcdir" : "data/fortune_src"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"proverb" : {
|
||||||
|
"dir" : "data/proverb",
|
||||||
|
"srcdir" : "data/proverb_src"
|
||||||
|
},
|
||||||
|
|
||||||
|
"friday" : {
|
||||||
|
"dir" : "data/friday",
|
||||||
|
"src" : "data/friday.txt"
|
||||||
|
},
|
||||||
|
|
||||||
|
"image": {
|
||||||
|
"imgur" : {
|
||||||
|
# See README.md about these settings - auth'ed search settings.
|
||||||
|
"client-id" : "imgur api client id",
|
||||||
|
"secret" : "secret for client id",
|
||||||
|
"access_token" : "access token for querying imgur api",
|
||||||
|
"refresh_token" : "token for refreshing access token"
|
||||||
|
},
|
||||||
|
"flickr" : {
|
||||||
|
# See README.md about these settings - auth'ed search settings.
|
||||||
|
"consumer_key" : "md5-like_hash",
|
||||||
|
"consumer_secret" : "some_hash-like_string",
|
||||||
|
"verifier": "some_hash-like_string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
"lat" : {
|
"lat" : {
|
||||||
"brain": "data/lat/lat.sqlite"
|
"brain": "data/lat/brain.sqlite",
|
||||||
}
|
"src": "data/lat.txt"
|
||||||
|
},
|
||||||
|
|
||||||
|
# Required for debugging reasons, if commented out or not exist, no debug logging appears at all.
|
||||||
|
"log" : "/var/log/aleesa-telegram-bot/aleesa.log",
|
||||||
|
|
||||||
|
# Verbosity can be trace, debug, info (inform), notice, warning (warn), error (err), critical (crit, fatal), alert, emergency.
|
||||||
|
# Currently implemented debug, info, notice, warn, error, fatal. Notice is default logging level.
|
||||||
|
"loglevel": "notice",
|
||||||
|
|
||||||
|
# Openwatermap plugin.
|
||||||
|
"openweathermap" : {
|
||||||
|
"appid" : "md5sum-like_string",
|
||||||
|
},
|
||||||
|
|
||||||
|
# Stuff for telegram itself.
|
||||||
|
"telegrambot" : {
|
||||||
|
|
||||||
|
# Directory with per-conversation "brains".
|
||||||
|
"braindir" : "data/telegrambot-brains",
|
||||||
|
|
||||||
|
# Prefix-sign for all commands. In many irc-bots (eggdrop/windrop) it is "." (dot), in sulci it was "!".
|
||||||
|
# In telegram commands begin with "/" on the start of first (and only) line. In case of this bot you can define what to use.
|
||||||
|
"csign" : "!",
|
||||||
|
|
||||||
|
"token" : "Long_string_given_by_@BotFather"
|
||||||
|
},
|
||||||
|
|
||||||
|
# Unprivileged user to run this bot from.
|
||||||
|
"user" : "unit",
|
||||||
}
|
}
|
||||||
|
|||||||
469
lib/BotLib.pm
Normal file
469
lib/BotLib.pm
Normal file
@@ -0,0 +1,469 @@
|
|||||||
|
package BotLib;
|
||||||
|
# store here utility functions that are not protocol-specified
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (carp);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Admin qw (@ForbiddenMessageTypes GetForbiddenTypes AddForbiddenType
|
||||||
|
DelForbiddenType ListForbidden FortuneToggle FortuneStatus
|
||||||
|
PluginToggle PluginStatus PluginEnabled);
|
||||||
|
use BotLib::Anek qw (Anek);
|
||||||
|
use BotLib::Archeologist qw (Dig);
|
||||||
|
use BotLib::Buni qw (Buni);
|
||||||
|
use BotLib::Drink qw (Drink);
|
||||||
|
use BotLib::Fisher qw (Fish);
|
||||||
|
use BotLib::Fortune qw (Fortune);
|
||||||
|
use BotLib::Friday qw (Friday);
|
||||||
|
use BotLib::Image qw (Kitty Fox Oboobs Obutts Rabbit Owl Frog Horse Snail);
|
||||||
|
use BotLib::Karma qw (KarmaSet KarmaGet);
|
||||||
|
use BotLib::Lat qw (Lat);
|
||||||
|
use BotLib::Monkeyuser qw (Monkeyuser);
|
||||||
|
use BotLib::Proverb qw (Proverb);
|
||||||
|
use BotLib::Util qw (trim);
|
||||||
|
use BotLib::Weather qw (Weather);
|
||||||
|
use BotLib::Xkcd qw (Xkcd);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (RandomCommonPhrase Command Highlight BotSleep IsCensored);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $csign = $c->{telegrambot}->{csign};
|
||||||
|
|
||||||
|
sub RandomCommonPhrase {
|
||||||
|
my @myphrase = (
|
||||||
|
'Так, блядь...',
|
||||||
|
'*Закатывает рукава* И ради этого ты меня позвал?',
|
||||||
|
'Ну чего ты начинаешь, нормально же общались',
|
||||||
|
'Повтори свой вопрос, не поняла',
|
||||||
|
'Выйди и зайди нормально',
|
||||||
|
'Я подумаю',
|
||||||
|
'Даже не знаю, что на это ответить',
|
||||||
|
'Ты упал такие вопросы девочке задавать?',
|
||||||
|
'Можно и так, но не уверена',
|
||||||
|
'А как ты думаешь?',
|
||||||
|
'А ви, таки, почему интересуетесь?',
|
||||||
|
);
|
||||||
|
|
||||||
|
return $myphrase[irand ($#myphrase + 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Command {
|
||||||
|
my $self = shift;
|
||||||
|
my $msg = shift;
|
||||||
|
my $text = shift;
|
||||||
|
my $chatid = shift;
|
||||||
|
my $reply;
|
||||||
|
my ($userid, $username, $fullname, $highlight, $visavi) = Highlight ($msg);
|
||||||
|
|
||||||
|
if (substr ($text, 1) eq 'ping') {
|
||||||
|
$reply = 'Pong.';
|
||||||
|
} elsif (substr ($text, 1) eq 'пинг') {
|
||||||
|
$reply = 'Понг.';
|
||||||
|
} elsif (substr ($text, 1) eq 'pong') {
|
||||||
|
$reply = 'Wat?';
|
||||||
|
} elsif (substr ($text, 1) eq 'понг') {
|
||||||
|
$reply = 'Шта?';
|
||||||
|
} elsif (substr ($text, 1) eq 'coin' || substr ($text, 1) eq 'монетка') {
|
||||||
|
if (rand (101) < 0.016) {
|
||||||
|
$reply = 'ребро';
|
||||||
|
} else {
|
||||||
|
if (irand (2) == 0) {
|
||||||
|
if (irand (2) == 0) {
|
||||||
|
$reply = 'орёл';
|
||||||
|
} else {
|
||||||
|
$reply = 'аверс';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (irand (2) == 0) {
|
||||||
|
$reply = 'решка';
|
||||||
|
} else {
|
||||||
|
$reply = 'реверс';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} elsif (substr ($text, 1) eq 'roll' || substr ($text, 1) eq 'dice' || substr ($text, 1) eq 'кости') {
|
||||||
|
$reply = sprintf 'На первой кости выпало %d, а на второй — %d.', irand (6) + 1, irand (6) + 1;
|
||||||
|
} elsif (substr ($text, 1) eq 'ver' || substr ($text, 1) eq 'version' || substr ($text, 1) eq 'версия') {
|
||||||
|
$reply = 'Версия: Три.Чего-то_там.С_мелочью';
|
||||||
|
} elsif (substr ($text, 1) eq 'anek' || substr ($text, 1) eq 'анек' || substr ($text, 1) eq 'анекдот') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = "```\n" . Anek () . "\n```";
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (length ($text) >= 2 && (substr ($text, 1, 2) eq 'w ' || substr ($text, 1, 2) eq 'п ')) {
|
||||||
|
my $city = substr $text, 3;
|
||||||
|
$reply = Weather $city;
|
||||||
|
} elsif (substr ($text, 1, 7) eq 'погода ') {
|
||||||
|
my $city = substr $text, 7;
|
||||||
|
$reply = Weather $city;
|
||||||
|
} elsif ((substr ($text, 1, 8) eq 'погодка ') || (substr ($text, 1, 8) eq 'погадка ') || (substr ($text, 1, 8) eq 'weather ')){
|
||||||
|
my $city = substr $text, 8;
|
||||||
|
$reply = Weather $city;
|
||||||
|
} elsif (substr ($text, 1) eq 'buni') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Buni ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'monkeyuser') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Monkeyuser ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'cat' || substr ($text, 1) eq 'кис') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Kitty ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'frog' || substr ($text, 1) eq 'toad' || substr ($text, 1) eq 'лягушка') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Frog ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'horse' || substr ($text, 1) eq 'лошадка') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Horse ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'snail' || substr ($text, 1) eq 'улитка') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Snail ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'lat' || substr ($text, 1) eq 'лат') {
|
||||||
|
$reply = Lat ();
|
||||||
|
} elsif (
|
||||||
|
(length ($text) >= 6 && (substr ($text, 1, 6) eq 'karma ' || substr ($text, 1, 6) eq 'карма ')) ||
|
||||||
|
substr ($text, 1) eq 'karma' || substr ($text, 1) eq 'карма'
|
||||||
|
) {
|
||||||
|
my $mytext = '';
|
||||||
|
|
||||||
|
if (length($text) > 6) {
|
||||||
|
$mytext = substr $text, 7;
|
||||||
|
chomp $mytext;
|
||||||
|
$mytext = trim $mytext;
|
||||||
|
} else {
|
||||||
|
$mytext = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$reply = KarmaGet ($chatid, $mytext);
|
||||||
|
} elsif (substr ($text, 1) eq 'xkcd') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Xkcd ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'fox' || substr ($text, 1) eq 'лис') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Fox ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'rabbit' || substr ($text, 1) eq 'bunny' || substr ($text, 1) eq 'кролик') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Rabbit ();
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'owl' || substr ($text, 1) eq 'сова') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Owl ();
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (
|
||||||
|
substr ($text, 1) eq 'tits' ||
|
||||||
|
substr ($text, 1) eq 'boobs' ||
|
||||||
|
substr ($text, 1) eq 'tities' ||
|
||||||
|
substr ($text, 1) eq 'boobies' ||
|
||||||
|
substr ($text, 1) eq 'сиси' ||
|
||||||
|
substr ($text, 1) eq 'сисечки'
|
||||||
|
) {
|
||||||
|
if (PluginEnabled $chatid, 'oboobs') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Oboobs ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
} elsif (
|
||||||
|
substr ($text, 1) eq 'butt' ||
|
||||||
|
substr ($text, 1) eq 'booty' ||
|
||||||
|
substr ($text, 1) eq 'ass' ||
|
||||||
|
substr ($text, 1) eq 'попа' ||
|
||||||
|
substr ($text, 1) eq 'попка'
|
||||||
|
) {
|
||||||
|
if (PluginEnabled $chatid, 'obutts') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Obutts ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'friday' || substr ($text, 1) eq 'пятница') {
|
||||||
|
$reply = Friday ();
|
||||||
|
} elsif (substr ($text, 1) eq 'proverb' || substr ($text, 1) eq 'пословица') {
|
||||||
|
$reply = Proverb ();
|
||||||
|
} elsif (substr ($text, 1) eq 'fortune' || substr ($text, 1) eq 'фортунка' || substr ($text, 1) eq 'f' || substr ($text, 1) eq 'ф') {
|
||||||
|
$reply = sprintf "```\n%s\n```\n", trim (Fortune ());
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'drink' || substr ($text, 1) eq 'праздник') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Drink ();
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
} elsif (substr ($text, 1) eq 'dig' || substr ($text, 1) eq 'копать') {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Dig $highlight;
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'fish' || substr ($text, 1) eq 'fishing' || substr ($text, 1) eq 'рыба' || substr ($text, 1) eq 'рыбка' || substr ($text, 1) eq 'рыбалка' ) {
|
||||||
|
$msg->typing ();
|
||||||
|
$reply = Fish $highlight;
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'хэлп' || substr ($text, 1) eq 'halp') {
|
||||||
|
$reply = 'HALP!!!11';
|
||||||
|
} elsif (substr ($text, 1) eq 'kde' || substr ($text, 1) eq 'кде') {
|
||||||
|
my @phrases = (
|
||||||
|
'Нет, я не буду поднимать вам плазму.',
|
||||||
|
'Повторяйте эту мантру по утрам не менее 5 раз: "Плазма не падает." И, возможно, она перестанет у вас падать.',
|
||||||
|
'Плазма не падает, она просто выходит отдохнуть.',
|
||||||
|
'Плазма это не агрегатное состояние, это суперпозиция. Во время работы она находится сразу в жидком, мягком и тёплом состояниях.',
|
||||||
|
);
|
||||||
|
|
||||||
|
$reply = $phrases[irand ($#phrases + 1)];
|
||||||
|
} elsif (substr ($text, 1) eq 'help' || substr ($text, 1) eq 'помощь') {
|
||||||
|
$reply = << "MYHELP";
|
||||||
|
```
|
||||||
|
${csign}help | ${csign}помощь - список команд
|
||||||
|
${csign}anek | ${csign}анек | ${csign}анекдот - рандомный анекдот с anekdot.ru
|
||||||
|
${csign}buni - рандомный стрип hapi buni
|
||||||
|
${csign}bunny | ${csign}rabbit | ${csign}кролик - кролик
|
||||||
|
${csign}cat | ${csign}кис - кошечка
|
||||||
|
${csign}coin | ${csign}монетка - подбросить монетку - орёл или решка?
|
||||||
|
${csign}dig | ${csign}копать - заняться археологией
|
||||||
|
${csign}drink | ${csign}праздник - какой сегодня праздник?
|
||||||
|
${csign}fish | ${csign}рыба | ${csign}рыбка - порыбачить
|
||||||
|
${csign}fishing | ${csign}рыбалка - порыбачить
|
||||||
|
${csign}f | ${csign}ф - рандомная фраза из сборника цитат fortune_mod
|
||||||
|
${csign}fortune | ${csign}фортунка - рандомная фраза из сборника цитат fortune_mod
|
||||||
|
${csign}fox | ${csign}лис - лисичка
|
||||||
|
${csign}friday | ${csign}пятница - а не пятница ли сегодня?
|
||||||
|
${csign}frog | ${csign}лягушка - лягушка
|
||||||
|
${csign}horse | ${csign}лошадка - лошадка
|
||||||
|
${csign}lat | ${csign}лат - сгенерить фразу из крылатых латинских выражений
|
||||||
|
${csign}monkeyuser - рандомный стрип MonkeyUser
|
||||||
|
${csign}owl | ${csign}сова - сова
|
||||||
|
${csign}proverb | ${csign}пословица - рандомная русская пословица
|
||||||
|
${csign}ping | ${csign}пинг - попинговать бота
|
||||||
|
${csign}roll | ${csign}dice | ${csign}кости - бросить кости
|
||||||
|
${csign}snail | ${csign}улитка - улитка
|
||||||
|
${csign}ver | ${csign}version | ${csign}версия - что-то про версию ПО
|
||||||
|
${csign}w город | ${csign}п город - погода в указанном городе
|
||||||
|
${csign}weather город - погода в указанном городе
|
||||||
|
${csign}погода город - погода в указанном городе
|
||||||
|
${csign}погодка город - погода в указанном городе
|
||||||
|
${csign}погадка город - погода в указанном городе
|
||||||
|
${csign}xkcd - рандомный стрип с сайта xkcd.ru
|
||||||
|
${csign}karma фраза | ${csign}карма фраза - посмотреть карму фразы
|
||||||
|
фраза-- | фраза++ - убавить или добавить карму фразе
|
||||||
|
```
|
||||||
|
Но на самом деле я бот больше для общения, чем для исполнения команд.
|
||||||
|
Поговоришь со мной?
|
||||||
|
MYHELP
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
return;
|
||||||
|
} elsif (substr ($text, 1) eq 'admin' || substr ($text, 1) eq 'админ') {
|
||||||
|
my $member = $self->getChatMember ({ 'chat_id' => $msg->chat->id, 'user_id' => $msg->from->id });
|
||||||
|
|
||||||
|
# this msg should be shown only if admins of chat request it
|
||||||
|
if (($member->status eq 'administrator') || ($member->status eq 'creator')) {
|
||||||
|
$reply = << "MYADMIN";
|
||||||
|
```
|
||||||
|
${csign}admin censor type # - где 1 - вкл, 0 - выкл цензуры для означенного типа сообщений
|
||||||
|
${csign}админ ценз тип # - где 1 - вкл, 0 - выкл цензуры для означенного типа сообщений
|
||||||
|
${csign}admin censor - показать список состояния типов сообщений
|
||||||
|
${csign}админ ценз - показать список состояния типов сообщений
|
||||||
|
${csign}admin fortune # - где 1 - вкл, 0 - выкл фортунку с утра
|
||||||
|
${csign}admin фортунка # - где 1 - вкл, 0 - выкл фортунку с утра
|
||||||
|
${csign}admin fortune - показываем ли с утра фортунку для чата
|
||||||
|
${csign}admin фортунка - показываем ли с утра фортунку для чата
|
||||||
|
${csign}admin oboobs # - где 1 - вкл, 0 - выкл плагина oboobs
|
||||||
|
${csign}admin oboobs - показываем ли сисечки по просьбе участников чата (команды ${csign}tits, ${csign}tities, ${csign}boobs, ${csign}boobies, ${csign}сиси, ${csign}сисечки)
|
||||||
|
${csign}admin obutts # - где 1 - вкл, 0 - выкл плагина obutts
|
||||||
|
${csign}admin obutts - показываем ли попки по просьбе участников чата (команды ${csign}ass, ${csign}butt, ${csign}booty, ${csign}попа, ${csign}попка)
|
||||||
|
```
|
||||||
|
Типы сообщений:
|
||||||
|
audio voice photo video animation sticker dice game poll document
|
||||||
|
MYADMIN
|
||||||
|
|
||||||
|
$msg->replyMd ($reply);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
} elsif ((substr ($text, 1, 5) eq 'admin' || substr ($text, 1, 5) eq 'админ') && (length ($text) >= 8)) {
|
||||||
|
my $member = $self->getChatMember ({ 'chat_id' => $msg->chat->id, 'user_id' => $msg->from->id });
|
||||||
|
|
||||||
|
# this msg should be shown only if admins of chat request it
|
||||||
|
if (($member->status eq 'administrator') || ($member->status eq 'creator')) {
|
||||||
|
my $command = trim (substr $text, 7);
|
||||||
|
my ($cmd, $args) = split /\s+/, $command, 2;
|
||||||
|
|
||||||
|
if ($cmd eq '') {
|
||||||
|
return;
|
||||||
|
} elsif ($cmd eq 'censor' || $cmd eq 'ценз') {
|
||||||
|
if (defined ($args) && ($args ne '')) {
|
||||||
|
my ($msgType, $toggle) = split /\s/, $args, 2;
|
||||||
|
|
||||||
|
if (defined $toggle) {
|
||||||
|
foreach (@ForbiddenMessageTypes) {
|
||||||
|
if ($msgType eq $_) {
|
||||||
|
if ($toggle == 1) {
|
||||||
|
AddForbiddenType ($chatid, $msgType);
|
||||||
|
$reply = "Теперь сообщения с $msgType будут автоматически удаляться";
|
||||||
|
} elsif ($toggle == 0) {
|
||||||
|
DelForbiddenType ($chatid, $msgType);
|
||||||
|
$reply = "Теперь сообщения с $msgType будут оставаться";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$reply = ListForbidden ($chatid);
|
||||||
|
}
|
||||||
|
} elsif ($cmd eq 'fortune' || $cmd eq 'фортунка') {
|
||||||
|
if (defined $args) {
|
||||||
|
if ($args == 1) {
|
||||||
|
$reply = FortuneToggle ($chatid, 1);
|
||||||
|
} elsif ($args == 0) {
|
||||||
|
$reply = FortuneToggle ($chatid, 0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$reply = FortuneStatus ($chatid);
|
||||||
|
}
|
||||||
|
} elsif ($cmd eq 'oboobs') {
|
||||||
|
if (defined $args) {
|
||||||
|
if ($args == 1) {
|
||||||
|
$reply = PluginToggle ($chatid, 'oboobs', 1);
|
||||||
|
} elsif ($args == 0) {
|
||||||
|
$reply = PluginToggle ($chatid, 'oboobs', 0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$reply = PluginStatus ($chatid, 'oboobs');
|
||||||
|
}
|
||||||
|
} elsif ($cmd eq 'obutts') {
|
||||||
|
if (defined $args) {
|
||||||
|
if ($args == 1) {
|
||||||
|
$reply = PluginToggle ($chatid, 'obutts', 1);
|
||||||
|
} elsif ($args == 0) {
|
||||||
|
$reply = PluginToggle ($chatid, 'obutts', 0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$reply = PluginStatus ($chatid, 'obutts');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Highlight {
|
||||||
|
my $msg = shift;
|
||||||
|
|
||||||
|
my $fullname;
|
||||||
|
my $highlight;
|
||||||
|
my $username;
|
||||||
|
my $visavi = '';
|
||||||
|
my $userid = $msg->from->id;
|
||||||
|
|
||||||
|
if ($msg->from->can ('username') && defined $msg->from->username ) {
|
||||||
|
$username = $msg->from->username;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($msg->from->can ('first_name') && defined $msg->from->first_name) {
|
||||||
|
$fullname = $msg->from->first_name;
|
||||||
|
|
||||||
|
if ($msg->from->can ('last_name') && defined $msg->from->last_name) {
|
||||||
|
$fullname .= ' ' . $msg->from->last_name;
|
||||||
|
}
|
||||||
|
} elsif ($msg->from->can ('last_name') && defined $msg->from->last_name) {
|
||||||
|
$fullname .= $msg->from->last_name;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined $username) {
|
||||||
|
$visavi .= '@' . $username;
|
||||||
|
|
||||||
|
if (defined $fullname) {
|
||||||
|
$highlight = "[$fullname](tg://user?id=$userid)";
|
||||||
|
$visavi .= ', ' . $fullname;
|
||||||
|
} else {
|
||||||
|
$highlight = "[$username](tg://user?id=$userid)";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$highlight = "[$fullname](tg://user?id=$userid)";
|
||||||
|
$visavi .= $fullname;
|
||||||
|
}
|
||||||
|
|
||||||
|
$visavi .= " ($userid)";
|
||||||
|
|
||||||
|
return ($userid, $username, $fullname, $highlight, $visavi);
|
||||||
|
}
|
||||||
|
|
||||||
|
sub BotSleep {
|
||||||
|
# TODO: Parametrise this with fuzzy sleep time in seconds
|
||||||
|
my $msg = shift;
|
||||||
|
# let's emulate real human and delay answer
|
||||||
|
sleep (irand (2) + 1);
|
||||||
|
|
||||||
|
for (0..(4 + irand (3))) {
|
||||||
|
$msg->typing ();
|
||||||
|
sleep 3;
|
||||||
|
sleep 3 unless ($_);
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep ( 3 + irand (2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub IsCensored {
|
||||||
|
my $msg = shift;
|
||||||
|
|
||||||
|
my $forbidden = GetForbiddenTypes ($msg->chat->id);
|
||||||
|
|
||||||
|
# voice messages are special
|
||||||
|
if (defined ($msg->voice) && defined ($msg->voice->duration) && ($msg->voice->duration > 0)) {
|
||||||
|
if ($forbidden->{'voice'}) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (keys %{$forbidden}) {
|
||||||
|
if ($forbidden->{$_} && (defined $msg->{$_})) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
266
lib/BotLib/Admin.pm
Normal file
266
lib/BotLib/Admin.pm
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
package BotLib::Admin;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck croak);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Util qw (utf2sha1);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
# to export array we need @ISA here
|
||||||
|
our @ISA = qw / Exporter /; ## no critic (ClassHierarchies::ProhibitExplicitISA)
|
||||||
|
our @EXPORT_OK = qw (@ForbiddenMessageTypes @PluginList GetForbiddenTypes AddForbiddenType DelForbiddenType
|
||||||
|
ListForbidden FortuneToggle FortuneToggleList FortuneStatus PluginToggle PluginStatus
|
||||||
|
PluginEnabled);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
# this list is not yet used
|
||||||
|
our @PluginList = qw (oboobs obutts); ## no critic (Variables::ProhibitPackageVars)
|
||||||
|
our @ForbiddenMessageTypes = qw (audio voice photo video video_note animation sticker dice game poll document); ## no critic (Variables::ProhibitPackageVars)
|
||||||
|
|
||||||
|
sub GetForbiddenTypes {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $messageTypes;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'censor' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach (@ForbiddenMessageTypes) {
|
||||||
|
my $type = $cache->get ($_);
|
||||||
|
|
||||||
|
if ($type) {
|
||||||
|
$messageTypes->{$_} = 1;
|
||||||
|
} else {
|
||||||
|
unless (defined $type) {
|
||||||
|
$cache->set ($_, 0, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
$messageTypes->{$_} = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $messageTypes;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub AddForbiddenType {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $type = shift;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'censor' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
$cache->set ($type, 1, 'never');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub DelForbiddenType {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $type = shift;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'censor' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
$cache->remove ($type);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub ListForbidden {
|
||||||
|
my $chatid = shift;
|
||||||
|
my @list;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'censor' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach (@ForbiddenMessageTypes) {
|
||||||
|
my $type = $cache->get ($_);
|
||||||
|
|
||||||
|
if ($type) {
|
||||||
|
push @list, sprintf 'Тип сообщения %s удаляется', $_;
|
||||||
|
} else {
|
||||||
|
unless (defined $type) {
|
||||||
|
$cache->set ($_, 0, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
push @list, sprintf 'Тип сообщения %s не удаляется', $_;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return join "\n", @list;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FortuneToggle (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $action = shift // undef;
|
||||||
|
my $phrase = 'Фортунка с утра ';
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'fortune'
|
||||||
|
);
|
||||||
|
|
||||||
|
my $state = $cache->get ($chatid);
|
||||||
|
|
||||||
|
if (defined $action) {
|
||||||
|
if ($action) {
|
||||||
|
$cache->set ($chatid, 1, 'never');
|
||||||
|
$phrase .= 'будет показываться.';
|
||||||
|
} else {
|
||||||
|
if (defined $state) {
|
||||||
|
$cache->remove ($chatid);
|
||||||
|
}
|
||||||
|
|
||||||
|
$phrase .= 'не будет показываться.';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (defined $state && $state) {
|
||||||
|
$cache->remove ($chatid);
|
||||||
|
$phrase .= 'не будет показываться.';
|
||||||
|
} else {
|
||||||
|
$cache->set ($chatid, 1, 'never');
|
||||||
|
$phrase .= 'будет показываться.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FortuneStatus ($) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $phrase = 'Фортунка с утра ';
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'fortune'
|
||||||
|
);
|
||||||
|
|
||||||
|
my $state = $cache->get ($chatid);
|
||||||
|
|
||||||
|
if (defined $state && $state) {
|
||||||
|
$phrase .= 'показывается.';
|
||||||
|
} else {
|
||||||
|
$phrase .= 'не показывается.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FortuneToggleList () {
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'fortune'
|
||||||
|
);
|
||||||
|
|
||||||
|
return $cache->get_keys ();
|
||||||
|
}
|
||||||
|
|
||||||
|
sub PluginStatus (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $plugin = shift;
|
||||||
|
my $phrase = "Плагин $plugin ";
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'plugin' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $state = $cache->get ($plugin);
|
||||||
|
|
||||||
|
if ($state) {
|
||||||
|
$phrase .= 'включён.';
|
||||||
|
} else {
|
||||||
|
unless (defined $state) {
|
||||||
|
$cache->set ($plugin, 0, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
$phrase .= 'выключен.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub PluginEnabled (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $plugin = shift;
|
||||||
|
|
||||||
|
# seems that we have point to return always true if chat is private
|
||||||
|
if ($chatid > 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'plugin' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $state = $cache->get ($plugin);
|
||||||
|
|
||||||
|
if (defined $state && $state) {
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub PluginToggle (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $plugin = shift;
|
||||||
|
my $action = shift // undef;
|
||||||
|
my $phrase = "Плагин $plugin ";
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . 'plugin' . '_' . utf2sha1 ($chatid)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $state = $cache->get ($plugin);
|
||||||
|
|
||||||
|
if (defined $action) {
|
||||||
|
if ($action) {
|
||||||
|
$cache->set ($plugin, 1, 'never');
|
||||||
|
$phrase .= 'включён';
|
||||||
|
} else {
|
||||||
|
$cache->set ($plugin, 0, 'never');
|
||||||
|
$phrase .= 'выключен';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (defined ($state) && $state) {
|
||||||
|
$cache->set ($plugin, 0, 'never');
|
||||||
|
$phrase .= 'включён';
|
||||||
|
} else {
|
||||||
|
$cache->set ($plugin, 1, 'never');
|
||||||
|
$phrase .= 'выключен';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
88
lib/BotLib/Anek.pm
Normal file
88
lib/BotLib/Anek.pm
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package BotLib::Anek;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Encode;
|
||||||
|
use HTML::TokeParser;
|
||||||
|
use JSON::XS;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Anek);
|
||||||
|
|
||||||
|
sub Anek {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Все рассказчики анекдотов отдыхают';
|
||||||
|
my $got_anek = 0;
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$ua->max_redirects(3);
|
||||||
|
$r = $ua->get ('https://www.anekdot.ru/rss/randomu.html')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $json;
|
||||||
|
my $response_text = decode ('UTF-8', $r->body);
|
||||||
|
my @text = split /\n/, $response_text;
|
||||||
|
|
||||||
|
while (my $str = pop @text) {
|
||||||
|
if ($str =~ /^var anekdot_texts \= JSON/) {
|
||||||
|
$str = (split /JSON\.parse\(\'/, $str, 2)[1];
|
||||||
|
|
||||||
|
if (defined $str && length ($str) > 10) {
|
||||||
|
$json = (split /\';\)/, $str, 2)[0];
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined $json && length ($json) > 10) {
|
||||||
|
$json =~ s/\\"/"/g;
|
||||||
|
$json =~ s/\\\\"/\\"/g;
|
||||||
|
$json = substr $json, 0, -3;
|
||||||
|
|
||||||
|
my $anek = eval { ${JSON::XS->new->relaxed->decode ($json)}[0] };
|
||||||
|
|
||||||
|
if (defined $anek) {
|
||||||
|
my @anek = split /<br>/, $anek;
|
||||||
|
$ret = join "\n", @anek;
|
||||||
|
|
||||||
|
if (length ($ret) > 1) {
|
||||||
|
$got_anek = 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] anekdot.ru server returns incorrect json, full response text message: %s', $response_text);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] anekdot.ru server returns unexpected response text: %s', $r->body);
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] anekdot.ru server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($got_anek) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
108
lib/BotLib/Archeologist.pm
Normal file
108
lib/BotLib/Archeologist.pm
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
package BotLib::Archeologist;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use DBI;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Dig);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $gamestatdir = $c->{gamestat}->{gamestatdir};
|
||||||
|
my $dbfile = sprintf '%s/gamestat.sqlite', $gamestatdir;
|
||||||
|
|
||||||
|
|
||||||
|
sub getRandomArtifact {
|
||||||
|
my $dbh;
|
||||||
|
$dbh = DBI->connect ("dbi:SQLite:$dbfile", '', '') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$dbh->{sqlite_unicode} = 1;
|
||||||
|
|
||||||
|
my $rows_affected = $dbh->do ('PRAGMA foreign_keys=ON') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$rows_affected = $dbh->do ('PRAGMA journal_mode=WAL') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
my $ary_ref = $dbh->selectall_arrayref ('SELECT name FROM artifacts WHERE id > 0 AND id < 10000') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$dbh->disconnect or $log->warn (sprintf '[WARN] Unable to close gamestat db, sqlite error: %s', $dbh->errstr);
|
||||||
|
|
||||||
|
return $ary_ref->[irand ($#{ $ary_ref } + 1)]->[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Dig {
|
||||||
|
my $name = shift;
|
||||||
|
|
||||||
|
my @location = (
|
||||||
|
'в архивах',
|
||||||
|
'в гималаях',
|
||||||
|
'в интернете',
|
||||||
|
'в кармане',
|
||||||
|
'в клумбе',
|
||||||
|
'в лунном кратере',
|
||||||
|
'во льдах арктики',
|
||||||
|
'в морге',
|
||||||
|
'в окрестностях погоста',
|
||||||
|
'в песочнице',
|
||||||
|
'в пустыне Гоби',
|
||||||
|
'в пустыне Сахаре',
|
||||||
|
'в русле высохшей реки',
|
||||||
|
'в собственной памяти',
|
||||||
|
'в старом сортире',
|
||||||
|
'в углу',
|
||||||
|
'в цветочном горшке',
|
||||||
|
'на бабушкином огороде',
|
||||||
|
'на винчестере',
|
||||||
|
'на горе Арарат',
|
||||||
|
'на горном плато',
|
||||||
|
'на дне моря',
|
||||||
|
'на необитаемом острове',
|
||||||
|
'на первом слое сумрака',
|
||||||
|
'на просторах Украины',
|
||||||
|
);
|
||||||
|
|
||||||
|
my $find_probability = irand 100;
|
||||||
|
my $success_probability = irand 100;
|
||||||
|
my $artifact_age = irand 15000;
|
||||||
|
|
||||||
|
if ($find_probability <= 20) {
|
||||||
|
return sprintf 'По уши закопавшись %s, %s, нифига вы не выкопали! Может повезет в другом месте?', $location[irand ($#location + 1)], $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $phrase = sprintf "Вы начали раскопки %s и усиленно роете лопатами, экскаватором...\n", $location[irand ($#location + 1)];
|
||||||
|
$phrase .= "Вам кажется, что ваш совочек ударился обо что-то твердое. Может, это клад?!\n\n";
|
||||||
|
my $artifact = getRandomArtifact();
|
||||||
|
|
||||||
|
if ($success_probability <= 25) {
|
||||||
|
$phrase .= sprintf '%s стал лучшим археологом, выкопав %s! возраст артефакта - %s лет!', $name, $artifact, $artifact_age;
|
||||||
|
} else {
|
||||||
|
$phrase .= sprintf "Поздравляю, %s! Вы только что выкопали %s, возраст - %s лет!\n", $name, $artifact, $artifact_age;
|
||||||
|
$phrase .= sprintf 'Извини, %s, но на артефакт это не тянет! Однако, попытка хорошая!', $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
60
lib/BotLib/Buni.pm
Normal file
60
lib/BotLib/Buni.pm
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package BotLib::Buni;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use HTML::TokeParser;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Buni);
|
||||||
|
|
||||||
|
sub Buni {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету Buni';
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$ua->max_redirects(3);
|
||||||
|
$r = $ua->get ('http://www.bunicomic.com/?random&nocache=1')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $p = HTML::TokeParser->new(\$r->body);
|
||||||
|
my @a;
|
||||||
|
|
||||||
|
# additional {} required in order "last" to work properly :)
|
||||||
|
{
|
||||||
|
do {
|
||||||
|
$#a = -1;
|
||||||
|
@a = $p->get_tag('meta'); ## no critic (Variables::RequireLocalizedPunctuationVars)
|
||||||
|
|
||||||
|
if (defined $a[0][1]->{property} && $a[0][1]->{property} eq 'og:image') {
|
||||||
|
$ret = sprintf '[buni](%s)', $a[0][1]->{content};
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
} while ($#{$a[0]} > 1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Bunicomic server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
@@ -1,36 +1,33 @@
|
|||||||
package conf;
|
package BotLib::Conf;
|
||||||
# loads config
|
# loads config
|
||||||
|
|
||||||
use 5.018;
|
use 5.018;
|
||||||
use strict;
|
use strict;
|
||||||
use warnings;
|
use warnings;
|
||||||
use utf8;
|
use utf8;
|
||||||
use open qw(:std :utf8);
|
use open qw (:std :utf8);
|
||||||
use English qw( -no_match_vars );
|
use English qw ( -no_match_vars );
|
||||||
|
|
||||||
use vars qw/$VERSION/;
|
|
||||||
use JSON::XS;
|
use JSON::XS;
|
||||||
|
|
||||||
use Exporter qw(import);
|
use version; our $VERSION = qw (1.0);
|
||||||
our @EXPORT_OK = qw(loadConf);
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (LoadConf);
|
||||||
|
|
||||||
$VERSION = '1.0';
|
sub LoadConf {
|
||||||
|
|
||||||
sub loadConf {
|
|
||||||
my $c = 'data/config.json';
|
my $c = 'data/config.json';
|
||||||
open my $CH, '<', $c or die "[FATA] No conf at $c: $OS_ERROR\n";
|
open my $CH, '<', $c or die "[FATAL] No conf at $c: $OS_ERROR\n";
|
||||||
my $len = (stat ($c)) [7];
|
my $len = (stat $c) [7];
|
||||||
my $json;
|
my $json;
|
||||||
my $readlen = read $CH, $json, $len;
|
my $readlen = read $CH, $json, $len;
|
||||||
|
|
||||||
unless ($readlen) {
|
unless ($readlen) {
|
||||||
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
die "[FATA] Unable to read $c: $OS_ERROR\n";
|
die "[FATAL] Unable to read $c: $OS_ERROR\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($readlen != $len) {
|
if ($readlen != $len) {
|
||||||
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
die "[FATA] File $c is $len bytes on disk, but we read only $readlen bytes\n";
|
die "[FATAL] File $c is $len bytes on disk, but we read only $readlen bytes\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
close $CH; ## no critic (InputOutput::RequireCheckedSyscalls
|
||||||
115
lib/BotLib/Drink.pm
Normal file
115
lib/BotLib/Drink.pm
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package BotLib::Drink;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use DateTime;
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Encode;
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use HTML::TokeParser;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Mojo::Log;
|
||||||
|
use Mojo::UserAgent::Cached;
|
||||||
|
use POSIX qw (strftime);
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Drink);
|
||||||
|
|
||||||
|
my @MONTH = qw (yanvar fevral mart aprel may iyun iyul avgust sentyabr oktyabr noyabr dekabr);
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
|
||||||
|
sub Drink {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Не знаю праздников - вджобываю весь день на шахтах, как проклятая.';
|
||||||
|
my ($dayNum, $monthNum) = (localtime ())[3, 4];
|
||||||
|
my $url = sprintf 'https://kakoysegodnyaprazdnik.ru/baza/%s/%s', $MONTH[$monthNum], $dayNum;
|
||||||
|
|
||||||
|
# Those POSIX assholes just forgot to add unix timestamps without TZ offset, so...
|
||||||
|
my ($mday, $mon, $year) = (gmtime ())[3, 4, 5];
|
||||||
|
my $offset = strftime ('%z', gmtime ());
|
||||||
|
my $offsetMinutes = (substr $offset, -2) * 60;
|
||||||
|
my $offsetHours = (substr $offset, 1, 2) * 60 * 60;
|
||||||
|
my $offsetSign;
|
||||||
|
|
||||||
|
if ((substr $offset, 0, 1) eq '+') {
|
||||||
|
$offsetSign = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $expirationDate = DateTime->new (
|
||||||
|
year => $year + 1900,
|
||||||
|
month => $mon + 1,
|
||||||
|
day => $mday,
|
||||||
|
hour => 0,
|
||||||
|
minute => 0,
|
||||||
|
second => 0
|
||||||
|
)->add (days => 1)->strftime ('%s');
|
||||||
|
|
||||||
|
if ((substr $offset, 0, 1) eq '+') {
|
||||||
|
$expirationDate = $expirationDate - $offsetHours - $offsetMinutes;
|
||||||
|
} else {
|
||||||
|
$expirationDate = $expirationDate + $offsetHours + $offsetMinutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent::Cached->new->connect_timeout (3);
|
||||||
|
$ua->cache_agent(
|
||||||
|
CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__,
|
||||||
|
expires_at => $expirationDate,
|
||||||
|
expires_on_backend => 1,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
# just to make Mojo::UserAgent::Cached happy
|
||||||
|
$ua->logger (Mojo::Log->new (path => '/dev/null', level => 'error'));
|
||||||
|
$r = $ua->get ($url => {'Accept-Language' => 'ru-RU', 'Accept-Charset' => 'utf-8'})->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $p = HTML::TokeParser->new(\$r->body);
|
||||||
|
my @a;
|
||||||
|
my @holyday;
|
||||||
|
|
||||||
|
do {
|
||||||
|
$#a = -1;
|
||||||
|
@a = $p->get_tag('span'); ## no critic (Variables::RequireLocalizedPunctuationVars)
|
||||||
|
|
||||||
|
if ($#{$a[0]} > 2 && defined $a[0][1]->{itemprop} && $a[0][1]->{itemprop} eq 'text') {
|
||||||
|
push @holyday,'* ' . decode ('UTF-8', $p->get_trimmed_text ('/span'));
|
||||||
|
}
|
||||||
|
|
||||||
|
} while ($#{$a[0]} > 1);
|
||||||
|
|
||||||
|
if ($#holyday > 0) {
|
||||||
|
# cut off something weird, definely not a "holyday"
|
||||||
|
$#holyday = $#holyday - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($#holyday > 0) {
|
||||||
|
$ret = join "\n", @holyday;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Kakoysegodnyaprazdnik server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
122
lib/BotLib/Fisher.pm
Normal file
122
lib/BotLib/Fisher.pm
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
package BotLib::Fisher;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use DBI;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Fish);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $gamestatdir = $c->{gamestat}->{gamestatdir};
|
||||||
|
my $dbfile = sprintf '%s/gamestat.sqlite', $gamestatdir;
|
||||||
|
|
||||||
|
|
||||||
|
sub getRandomArtifact {
|
||||||
|
my $dbh;
|
||||||
|
$dbh = DBI->connect ("dbi:SQLite:$dbfile", '', '') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$dbh->{sqlite_unicode} = 1;
|
||||||
|
|
||||||
|
my $rows_affected = $dbh->do ('PRAGMA foreign_keys=ON') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$rows_affected = $dbh->do ('PRAGMA journal_mode=WAL') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
my $ary_ref = $dbh->selectall_arrayref ('SELECT name FROM artifacts WHERE id > 9999 AND id < 20000') or do {
|
||||||
|
$log->error (sprintf '[ERROR] Unable to get random artifact, sqlite error: %s', $dbh->errstr);
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
|
||||||
|
$dbh->disconnect or $log->warn (sprintf '[WARN] Unable to close gamestat db, sqlite error: %s', $dbh->errstr);
|
||||||
|
|
||||||
|
return $ary_ref->[irand ($#{ $ary_ref } + 1)]->[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
sub Fish {
|
||||||
|
my $name = shift;
|
||||||
|
|
||||||
|
my @location = (
|
||||||
|
'в поток',
|
||||||
|
'в озеро',
|
||||||
|
'в реку',
|
||||||
|
'в северный ледовитый океан',
|
||||||
|
'в индийский океан',
|
||||||
|
'в биде',
|
||||||
|
'в детский плавательный бассейн',
|
||||||
|
'в туалет',
|
||||||
|
'в кучу рвоты',
|
||||||
|
'в лужу мочи',
|
||||||
|
'в раковину',
|
||||||
|
'в слив ванной',
|
||||||
|
'в лужу грязи',
|
||||||
|
'в ведро воды',
|
||||||
|
'в бутылку с водкой',
|
||||||
|
'в ванную',
|
||||||
|
'в бочку с дождевой водой',
|
||||||
|
'в аквариум',
|
||||||
|
'в сугроб',
|
||||||
|
'в водопад',
|
||||||
|
'в чашку кофе',
|
||||||
|
'в стакан молока',
|
||||||
|
'в черную дыру',
|
||||||
|
'дно Удомельского реактора',
|
||||||
|
'на Марс',
|
||||||
|
'в соседнюю галактику',
|
||||||
|
'к соседу на балкон',
|
||||||
|
'далеко-далеко',
|
||||||
|
'далеко и надолго',
|
||||||
|
'на крышу дома',
|
||||||
|
);
|
||||||
|
|
||||||
|
my @material = (
|
||||||
|
'бамбуковую',
|
||||||
|
'фибергласовую',
|
||||||
|
'карбоновую',
|
||||||
|
'композитную',
|
||||||
|
);
|
||||||
|
|
||||||
|
my $find_probability = irand 100;
|
||||||
|
my $success_probability = irand 100;
|
||||||
|
my $weight = irand 7000;
|
||||||
|
|
||||||
|
my $phrase = sprintf "Вы забрасываете %s удочку %s.\nВы чувствуете поклёвку и начинаете быстро тащить что-то.\n", $material[irand ($#material + 1)], $location[irand ($#location + 1)];
|
||||||
|
|
||||||
|
if ($find_probability <= 20) {
|
||||||
|
$phrase .= sprintf 'Черт, твоя рыбка сорвалась, %s! Не беда, может потом повезет?', $name;
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $artifact = getRandomArtifact ();
|
||||||
|
$phrase .= sprintf "Поздравляю, %s! Вы только что поймали %s! аж на %d кило!\n\n", $name, $artifact, $weight;
|
||||||
|
|
||||||
|
if ($success_probability <= 25) {
|
||||||
|
$phrase .= sprintf 'Ё-мое!!! А это ведь новый рекорд! Продолжай в том же духе, %s!', $name;
|
||||||
|
} else {
|
||||||
|
$phrase .= sprintf 'Извини, %s, но это не новый рекорд! Однако, хорошая попытка!', $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
86
lib/BotLib/Fortune.pm
Normal file
86
lib/BotLib/Fortune.pm
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
package BotLib::Fortune;
|
||||||
|
# Any fortune_mod sources are suitable. Text file with "\n%\n" sentence delimeter.
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck croak);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use SQLite_File;
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Seed Fortune);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $dir = $c->{fortune}->{dir};
|
||||||
|
my $srcdir = $c->{fortune}->{srcdir};
|
||||||
|
|
||||||
|
sub Seed () {
|
||||||
|
unless (-d $dir) {
|
||||||
|
make_path ($dir) || croak "Unable to create $dir: $OS_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
my $backingfile = sprintf '%s/fortune.sqlite', $dir;
|
||||||
|
|
||||||
|
if (-f $backingfile) {
|
||||||
|
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
tie my @fortune, 'SQLite_File', $backingfile || croak "Unable to tie to $backingfile: $OS_ERROR";
|
||||||
|
|
||||||
|
opendir (my $srcdirhandle, $srcdir) || croak "Unable to open $srcdir: $OS_ERROR";
|
||||||
|
|
||||||
|
while (my $fortunefile = readdir ($srcdirhandle)) {
|
||||||
|
my $srcfile = sprintf '%s/%s', $srcdir, $fortunefile;
|
||||||
|
|
||||||
|
unless (-f $srcfile) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($fortunefile =~ m/^\.+$/) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
open (my $fh, '<', $srcfile) || croak "Unable to open $srcfile, $OS_ERROR";
|
||||||
|
# set correct phrase delimiter
|
||||||
|
local $INPUT_RECORD_SEPARATOR = "\n%\n";
|
||||||
|
|
||||||
|
while (readline $fh) {
|
||||||
|
my $phrase = substr $_, 0, -3;
|
||||||
|
push @fortune, $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
close $fh; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
closedir $srcdirhandle;
|
||||||
|
untie @fortune;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# just return answer
|
||||||
|
sub Fortune () {
|
||||||
|
my $backingfile = sprintf '%s/fortune.sqlite', $dir;
|
||||||
|
|
||||||
|
tie my @array, 'SQLite_File', $backingfile || do {
|
||||||
|
$log->error ("[ERROR] Unable to tie to $backingfile: $OS_ERROR");
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
my $phrase = $array[irand ($#array + 1)];
|
||||||
|
# decode?
|
||||||
|
utf8::decode $phrase;
|
||||||
|
untie @array;
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
96
lib/BotLib/Friday.pm
Normal file
96
lib/BotLib/Friday.pm
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package BotLib::Friday;
|
||||||
|
# for friday data stolen from https://raw.githubusercontent.com/isida/vi/master/data/friday.txt
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck croak);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use SQLite_File;
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Seed Friday);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $dir = $c->{friday}->{dir};
|
||||||
|
my $srcfile = $c->{friday}->{src};
|
||||||
|
my @dow = qw (monday tuesday wednesday thursday friday saturday sunday);
|
||||||
|
|
||||||
|
sub Seed () {
|
||||||
|
unless (-d $dir) {
|
||||||
|
make_path ($dir) || croak "Unable to create $dir: $OS_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
my $friday;
|
||||||
|
|
||||||
|
for (0..$#dow) {
|
||||||
|
my $backingfile = sprintf '%s/%s.sqlite', $dir, $dow[$_];
|
||||||
|
|
||||||
|
if (-f $backingfile) {
|
||||||
|
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
tie @{$friday->[$_]}, 'SQLite_File', $backingfile || croak "Unable to tie to $backingfile: $OS_ERROR\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
open (my $fh, '<', $srcfile) || croak "Unable to open $srcfile, $OS_ERROR\n";
|
||||||
|
|
||||||
|
while (readline $fh) {
|
||||||
|
unless (m/ \|\| /xmsg) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
chomp();
|
||||||
|
my ($phrase, $days) = split(/ \|\| /);
|
||||||
|
my @daylist = split(//, $days);
|
||||||
|
|
||||||
|
foreach my $day (@daylist) {
|
||||||
|
unless (defined $day) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($day =~ /^\d$/) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined $phrase && ($phrase ne '') && ($phrase !~ m/^\s+$/xmsg)) {
|
||||||
|
push @{$friday->[$day - 1]}, $phrase;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close $fh; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
|
|
||||||
|
for (0..$#dow) {
|
||||||
|
untie $friday->[$_];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# just return answer
|
||||||
|
sub Friday () {
|
||||||
|
my $today = (localtime (time))[6] - 1;
|
||||||
|
my $backingfile = sprintf '%s/%s.sqlite', $dir, $dow[$today];
|
||||||
|
|
||||||
|
tie my @array, 'SQLite_File', $backingfile || do {
|
||||||
|
$log->error ("[ERROR] Unable to tie to $backingfile: $OS_ERROR\n");
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
my $phrase = $array[irand ($#array + 1)];
|
||||||
|
utf8::decode $phrase;
|
||||||
|
untie @array;
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
115
lib/BotLib/Gamestat.pm
Normal file
115
lib/BotLib/Gamestat.pm
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package BotLib::Gamestat;
|
||||||
|
# Stores and calculates player stats for games
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use DBI;
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use String::Random qw (random_string);
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Util qw (trim utf2sha1);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (SeedArtifacts);
|
||||||
|
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $dir = $c->{gamestat}->{dir};
|
||||||
|
my $gamestatdir = $c->{gamestat}->{gamestatdir};
|
||||||
|
my $dbfile = sprintf '%s/gamestat.sqlite', $gamestatdir;
|
||||||
|
|
||||||
|
# assume that there is not too much artifacts.
|
||||||
|
sub SeedArtifacts {
|
||||||
|
open (my $AFH, '<', "$dir/archeologic_artifacts.txt") || die "No $dir/archeologic_artifacts.txt\n";
|
||||||
|
my @arch_artifacts;
|
||||||
|
|
||||||
|
while (my $artifact = <$AFH>) {
|
||||||
|
next if ($artifact =~ /^\s*$/);
|
||||||
|
$artifact = trim ($artifact);
|
||||||
|
push @arch_artifacts, $artifact;
|
||||||
|
}
|
||||||
|
|
||||||
|
close $AFH; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
|
||||||
|
open ($AFH, '<', "$dir/fisher_artifacts.txt") || die "No $dir/fisher_artifacts.txt\n";
|
||||||
|
my @fisher_artifacts;
|
||||||
|
|
||||||
|
while (my $artifact = <$AFH>) {
|
||||||
|
next if ($artifact =~ /^\s*$/);
|
||||||
|
$artifact = trim ($artifact);
|
||||||
|
push @fisher_artifacts, $artifact;
|
||||||
|
}
|
||||||
|
|
||||||
|
close $AFH; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
undef $AFH;
|
||||||
|
|
||||||
|
my $tablename = random_string ('..........');
|
||||||
|
$tablename = utf2sha1 ($tablename);
|
||||||
|
|
||||||
|
while ($tablename =~ /^\d/) {
|
||||||
|
$tablename = utf2sha1 ($tablename);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tablename =~ s/[\/_\+]/a/g;
|
||||||
|
$tablename = lc ($tablename);
|
||||||
|
|
||||||
|
unless (-d $gamestatdir) {
|
||||||
|
make_path ($gamestatdir) || die "Unable to create $gamestatdir: $OS_ERROR\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
my $dbh = DBI->connect ("dbi:SQLite:$dbfile", '', '');
|
||||||
|
$dbh->{sqlite_unicode} = 1;
|
||||||
|
my $rows_affected = $dbh->do ('PRAGMA foreign_keys=ON') or die $dbh->errstr . "\n";
|
||||||
|
$rows_affected = $dbh->do ('PRAGMA journal_mode=WAL') or die $dbh->errstr . "\n";
|
||||||
|
|
||||||
|
# Open transaction
|
||||||
|
$dbh->begin_work or die $dbh->errstr . "\n";
|
||||||
|
|
||||||
|
my $query = <<"QUERY";
|
||||||
|
CREATE TABLE IF NOT EXISTS $tablename (
|
||||||
|
id INT UNIQUE NOT NULL, -- artifact id
|
||||||
|
name TEXT PRIMARY KEY -- artifact name
|
||||||
|
);
|
||||||
|
QUERY
|
||||||
|
|
||||||
|
$rows_affected = $dbh->do ($query) or die $dbh->errstr . "\n";
|
||||||
|
my $sth = $dbh->prepare ("REPLACE INTO $tablename(id,name) VALUES (?,?)") or die $dbh->errstr . "\n";
|
||||||
|
|
||||||
|
# Insert our archeological artifacts
|
||||||
|
my $counter = 0;
|
||||||
|
|
||||||
|
foreach my $artifact (@arch_artifacts) {
|
||||||
|
last if ($counter == 10000);
|
||||||
|
$sth->execute ($c, $artifact);
|
||||||
|
$counter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Insert our fishing artifacts
|
||||||
|
$counter = 10000;
|
||||||
|
|
||||||
|
foreach my $artifact (@fisher_artifacts) {
|
||||||
|
last if ($counter == 20000);
|
||||||
|
$sth->execute ($c, $artifact);
|
||||||
|
$counter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add indexes
|
||||||
|
$rows_affected = $dbh->do ("CREATE INDEX IF NOT EXISTS myartifactid ON $tablename(id)") or die $dbh->errstr . "\n";
|
||||||
|
|
||||||
|
# Drop target table and replace it with our
|
||||||
|
$rows_affected = $dbh->do ('DROP TABLE IF EXISTS artifacts') or die $dbh->errstr . "\n";
|
||||||
|
$rows_affected = $dbh->do ("ALTER TABLE $tablename RENAME TO artifacts") or die $dbh->errstr . "\n";
|
||||||
|
|
||||||
|
# Close transaction
|
||||||
|
$dbh->commit or die $dbh->errstr . "\n";
|
||||||
|
$dbh->disconnect or warn (sprintf '[WARN] Unable to close gamestat db, sqlite error: %s', $dbh->errstr) . "\n";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
241
lib/BotLib/Image.pm
Normal file
241
lib/BotLib/Image.pm
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
package BotLib::Image;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
use BotLib::Image::Flickr qw (FlickrByTags);
|
||||||
|
use BotLib::Image::Imgur qw (Imgur);
|
||||||
|
use BotLib::Util qw (urlencode);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Kitty Fox Oboobs Obutts Rabbit Owl Frog Horse Snail);
|
||||||
|
|
||||||
|
sub Kitty {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету кошечек, все разбежались.';
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$r = $ua->get ('https://api.thecatapi.com/v1/images/search')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $jcat = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless (defined $jcat) {
|
||||||
|
$log->warn ("[WARN] Unable to decode JSON from thecatapi: $EVAL_ERROR");
|
||||||
|
} else {
|
||||||
|
if ($jcat->[0]->{url}) {
|
||||||
|
my @cats = ('龴ↀ◡ↀ龴', '=^..^=', '≧◔◡◔≦ ','^ↀᴥↀ^');
|
||||||
|
$ret = sprintf '[%s](%s)', $cats[irand ($#cats + 1)], $jcat->[0]->{url};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Thecatapi server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Fox {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету лисичек, все разбежались.';
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$r = $ua->get ('https://randomfox.ca/floof/')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $jfox = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless (defined $jfox) {
|
||||||
|
$log->warn ("[WARN] Unable to decode JSON from randomfox: $EVAL_ERROR");
|
||||||
|
} else {
|
||||||
|
if ($jfox->{image}) {
|
||||||
|
$jfox->{image} =~ s/\\//xmsg;
|
||||||
|
$ret = sprintf '[-^^,--,~](%s)', $jfox->{image};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Randomfox server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Oboobs {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету cисичек, все разбежались.';
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$r = $ua->get ('http://api.oboobs.ru/boobs/0/1/random')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $joboobs = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless (defined $joboobs) {
|
||||||
|
$log->warn ("[WARN] Unable to decode JSON from oboobs: $EVAL_ERROR");
|
||||||
|
} else {
|
||||||
|
if ($joboobs->[0]->{preview}) {
|
||||||
|
my @boobs = ('(. )( .)', '( . Y . )', '(o)(o)', '( @ )( @ )', '(.)(.)');
|
||||||
|
$ret = sprintf '[%s](https://media.oboobs.ru/%s)', $boobs[irand ($#boobs + 1)], $joboobs->[0]->{preview};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Oboobs server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Obutts {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету попок, все разбежались.';
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$r = $ua->get ('http://api.obutts.ru/butts/0/1/random')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $jobutts = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless (defined $jobutts) {
|
||||||
|
$log->warn ("[ERROR] Unable to decode JSON from obutts: $EVAL_ERROR");
|
||||||
|
} else {
|
||||||
|
if ($jobutts->[0]->{preview}) {
|
||||||
|
my @butts = ('(__(__)', '(_!_)', '(__.__)');
|
||||||
|
$ret = sprintf '[%s](http://media.obutts.ru/%s)', $butts[irand ($#butts + 1)], $jobutts->[0]->{preview};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Obutts server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
# It works but results are not particularly relevant, partially. about 20-30% miss
|
||||||
|
# So i prefer to use flickr rabbits selection :)
|
||||||
|
sub rabbit_imgur {
|
||||||
|
my @terms = (
|
||||||
|
urlencode '?q=animals AND (rabbits OR bunnies)',
|
||||||
|
urlencode 'year?q=animals AND (rabbits OR bunnies)',
|
||||||
|
urlencode 'relevance?q=animals AND (rabbits OR bunnies)',
|
||||||
|
urlencode 'relevance/year?q=animals AND (rabbits OR bunnies)',
|
||||||
|
urlencode 'score?q_not=cat OR kitten OR kittens OR dog OR cats OR dogs OR puppy OR puppies&q_tags=bunnies,bunny,rabbits,rabbit',
|
||||||
|
);
|
||||||
|
|
||||||
|
my $rabbit = Imgur ($terms[irand ($#terms + 1)]);
|
||||||
|
# return just large thumbnail instead of real photo (that can be really huge)
|
||||||
|
$rabbit = sprintf '%sl%s', substr ($rabbit, 0, -4), substr ($rabbit, -4);
|
||||||
|
|
||||||
|
if (defined $rabbit) {
|
||||||
|
return sprintf '[(\_/)](%s)', $rabbit;
|
||||||
|
} else {
|
||||||
|
return 'Нету кроликов, все разбежались.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Rabbit {
|
||||||
|
# rabbit, but bunny
|
||||||
|
my $url = FlickrByTags ('animal,bunny');
|
||||||
|
|
||||||
|
if (defined $url) {
|
||||||
|
return sprintf '[(\_/)](%s)', $url;
|
||||||
|
} else {
|
||||||
|
return 'Нету кроликов, все разбежались.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Owl {
|
||||||
|
my $url = FlickrByTags ('bird,owl');
|
||||||
|
|
||||||
|
if (defined $url) {
|
||||||
|
return sprintf '[{ O v O }](%s)', $url;
|
||||||
|
} else {
|
||||||
|
return 'Нету сов, все разлетелись.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Frog {
|
||||||
|
# unable to find any one-line ascii art for frog :(
|
||||||
|
my @art = qw (frog toad лягушка);
|
||||||
|
my $url = FlickrByTags ('frog,toad,amphibian');
|
||||||
|
|
||||||
|
if (defined $url) {
|
||||||
|
return sprintf '[%s](%s)', $art [irand ($#art + 1)], $url;
|
||||||
|
} else {
|
||||||
|
return 'Нету лягушек, все свалили.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Horse {
|
||||||
|
# unable to find any one-line ascii art for frog :(
|
||||||
|
my @art = qw (horse лошадь лошадка);
|
||||||
|
my $url = FlickrByTags ('horse,equine,mammal');
|
||||||
|
|
||||||
|
if (defined $url) {
|
||||||
|
return sprintf '[%s](%s)', $art [irand ($#art + 1)], $url;
|
||||||
|
} else {
|
||||||
|
return 'Нету коняшек, все разбежались.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub Snail {
|
||||||
|
# unable to find any one-line ascii art for frog :(
|
||||||
|
my @art = qw ('-'_@_ @╜ @_'-');
|
||||||
|
my $url = FlickrByTags ('snail,slug');
|
||||||
|
|
||||||
|
if (defined $url) {
|
||||||
|
return sprintf '[%s](%s)', $art [irand ($#art + 1)], $url;
|
||||||
|
} else {
|
||||||
|
return 'Нету улиток, все расползлись.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
599
lib/BotLib/Image/Flickr.pm
Normal file
599
lib/BotLib/Image/Flickr.pm
Normal file
@@ -0,0 +1,599 @@
|
|||||||
|
package BotLib::Image::Flickr;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use Digest::HMAC_SHA1 qw (hmac_sha1);
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use MIME::Base64;
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
use URI::Encode::XS qw (uri_encode);
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Util qw (urlencode);
|
||||||
|
|
||||||
|
use Data::Dumper;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (FlickrInit FlickrByTags FlickrByText FlickrTestLogin);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
|
||||||
|
my $flickr_consumer_key = $c->{image}->{flickr}->{consumer_key};
|
||||||
|
my $flickr_consumer_secret = $c->{image}->{flickr}->{consumer_secret};
|
||||||
|
my $flickr_verifier = $c->{image}->{flickr}->{verifier};
|
||||||
|
my $flickr_request_token_url = 'https://www.flickr.com/services/oauth/request_token';
|
||||||
|
my $flickr_authorization_url = 'https://www.flickr.com/services/oauth/authorize';
|
||||||
|
my $flickr_access_token_url = 'https://www.flickr.com/services/oauth/access_token';
|
||||||
|
my $flickr_callback_url = 'http://www.example.com';
|
||||||
|
my $flickr_api_url = 'https://www.flickr.com/services/rest/';
|
||||||
|
|
||||||
|
sub mknonce {
|
||||||
|
# make random number, 8 symbols in length
|
||||||
|
my $nonce = sprintf '%08d', irand (99999999);
|
||||||
|
return $nonce;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickerSignReq {
|
||||||
|
my %p = @_;
|
||||||
|
my $string;
|
||||||
|
my $hmac;
|
||||||
|
|
||||||
|
if ($p{type} eq 'request_token') {
|
||||||
|
my @parameters;
|
||||||
|
delete $p{type};
|
||||||
|
push @parameters, 'oauth_signature_method=HMAC-SHA1';
|
||||||
|
push @parameters, 'oauth_version=1.0';
|
||||||
|
push @parameters, sprintf 'oauth_callback=%s', uri_encode ($flickr_callback_url);
|
||||||
|
push @parameters, sprintf 'oauth_consumer_key=%s', $flickr_consumer_key;
|
||||||
|
|
||||||
|
foreach my $param (keys %p) {
|
||||||
|
push @parameters, sprintf ('%s=%s', $param, $p{$param});
|
||||||
|
}
|
||||||
|
|
||||||
|
$string = sprintf 'GET&%s&', uri_encode ($flickr_request_token_url);
|
||||||
|
$string .= uri_encode (join '&', sort (@parameters));
|
||||||
|
# Thanks to twitter api dev portal, they explain this particular case: while we requesting this token
|
||||||
|
# we do not yet know access_token secret, so we just omit it in this signature
|
||||||
|
# https://developer.twitter.com/en/docs/authentication/oauth-1-0a/creating-a-signature
|
||||||
|
$hmac = Digest::HMAC_SHA1->new (sprintf '%s&', uri_encode ($flickr_consumer_secret));
|
||||||
|
} elsif ($p{type} eq 'access_token') {
|
||||||
|
my @parameters;
|
||||||
|
my $flickr_request_token_secret = $p{oauth_token_secret};
|
||||||
|
delete $p{oauth_token_secret};
|
||||||
|
delete $p{type};
|
||||||
|
push @parameters, 'oauth_signature_method=HMAC-SHA1';
|
||||||
|
push @parameters, 'oauth_version=1.0';
|
||||||
|
push @parameters, sprintf 'oauth_consumer_key=%s', $flickr_consumer_key;
|
||||||
|
|
||||||
|
foreach my $param (keys %p) {
|
||||||
|
push @parameters, sprintf ('%s=%s', $param, $p{$param});
|
||||||
|
}
|
||||||
|
|
||||||
|
$string = sprintf 'GET&%s&', uri_encode ($flickr_access_token_url);
|
||||||
|
$string .= uri_encode (join '&', sort (@parameters));
|
||||||
|
$hmac = Digest::HMAC_SHA1->new (sprintf '%s&%s', uri_encode ($flickr_consumer_secret), uri_encode ($flickr_request_token_secret));
|
||||||
|
} elsif ($p{type} eq 'test_login' || $p{type} eq 'search_text' || $p{type} eq 'search_tags') {
|
||||||
|
my @parameters;
|
||||||
|
my $flickr_request_token_secret = $p{oauth_token_secret};
|
||||||
|
delete $p{oauth_token_secret};
|
||||||
|
delete $p{type};
|
||||||
|
|
||||||
|
foreach my $param (keys %p) {
|
||||||
|
push @parameters, sprintf ('%s=%s', $param, $p{$param});
|
||||||
|
}
|
||||||
|
|
||||||
|
$string = sprintf 'GET&%s&', uri_encode ($flickr_api_url);
|
||||||
|
$string .= uri_encode (join '&', sort (@parameters));
|
||||||
|
$hmac = Digest::HMAC_SHA1->new (sprintf '%s&%s', uri_encode ($flickr_consumer_secret), uri_encode ($flickr_request_token_secret));
|
||||||
|
}
|
||||||
|
|
||||||
|
$hmac->add ($string);
|
||||||
|
return encode_base64 ($hmac->digest, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrRequestToken {
|
||||||
|
my $oauth_timestamp = time ();
|
||||||
|
my $oauth_nonce = mknonce ();
|
||||||
|
|
||||||
|
my $oauth_signature = flickerSignReq (
|
||||||
|
type => 'request_token',
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
oauth_nonce => $oauth_nonce
|
||||||
|
);
|
||||||
|
|
||||||
|
my $url = $flickr_request_token_url . sprintf (
|
||||||
|
'?oauth_nonce=%s&oauth_timestamp=%s&oauth_consumer_key=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&&oauth_signature=%s&oauth_callback=%s',
|
||||||
|
$oauth_nonce,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
uri_encode ($oauth_signature),
|
||||||
|
uri_encode ($flickr_callback_url)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
my %params;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
# they ignore format=json, so...
|
||||||
|
%params = map {split /=/} split /&/, $r->body;
|
||||||
|
} else {
|
||||||
|
say "Something bad returns from flickr api: $r->code $r->message"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
}
|
||||||
|
|
||||||
|
return %params;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrAccessToken {
|
||||||
|
my $flickr_request_token = shift;
|
||||||
|
my $flickr_request_token_secret = shift;
|
||||||
|
my $flickr_verifier = shift; ## no critic (Variables::ProhibitReusedNames)
|
||||||
|
|
||||||
|
my $oauth_timestamp = time ();
|
||||||
|
my $oauth_nonce = mknonce ();
|
||||||
|
|
||||||
|
my $oauth_signature = flickerSignReq (
|
||||||
|
type => 'access_token',
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
oauth_token => $flickr_request_token,
|
||||||
|
oauth_token_secret => $flickr_request_token_secret,
|
||||||
|
oauth_verifier => $flickr_verifier
|
||||||
|
);
|
||||||
|
|
||||||
|
my $url = $flickr_access_token_url . sprintf (
|
||||||
|
'?oauth_nonce=%s&oauth_timestamp=%s&oauth_verifier=%s&oauth_consumer_key=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s',
|
||||||
|
$oauth_nonce,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_verifier,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$flickr_request_token,
|
||||||
|
uri_encode ($oauth_signature)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
my %params;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
# they ignore format=json
|
||||||
|
%params = map {split /=/} split /&/, $r->body;
|
||||||
|
} else {
|
||||||
|
say "Something bad returns from flickr api: $r->code $r->message"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
}
|
||||||
|
|
||||||
|
return %params;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrAuthorization {
|
||||||
|
my $flickr_request_token = shift;
|
||||||
|
|
||||||
|
my $url = $flickr_authorization_url . sprintf (
|
||||||
|
'?oauth_token=%s&perms=read',
|
||||||
|
$flickr_request_token,
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
if ($r->code == 302) {
|
||||||
|
return $r->content->headers->location;
|
||||||
|
} else {
|
||||||
|
printf "Something went wrong: %s %s\n", $r->code, $r->message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrTestLogin {
|
||||||
|
my $flickr_access_token = shift;
|
||||||
|
my $flickr_access_token_secret = shift;
|
||||||
|
|
||||||
|
my $oauth_timestamp = time ();
|
||||||
|
my $oauth_nonce = mknonce ();
|
||||||
|
|
||||||
|
my $oauth_signature = flickerSignReq (
|
||||||
|
nojsoncallback => 1,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
format => 'json',
|
||||||
|
oauth_consumer_key => $flickr_consumer_key,
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
type => 'test_login',
|
||||||
|
method => 'flickr.test.login',
|
||||||
|
oauth_token => $flickr_access_token,
|
||||||
|
oauth_token_secret => $flickr_access_token_secret,
|
||||||
|
oauth_signature_method => 'HMAC-SHA1',
|
||||||
|
oauth_version => '1.0'
|
||||||
|
);
|
||||||
|
|
||||||
|
my $url = $flickr_api_url . sprintf (
|
||||||
|
'?nojsoncallback=1&oauth_nonce=%s&format=json&oauth_consumer_key=%s&oauth_timestamp=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s&method=flickr.test.login',
|
||||||
|
$oauth_nonce,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_access_token,
|
||||||
|
uri_encode ($oauth_signature)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $response = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (defined $response) {
|
||||||
|
say Dumper $response; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
say "Flickr api returns incorrect json: $r->message"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
say "HTTP status code not 200: $r->code, $r->message"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrSearchByText {
|
||||||
|
my $flickr_access_token = shift;
|
||||||
|
my $flickr_access_token_secret = shift;
|
||||||
|
my $text = shift;
|
||||||
|
|
||||||
|
my $oauth_timestamp = time ();
|
||||||
|
my $oauth_nonce = mknonce ();
|
||||||
|
|
||||||
|
my $oauth_signature = flickerSignReq (
|
||||||
|
nojsoncallback => 1,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
format => 'json',
|
||||||
|
oauth_consumer_key => $flickr_consumer_key,
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
type => 'search_text',
|
||||||
|
content_type => 1,
|
||||||
|
media => 'photos',
|
||||||
|
method => 'flickr.photos.search',
|
||||||
|
text => $text,
|
||||||
|
per_page => 1,
|
||||||
|
oauth_token => $flickr_access_token,
|
||||||
|
oauth_token_secret => $flickr_access_token_secret,
|
||||||
|
oauth_signature_method => 'HMAC-SHA1',
|
||||||
|
oauth_version => '1.0'
|
||||||
|
);
|
||||||
|
|
||||||
|
my $url = $flickr_api_url . sprintf (
|
||||||
|
'?nojsoncallback=1&oauth_nonce=%s&format=json&oauth_consumer_key=%s&oauth_timestamp=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s&method=flickr.photos.search&content_type=1&media=photos&per_page=1&text=%s',
|
||||||
|
$oauth_nonce,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_access_token,
|
||||||
|
uri_encode ($oauth_signature),
|
||||||
|
uri_encode ($text)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $response = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (defined $response) {
|
||||||
|
# lets make another query, this time with random picture
|
||||||
|
my $page = irand int ($response->{photos}->{total} / 500);
|
||||||
|
$oauth_timestamp = time ();
|
||||||
|
$oauth_nonce = mknonce ();
|
||||||
|
$oauth_signature = flickerSignReq (
|
||||||
|
nojsoncallback => 1,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
format => 'json',
|
||||||
|
oauth_consumer_key => $flickr_consumer_key,
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
type => 'search_text',
|
||||||
|
content_type => 1,
|
||||||
|
media => 'photos',
|
||||||
|
method => 'flickr.photos.search',
|
||||||
|
text => $text,
|
||||||
|
page => $page,
|
||||||
|
per_page => 500,
|
||||||
|
oauth_token => $flickr_access_token,
|
||||||
|
oauth_token_secret => $flickr_access_token_secret,
|
||||||
|
oauth_signature_method => 'HMAC-SHA1',
|
||||||
|
oauth_version => '1.0'
|
||||||
|
);
|
||||||
|
|
||||||
|
$url = $flickr_api_url . sprintf (
|
||||||
|
'?nojsoncallback=1&oauth_nonce=%s&format=json&oauth_consumer_key=%s&oauth_timestamp=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s&method=flickr.photos.search&content_type=1&media=photos&per_page=500&page=%d&text=%s',
|
||||||
|
$oauth_nonce,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_access_token,
|
||||||
|
uri_encode ($oauth_signature),
|
||||||
|
$page,
|
||||||
|
uri_encode ($text)
|
||||||
|
);
|
||||||
|
|
||||||
|
$ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
$r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
$response = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (defined $response) {
|
||||||
|
return $response;
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api HTTP status code not 200: $r->code, $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub flickrSearchByTags {
|
||||||
|
my $flickr_access_token = shift;
|
||||||
|
my $flickr_access_token_secret = shift;
|
||||||
|
my $tags = shift;
|
||||||
|
|
||||||
|
my $oauth_timestamp = time ();
|
||||||
|
my $oauth_nonce = mknonce ();
|
||||||
|
|
||||||
|
my $oauth_signature = flickerSignReq (
|
||||||
|
nojsoncallback => 1,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
format => 'json',
|
||||||
|
oauth_consumer_key => $flickr_consumer_key,
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
type => 'search_tags',
|
||||||
|
content_type => 1,
|
||||||
|
media => 'photos',
|
||||||
|
method => 'flickr.photos.search',
|
||||||
|
tags => $tags,
|
||||||
|
per_page => 1,
|
||||||
|
oauth_token => $flickr_access_token,
|
||||||
|
oauth_token_secret => $flickr_access_token_secret,
|
||||||
|
oauth_signature_method => 'HMAC-SHA1',
|
||||||
|
oauth_version => '1.0'
|
||||||
|
);
|
||||||
|
|
||||||
|
my $url = $flickr_api_url . sprintf (
|
||||||
|
'?nojsoncallback=1&oauth_nonce=%s&format=json&oauth_consumer_key=%s&oauth_timestamp=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s&method=flickr.photos.search&content_type=1&media=photos&per_page=1&tags=%s&tag_mode=all',
|
||||||
|
$oauth_nonce,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_access_token,
|
||||||
|
uri_encode ($oauth_signature),
|
||||||
|
uri_encode ($tags)
|
||||||
|
);
|
||||||
|
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
my $r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $response = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (defined $response) {
|
||||||
|
# lets make another query, this time with random picture
|
||||||
|
my $page = irand int ($response->{photos}->{total} / 500);
|
||||||
|
$oauth_timestamp = time ();
|
||||||
|
$oauth_nonce = mknonce ();
|
||||||
|
$oauth_signature = flickerSignReq (
|
||||||
|
nojsoncallback => 1,
|
||||||
|
oauth_nonce => $oauth_nonce,
|
||||||
|
format => 'json',
|
||||||
|
oauth_consumer_key => $flickr_consumer_key,
|
||||||
|
oauth_timestamp => $oauth_timestamp,
|
||||||
|
type => 'search_text',
|
||||||
|
content_type => 1,
|
||||||
|
media => 'photos',
|
||||||
|
method => 'flickr.photos.search',
|
||||||
|
tags => $tags,
|
||||||
|
page => $page,
|
||||||
|
per_page => 500,
|
||||||
|
oauth_token => $flickr_access_token,
|
||||||
|
oauth_token_secret => $flickr_access_token_secret,
|
||||||
|
oauth_signature_method => 'HMAC-SHA1',
|
||||||
|
oauth_version => '1.0'
|
||||||
|
);
|
||||||
|
|
||||||
|
$url = $flickr_api_url . sprintf (
|
||||||
|
'?nojsoncallback=1&oauth_nonce=%s&format=json&oauth_consumer_key=%s&oauth_timestamp=%s&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=%s&oauth_signature=%s&method=flickr.photos.search&content_type=1&media=photos&per_page=500&page=%d&tags=%s&tag_mode=all',
|
||||||
|
$oauth_nonce,
|
||||||
|
$flickr_consumer_key,
|
||||||
|
$oauth_timestamp,
|
||||||
|
$flickr_access_token,
|
||||||
|
uri_encode ($oauth_signature),
|
||||||
|
$page,
|
||||||
|
uri_encode ($tags)
|
||||||
|
);
|
||||||
|
|
||||||
|
$ua = Mojo::UserAgent->new->connect_timeout (5);
|
||||||
|
$r = $ua->get ($url)->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
$response = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (defined $response) {
|
||||||
|
return $response;
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api returns incorrect json: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Flickr api HTTP status code not 200: $r->code, $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FlickrInit {
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__
|
||||||
|
);
|
||||||
|
|
||||||
|
if (defined $flickr_verifier && $flickr_verifier) {
|
||||||
|
my $flickr_request_token = $cache->get ('flickr_request_token');
|
||||||
|
my $flickr_request_token_secret = $cache->get ('flickr_request_token_secret');
|
||||||
|
|
||||||
|
unless (defined $flickr_request_token || defined $flickr_request_token_secret) {
|
||||||
|
say 'Looks like there is no request token or request token secret in config db.'; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
say 'Please remove verifier settings from config.json and run this script again.'; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
my %accessToken = flickrAccessToken ($flickr_request_token, $flickr_request_token_secret, $flickr_verifier);
|
||||||
|
|
||||||
|
if (defined ($accessToken{oauth_token}) && defined ($accessToken{oauth_token_secret})) {
|
||||||
|
# TODO: check set
|
||||||
|
$cache->set ('flickr_access_token', $accessToken{oauth_token}, 'never');
|
||||||
|
$cache->set ('flickr_access_token_secret', $accessToken{oauth_token_secret}, 'never');
|
||||||
|
|
||||||
|
say sprintf ( ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
'Access token (%s) and access token secret (%s) are config db',
|
||||||
|
$accessToken{oauth_token},
|
||||||
|
$accessToken{oauth_token_secret},
|
||||||
|
);
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
my %req = flickrRequestToken ();
|
||||||
|
if (defined ($req{oauth_token}) && defined ($req{oauth_token_secret}) && defined ($req{oauth_token})) {
|
||||||
|
# TODO: check set
|
||||||
|
$cache->set ('flickr_request_token', $req{oauth_token}, 'never');
|
||||||
|
$cache->set ('flickr_request_token_secret', $req{oauth_token_secret}, 'never');
|
||||||
|
my $confirm_url = flickrAuthorization ($req{oauth_token});
|
||||||
|
|
||||||
|
if (defined $confirm_url) {
|
||||||
|
say "Please open this url in your browser and grant access for this app:\n$confirm_url"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
say 'Do not forget to put oauth_verifier to config.json file and re-run this script to get access token'; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
say 'Note that you should be logged off from flickr account.'; ## no critic (InputOutput::RequireCheckedSyscalls)
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FlickrTestLogin {
|
||||||
|
my $text = shift;
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__
|
||||||
|
);
|
||||||
|
|
||||||
|
my $flickr_access_token = $cache->get ('flickr_access_token');
|
||||||
|
my $flickr_access_token_secret = $cache->get ('flickr_access_token_secret');
|
||||||
|
|
||||||
|
if (flickrTestLogin ($flickr_access_token, $flickr_access_token_secret)) {
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FlickrByTags {
|
||||||
|
my $text = shift;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__
|
||||||
|
);
|
||||||
|
|
||||||
|
my $flickr_access_token = $cache->get ('flickr_access_token');
|
||||||
|
my $flickr_access_token_secret = $cache->get ('flickr_access_token_secret');
|
||||||
|
|
||||||
|
# NB: I honestly query random page (among number of pages) of results from api, but always got first page,
|
||||||
|
# no matter what is shown in response' "page" parameter. Looks like bug in API. Try to little bit mitigate
|
||||||
|
# this bug via query 500 results per page, then we can select random result in this heap. But anyway, let's
|
||||||
|
# make this thing future proof and leave randomizer in page select.
|
||||||
|
my $result = flickrSearchByTags ($flickr_access_token, $flickr_access_token_secret, $text);
|
||||||
|
|
||||||
|
if ($result) {
|
||||||
|
if (defined ($result->{photos}) && defined ($result->{photos}->{photo})) {
|
||||||
|
my $item = irand int(@{$result->{photos}->{photo}});
|
||||||
|
$item = ${$result->{photos}->{photo}}[$item];
|
||||||
|
$item = sprintf 'https://live.staticflickr.com/%s/%s_%s_z.jpg', $item->{server}, $item->{id}, $item->{secret};
|
||||||
|
return $item;
|
||||||
|
} else {
|
||||||
|
$log->notice ('[NOTICE] Flickr api returns empty search result list');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub FlickrByText {
|
||||||
|
my $text = shift;
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__
|
||||||
|
);
|
||||||
|
|
||||||
|
my $flickr_access_token = $cache->get ('flickr_access_token');
|
||||||
|
my $flickr_access_token_secret = $cache->get ('flickr_access_token_secret');
|
||||||
|
|
||||||
|
# NB: I honestly query random page (among number of pages) of results from api, but always got first page,
|
||||||
|
# no matter what is shown in response' "page" parameter. Looks like bug in API. Try to little bit mitigate
|
||||||
|
# this bug via query 500 results per page, then we can select random result in this heap. But anyway, let's
|
||||||
|
# make this thing future proof and leave randomizer in page select.
|
||||||
|
my $result = flickrSearchByText ($flickr_access_token, $flickr_access_token_secret, $text);
|
||||||
|
|
||||||
|
if ($result) {
|
||||||
|
if (defined ($result->{photos}) && defined ($result->{photos}->{photo})) {
|
||||||
|
my $item = irand int(@{$result->{photos}->{photo}});
|
||||||
|
$item = ${$result->{photos}->{photo}}[$item];
|
||||||
|
$item = sprintf 'https://live.staticflickr.com/%s/%s_%s_z.jpg', $item->{server}, $item->{id}, $item->{secret};
|
||||||
|
return $item;
|
||||||
|
} else {
|
||||||
|
$log->notice ('[NOTICE] Flickr api returns empty search result list');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
151
lib/BotLib/Image/Imgur.pm
Normal file
151
lib/BotLib/Image/Imgur.pm
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
package Botlib::Image::Imgur;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Imgur);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
|
||||||
|
sub Imgur {
|
||||||
|
my $tag = shift;
|
||||||
|
|
||||||
|
my $refresh_url = 'https://api.imgur.com/oauth2/token';
|
||||||
|
my $search_url = 'https://api.imgur.com/3/gallery/search/';
|
||||||
|
|
||||||
|
my $imgur_client_id = $c->{image}->{imgur}->{client_id} // do {
|
||||||
|
$log->error ('[ERROR] No client_id specified in config for imgur module');
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
my $imgur_client_secret = $c->{image}->{imgur}->{client_secret} // do {
|
||||||
|
$log->error ('[ERROR] No client_secret specified in config for imgur module');
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
my $imgur_access_token = $c->{image}->{imgur}->{access_token} // do {
|
||||||
|
$log->error ('[ERROR] No access_token specified in config for imgur module');
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
my $imgur_refresh_token = $c->{image}->{imgur}->{refresh_token} // do {
|
||||||
|
$log->warn ('[WARN] No refresh_token specified in config for imgur module');
|
||||||
|
};
|
||||||
|
|
||||||
|
# N.B. Both imgur_access_token and imgur_refresh_token time to time can change, so we need
|
||||||
|
# some place where we can store new values
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__
|
||||||
|
);
|
||||||
|
|
||||||
|
$imgur_access_token = $cache->get ('imgur_access_token');
|
||||||
|
|
||||||
|
# if there is no access_token in db - put there one from config
|
||||||
|
unless (defined $imgur_access_token) {
|
||||||
|
$cache->set ('imgur_access_token', $c->{image}->{imgur}->{access_token}, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
$imgur_refresh_token = $cache->get ('imgur_refresh_token');
|
||||||
|
|
||||||
|
# if there is no refresh_token in db - put there one from config
|
||||||
|
unless (defined $imgur_refresh_token) {
|
||||||
|
$cache->set ('imgur_refresh_token', $c->{image}->{imgur}->{refresh_token}, 'never');
|
||||||
|
}
|
||||||
|
|
||||||
|
# query api
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
my $r = $ua->get ($search_url . $tag => {Authorization => "Bearer $imgur_access_token"})->result;
|
||||||
|
|
||||||
|
# looks like we need to refresh token
|
||||||
|
if (($r->code == 401) || ($r->code == 403)) {
|
||||||
|
$ua->post (
|
||||||
|
$refresh_url => form {
|
||||||
|
refresh_token => $imgur_refresh_token,
|
||||||
|
client_id => $imgur_client_id,
|
||||||
|
client_secret => $imgur_client_secret,
|
||||||
|
grant_type => 'refresh_token',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
unless ($r->is_success) {
|
||||||
|
$log->error ("[ERROR] Unable to refresh imgur token, please re-authorise app! or imgur experiencing api outage: $r->code $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $refresh = eval { return $r->json; };
|
||||||
|
|
||||||
|
if (defined $refresh) {
|
||||||
|
$imgur_refresh_token = $refresh->{refresh_token};
|
||||||
|
$cache->set ('refresh_token', $refresh->{refresh_token}, 'never');
|
||||||
|
$imgur_access_token = $refresh->{access_token};
|
||||||
|
$cache->set ('imgur_access_token', $refresh->{access_token}, 'never');
|
||||||
|
} else {
|
||||||
|
$log->warn ("[ERROR] Unable to refresh imgur access_token, unable to decode json: $EVAL_ERROR");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
|
||||||
|
# query api again
|
||||||
|
$r = $ua->get ($search_url . $tag => {Authorization => "Bearer $imgur_access_token"})->result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $searchResult = eval { return $r->json; };
|
||||||
|
my @urls;
|
||||||
|
|
||||||
|
if (defined $searchResult) {
|
||||||
|
if ($searchResult->{success}) {
|
||||||
|
foreach my $item (@{$searchResult->{data}}) {
|
||||||
|
foreach my $image (@{$item->{images}}) {
|
||||||
|
if (defined ($image->{animated}) && (0 + $image->{animated}) != 0) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (($image->{type} eq 'image/jpeg') || ($image->{type} eq 'image/png')) {
|
||||||
|
if (defined ($image->{is_ad}) && (0 + $image->{is_ad}) !=0) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined ($image->{nsfw}) && (0 + $image->{nsfw}) != 0) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
push @urls, $image->{link};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($#urls > 0) {
|
||||||
|
return $urls[irand ($#urls + 1)];
|
||||||
|
} else {
|
||||||
|
$log->notice ('[NOTICE] Imgur api returned empty result.');
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Unable to get results from imgur api: $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Unable to decode imgur api json: $EVAL_ERROR");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ("[WARN] Unable to get results from imgur api: $r->code, $r->message");
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
104
lib/BotLib/Karma.pm
Normal file
104
lib/BotLib/Karma.pm
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
package BotLib::Karma;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (KarmaSet KarmaGet);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
my $max = 5;
|
||||||
|
|
||||||
|
# swallow phrase and return answer
|
||||||
|
sub KarmaSet (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $phrase = shift;
|
||||||
|
my $action = shift;
|
||||||
|
|
||||||
|
if (($phrase eq '') || ($phrase =~ /^ +$/)) {
|
||||||
|
$phrase = ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . $chatid
|
||||||
|
);
|
||||||
|
|
||||||
|
my $score = $cache->get ($phrase);
|
||||||
|
|
||||||
|
if (defined $score) {
|
||||||
|
if ($action eq '++') {
|
||||||
|
$score++;
|
||||||
|
} else {
|
||||||
|
$score--;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if ($action eq '++') {
|
||||||
|
$score = 1;
|
||||||
|
} else {
|
||||||
|
$score = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cache->set ($phrase, $score, 'never') != $score) {
|
||||||
|
$log->error ('[ERROR] Cache error: unable to set karma.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($score < -1 && (($score % (0 - $max)) + 1) == 0) {
|
||||||
|
if ($phrase eq ' ') {
|
||||||
|
return sprintf 'Зарегистрировано пробитие дна, карма пустоты составляет %d', $score;
|
||||||
|
} else {
|
||||||
|
return sprintf 'Зарегистрировано пробитие дна, карма %s составляет %d', $phrase, $score;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if ($phrase eq ' ') {
|
||||||
|
return sprintf 'Карма пустоты составляет %d', $score;
|
||||||
|
} else {
|
||||||
|
return sprintf 'Карма %s составляет %d', $phrase, $score;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# just return answer
|
||||||
|
sub KarmaGet (@) {
|
||||||
|
my $chatid = shift;
|
||||||
|
my $phrase = shift;
|
||||||
|
|
||||||
|
if (($phrase eq '') || ($phrase =~ /^ +$/)) {
|
||||||
|
$phrase = ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $cache = CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__ . '_' . $chatid
|
||||||
|
);
|
||||||
|
|
||||||
|
my $score = $cache->get ($phrase);
|
||||||
|
|
||||||
|
unless (defined $score) {
|
||||||
|
$score = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($phrase eq ' ') {
|
||||||
|
return sprintf 'Карма пустоты составляет %d', $score;
|
||||||
|
} else {
|
||||||
|
return sprintf 'Карма %s составляет %d', $phrase, $score;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
74
lib/BotLib/Lat.pm
Normal file
74
lib/BotLib/Lat.pm
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package BotLib::Lat;
|
||||||
|
# famous latin phases taken from https://ru.wikipedia.org/wiki/Список_крылатых_латинских_выражений
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use File::Basename qw (dirname);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use Hailo;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Train Lat);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $brain = $c->{lat}->{brain};
|
||||||
|
my $srcfile = $c->{lat}->{src};
|
||||||
|
|
||||||
|
sub Train () {
|
||||||
|
my $braindir = dirname $brain;
|
||||||
|
|
||||||
|
unless (-d $braindir) {
|
||||||
|
make_path ($braindir) or do {
|
||||||
|
cluck "Unable to create $braindir: $OS_ERROR";
|
||||||
|
exit 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
my $lat = Hailo->new (
|
||||||
|
brain => $brain,
|
||||||
|
# in our case mean amount of words in phase is 3
|
||||||
|
order => 2
|
||||||
|
);
|
||||||
|
|
||||||
|
$lat->train ($srcfile);
|
||||||
|
my ($tokens, $expressions) = ($lat->stats ())[0,1];
|
||||||
|
printf "Total tokens: %s\nTotal expressions: %s\n", $tokens, $expressions;
|
||||||
|
$lat->save ();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# just return answer
|
||||||
|
sub Lat () {
|
||||||
|
my $braindir = dirname $brain;
|
||||||
|
|
||||||
|
unless (-d $braindir) {
|
||||||
|
$log->error ("[ERROR] No lat module data: $braindir is absent! Train lat first.");
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
unless (-f $brain) {
|
||||||
|
$log->error ("[ERROR] No lat module data: $brain is absent! Train lat first.");
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $lat = Hailo->new (
|
||||||
|
brain => $brain,
|
||||||
|
# in our case mean amount of words in phase is 3
|
||||||
|
order => 2,
|
||||||
|
save_on_exit => 0
|
||||||
|
);
|
||||||
|
|
||||||
|
return $lat->reply ();
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
63
lib/BotLib/Monkeyuser.pm
Normal file
63
lib/BotLib/Monkeyuser.pm
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
package BotLib::Monkeyuser;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck);
|
||||||
|
use HTML::TokeParser;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Monkeyuser);
|
||||||
|
|
||||||
|
sub Monkeyuser {
|
||||||
|
my $r;
|
||||||
|
my $ret = 'Нету Monkey User-ов, они все спрятались.';
|
||||||
|
my @link;
|
||||||
|
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (3);
|
||||||
|
$r = $ua->get ('https://www.monkeyuser.com/toc/')->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
my $p = HTML::TokeParser->new(\$r->body);
|
||||||
|
my @a;
|
||||||
|
|
||||||
|
do {
|
||||||
|
$#a = -1;
|
||||||
|
@a = $p->get_tag('a'); ## no critic (Variables::RequireLocalizedPunctuationVars)
|
||||||
|
|
||||||
|
if (defined $a[0][1]->{class} && $a[0][1]->{class} eq 'lazyload small-image') {
|
||||||
|
if (defined $a[0][1]->{'data-src'} && ($a[0][1]->{'data-src'} !~ /adlitteram/)) {
|
||||||
|
push @link, $a[0][1]->{'data-src'};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} while ($#{$a[0]} > 1);
|
||||||
|
|
||||||
|
if ($#link > 0) {
|
||||||
|
$ret = sprintf '[MonkeyUser](https://www.monkeyuser.com%s)', $link [irand (1 + $#link)];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] MonkeyUser server return status %s with message: %s', $r->{status}, $r->{reason});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
88
lib/BotLib/Proverb.pm
Normal file
88
lib/BotLib/Proverb.pm
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package BotLib::Proverb;
|
||||||
|
# Any fortune_mod sources are suitable. Text file with "\n%\n" sentence delimeter.
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck croak);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use SQLite_File;
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Util qw (trim);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Seed Proverb);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $dir = $c->{proverb}->{dir};
|
||||||
|
my $srcdir = $c->{proverb}->{srcdir};
|
||||||
|
|
||||||
|
sub Seed () {
|
||||||
|
unless (-d $dir) {
|
||||||
|
make_path ($dir) || croak "Unable to create $dir: $OS_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
my $backingfile = sprintf '%s/proverb.sqlite', $dir;
|
||||||
|
|
||||||
|
if (-f $backingfile) {
|
||||||
|
unlink $backingfile || croak "Unable to remove $backingfile: $OS_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
tie my @proverb, 'SQLite_File', $backingfile || croak "Unable to tie to $backingfile: $OS_ERROR";
|
||||||
|
opendir (my $srcdirhandle, $srcdir) || croak "Unable to open $srcdir: $OS_ERROR";
|
||||||
|
|
||||||
|
while (my $proverbfile = readdir ($srcdirhandle)) {
|
||||||
|
my $srcfile = sprintf '%s/%s', $srcdir, $proverbfile;
|
||||||
|
|
||||||
|
unless (-f $srcfile) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($proverbfile =~ m/^\.+$/) {
|
||||||
|
next;
|
||||||
|
}
|
||||||
|
|
||||||
|
open (my $fh, '<', $srcfile) || croak "Unable to open $srcfile, $OS_ERROR";
|
||||||
|
|
||||||
|
while (readline $fh) {
|
||||||
|
chomp;
|
||||||
|
my $str = trim ($_);
|
||||||
|
|
||||||
|
if ($str ne '') {
|
||||||
|
push @proverb, $str;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close $fh; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
closedir $srcdirhandle;
|
||||||
|
untie @proverb;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# just return answer
|
||||||
|
sub Proverb () {
|
||||||
|
my $backingfile = sprintf '%s/proverb.sqlite', $dir;
|
||||||
|
|
||||||
|
tie my @array, 'SQLite_File', $backingfile || do {
|
||||||
|
$log->error ("[ERROR] Unable to tie to $backingfile: $OS_ERROR");
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
my $phrase = $array[irand ($#array + 1)];
|
||||||
|
# decode?
|
||||||
|
utf8::decode $phrase;
|
||||||
|
untie @array;
|
||||||
|
return $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
82
lib/BotLib/Util.pm
Normal file
82
lib/BotLib/Util.pm
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package BotLib::Util;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Digest::SHA qw (sha1_base64);
|
||||||
|
use Encode;
|
||||||
|
use MIME::Base64;
|
||||||
|
use Text::Fuzzy qw (distance_edits);
|
||||||
|
use URI::URL;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (trim urlencode fmatch utf2b64 utf2sha1);
|
||||||
|
|
||||||
|
sub trim {
|
||||||
|
my $str = shift;
|
||||||
|
|
||||||
|
if ($str eq '') {
|
||||||
|
return $str;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (substr ($str, 0, 1) =~ /^\s$/xms) {
|
||||||
|
$str = substr $str, 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (substr ($str, -1, 1) =~ /^\s$/xms) {
|
||||||
|
chop $str;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $str;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub urlencode {
|
||||||
|
my $str = shift;
|
||||||
|
my $urlobj = url $str;
|
||||||
|
return $urlobj->as_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub fmatch {
|
||||||
|
my $srcphrase = shift;
|
||||||
|
my $answer = shift;
|
||||||
|
|
||||||
|
my ($distance, undef) = distance_edits ($srcphrase, $answer);
|
||||||
|
my $srcphraselen = length $srcphrase;
|
||||||
|
my $distance_max = int ($srcphraselen - ($srcphraselen * (100 - (90 / ($srcphraselen ** 0.5))) * 0.01));
|
||||||
|
|
||||||
|
if ($distance >= $distance_max) {
|
||||||
|
return 0;
|
||||||
|
} else {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub utf2b64 {
|
||||||
|
my $string = shift;
|
||||||
|
|
||||||
|
if ($string eq '') {
|
||||||
|
return encode_base64 '';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $bytes = encode_utf8 $string;
|
||||||
|
return encode_base64 $bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub utf2sha1 {
|
||||||
|
my $string = shift;
|
||||||
|
|
||||||
|
if ($string eq '') {
|
||||||
|
return sha1_base64 '';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $bytes = encode_utf8 $string;
|
||||||
|
return sha1_base64 $bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
201
lib/BotLib/Weather.pm
Normal file
201
lib/BotLib/Weather.pm
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
package BotLib::Weather;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (carp cluck);
|
||||||
|
use CHI;
|
||||||
|
use CHI::Driver::BerkeleyDB;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Mojo::Log;
|
||||||
|
use Mojo::UserAgent::Cached;
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Util qw (trim urlencode);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Weather);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $cachedir = $c->{cachedir};
|
||||||
|
|
||||||
|
sub Weather {
|
||||||
|
my $city = shift;
|
||||||
|
$city = trim $city;
|
||||||
|
|
||||||
|
return 'Мне нужно ИМЯ города.' if ($city eq '');
|
||||||
|
return 'Длинновато для названия города.' if (length ($city) > 80);
|
||||||
|
|
||||||
|
$city = ucfirst $city;
|
||||||
|
|
||||||
|
if ($city eq 'Мск' || $city eq 'Default' || $city eq 'Dc' || $city eq 'Msk' || $city eq 'Dc-universe') {
|
||||||
|
$city = 'Москва';
|
||||||
|
} elsif ($city eq 'Спб' || $city eq 'Spb') {
|
||||||
|
$city = 'Санкт-Петербург';
|
||||||
|
} elsif ($city eq 'Ект' || $city eq 'Ебург' || $city eq 'Ёбург' || $city eq 'Екат' || $city eq 'Ekt' || $city eq 'Eburg' || $city eq 'Ekat') {
|
||||||
|
$city = 'Екатеринбург';
|
||||||
|
}
|
||||||
|
|
||||||
|
my $w = __weather ($city);
|
||||||
|
my $reply;
|
||||||
|
|
||||||
|
if ($w) {
|
||||||
|
if ($w->{temperature_min} == $w->{temperature_max}) {
|
||||||
|
$reply = sprintf (
|
||||||
|
"Погода в городе %s, %s:\n%s, ветер %s %s м/c, температура %s°C, ощущается как %s°C, относительная влажность %s%%, давление %s мм.рт.ст",
|
||||||
|
$w->{name},
|
||||||
|
$w->{country},
|
||||||
|
ucfirst $w->{description},
|
||||||
|
$w->{wind_direction},
|
||||||
|
$w->{wind_speed},
|
||||||
|
$w->{temperature_min},
|
||||||
|
$w->{temperature_feelslike},
|
||||||
|
$w->{humidity},
|
||||||
|
$w->{pressure}
|
||||||
|
);
|
||||||
|
} elsif ($w->{temperature_min} < 0 && $w->{temperature_max} <= 0) {
|
||||||
|
$reply = sprintf (
|
||||||
|
"Погода в городе %s, %s:\n%s, ветер %s %s м/c, температура от %s до %s°C, ощущается как %s°C, относительная влажность %s%%, давление %s мм.рт.ст",
|
||||||
|
$w->{name},
|
||||||
|
$w->{country},
|
||||||
|
ucfirst $w->{description},
|
||||||
|
$w->{wind_direction},
|
||||||
|
$w->{wind_speed},
|
||||||
|
$w->{temperature_max},
|
||||||
|
$w->{temperature_min},
|
||||||
|
$w->{temperature_feelslike},
|
||||||
|
$w->{humidity},
|
||||||
|
$w->{pressure}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$reply = sprintf (
|
||||||
|
"Погода в городе %s, %s:\n%s, ветер %s %s м/c, температура от %s до %s°C, ощущается как %s°C, относительная влажность %s%%, давление %s мм.рт.ст",
|
||||||
|
$w->{name},
|
||||||
|
$w->{country},
|
||||||
|
ucfirst $w->{description},
|
||||||
|
$w->{wind_direction},
|
||||||
|
$w->{wind_speed},
|
||||||
|
$w->{temperature_min},
|
||||||
|
$w->{temperature_max},
|
||||||
|
$w->{temperature_feelslike},
|
||||||
|
$w->{humidity},
|
||||||
|
$w->{pressure}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$reply = "Я не знаю, какая погода в $city";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub __weather {
|
||||||
|
my $city = shift;
|
||||||
|
$city = urlencode $city;
|
||||||
|
my $appid = $c->{openweathermap}->{appid};
|
||||||
|
my $now = time ();
|
||||||
|
my $fc;
|
||||||
|
my $w;
|
||||||
|
|
||||||
|
my $r;
|
||||||
|
|
||||||
|
# try 3 times and giveup
|
||||||
|
for (1..3) {
|
||||||
|
my $ua = Mojo::UserAgent::Cached->new;
|
||||||
|
$ua->local_dir ($cachedir);
|
||||||
|
$ua->cache_agent(
|
||||||
|
CHI->new (
|
||||||
|
driver => 'BerkeleyDB',
|
||||||
|
root_dir => $cachedir,
|
||||||
|
namespace => __PACKAGE__,
|
||||||
|
expires_in => '3 hours',
|
||||||
|
expires_on_backend => 1,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
# just to make Mojo::UserAgent::Cached happy
|
||||||
|
$ua->logger (Mojo::Log->new (path => '/dev/null', level => 'error'));
|
||||||
|
$r = $ua->get (sprintf ('http://api.openweathermap.org/data/2.5/weather?q=%s&lang=ru&APPID=%s', $city, $appid))->result;
|
||||||
|
|
||||||
|
if ($r->is_success) {
|
||||||
|
last;
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
# all 3 times can give error, so check it here
|
||||||
|
if ($r->is_success) {
|
||||||
|
$fc = eval {
|
||||||
|
return $r->json;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless ($fc) {
|
||||||
|
$log->warn ("[WARN] openweathermap returns corrupted json: $EVAL_ERROR");
|
||||||
|
return undef;
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
$log->warn (sprintf '[WARN] Server return status %s with message: %s', $r->code, $r->message);
|
||||||
|
return undef;
|
||||||
|
}
|
||||||
|
|
||||||
|
# TODO: check all of this for existence
|
||||||
|
$w->{'name'} = $fc->{name};
|
||||||
|
$w->{'state'} = $fc->{state};
|
||||||
|
$w->{'country'} = $fc->{sys}->{country};
|
||||||
|
$w->{'longitude'} = $fc->{coord}->{lon};
|
||||||
|
$w->{'latitude'} = $fc->{coord}->{lat};
|
||||||
|
$w->{'temperature_min'} = int ($fc->{main}->{temp_min} - 273.15);
|
||||||
|
$w->{'temperature_max'} = int ($fc->{main}->{temp_max} - 273.15);
|
||||||
|
$w->{'temperature_feelslike'} = int ($fc->{main}->{feels_like} - 273.15);
|
||||||
|
$w->{'humidity'} = $fc->{main}->{humidity};
|
||||||
|
$w->{'pressure'} = int ($fc->{main}->{pressure} * 0.75006375541921);
|
||||||
|
$w->{'description'} = $fc->{weather}->[0]->{description};
|
||||||
|
$w->{'wind_speed'} = $fc->{wind}->{speed};
|
||||||
|
$w->{'wind_direction'} = 'разный';
|
||||||
|
my $dir = int ($fc->{wind}->{deg} + 0);
|
||||||
|
|
||||||
|
if ($dir == 0) {
|
||||||
|
$w->{'wind_direction'} = 'северный';
|
||||||
|
} elsif ($dir > 0 && $dir <= 30) {
|
||||||
|
$w->{'wind_direction'} = 'северо-северо-восточный';
|
||||||
|
} elsif ($dir > 30 && $dir <= 60) {
|
||||||
|
$w->{'wind_direction'} = 'северо-восточный';
|
||||||
|
} elsif ($dir > 60 && $dir < 90) {
|
||||||
|
$w->{'wind_direction'} = 'восточно-северо-восточный';
|
||||||
|
} elsif ($dir == 90) {
|
||||||
|
$w->{'wind_direction'} = 'восточный';
|
||||||
|
} elsif ($dir > 90 && $dir <= 120) {
|
||||||
|
$w->{'wind_direction'} = 'восточно-юго-восточный';
|
||||||
|
} elsif ($dir > 120 && $dir <= 150) {
|
||||||
|
$w->{'wind_direction'} = 'юговосточный';
|
||||||
|
} elsif ($dir > 150 && $dir < 180) {
|
||||||
|
$w->{'wind_direction'} = 'юго-юго-восточный';
|
||||||
|
} elsif ($dir == 180) {
|
||||||
|
$w->{'wind_direction'} = 'южный';
|
||||||
|
} elsif ($dir > 180 && $dir <= 210) {
|
||||||
|
$w->{'wind_direction'} = 'юго-юго-западный';
|
||||||
|
} elsif ($dir > 210 && $dir <= 240) {
|
||||||
|
$w->{'wind_direction'} = 'юго-западный';
|
||||||
|
} elsif ($dir > 240 && $dir < 270) {
|
||||||
|
$w->{'wind_direction'} = 'западно-юго-западный';
|
||||||
|
} elsif ($dir == 270) {
|
||||||
|
$w->{'wind_direction'} = 'западный';
|
||||||
|
} elsif ($dir > 270 && $dir <= 300) {
|
||||||
|
$w->{'wind_direction'} = 'западно-северо-западный';
|
||||||
|
} elsif ($dir > 300 && $dir <= 330) {
|
||||||
|
$w->{'wind_direction'} = 'северо-западный';
|
||||||
|
} elsif ($dir > 330 && $dir < 360) {
|
||||||
|
$w->{'wind_direction'} = 'северо-северо-западный';
|
||||||
|
} elsif ($dir == 360) {
|
||||||
|
$w->{'wind_direction'} = 'северный';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $w;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
47
lib/BotLib/Xkcd.pm
Normal file
47
lib/BotLib/Xkcd.pm
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package BotLib::Xkcd;
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use Mojo::UserAgent;
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (Xkcd);
|
||||||
|
|
||||||
|
sub Xkcd {
|
||||||
|
my $ua = Mojo::UserAgent->new->connect_timeout (5)->max_redirects (0);
|
||||||
|
my $location;
|
||||||
|
my $status = 400;
|
||||||
|
my $c = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
my $r = $ua->get ('https://xkcd.ru/random/')->result;
|
||||||
|
|
||||||
|
if (
|
||||||
|
defined $r->content &&
|
||||||
|
defined $r->content->headers &&
|
||||||
|
defined $r->content->headers->location &&
|
||||||
|
$r->content->headers->location ne ''
|
||||||
|
) {
|
||||||
|
$location = substr $r->content->headers->location, 1, -1;
|
||||||
|
$location = sprintf 'https://xkcd.ru/i/%s_v1.png', $location;
|
||||||
|
$r = $ua->head ($location)->result;
|
||||||
|
}
|
||||||
|
|
||||||
|
$c++;
|
||||||
|
$status = $r->code;
|
||||||
|
} while ($c < 3 || $status >= 404);
|
||||||
|
|
||||||
|
if ($status == 200) {
|
||||||
|
return sprintf '[xkcd.ru](%s)', $location;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Комикс-стрип нарисовать не так-то просто :(';
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
@@ -6,6 +6,7 @@ use Mojo::Base -base;
|
|||||||
|
|
||||||
use strict;
|
use strict;
|
||||||
use warnings;
|
use warnings;
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
|
||||||
use Mojo::IOLoop;
|
use Mojo::IOLoop;
|
||||||
use Mojo::UserAgent;
|
use Mojo::UserAgent;
|
||||||
@@ -17,6 +18,13 @@ use Log::Any;
|
|||||||
use Data::Dumper;
|
use Data::Dumper;
|
||||||
|
|
||||||
use Teapot::Bot::Object::Message;
|
use Teapot::Bot::Object::Message;
|
||||||
|
use Teapot::Bot::Object::Poll;
|
||||||
|
use Teapot::Bot::Object::PollAnswer;
|
||||||
|
use Teapot::Bot::Object::ChatMemberUpdated;
|
||||||
|
use Teapot::Bot::Object::User;
|
||||||
|
use Teapot::Bot::Object::Chat;
|
||||||
|
use Teapot::Bot::Object::ChatMember;
|
||||||
|
use Teapot::Bot::Object::ChatInviteLink;
|
||||||
|
|
||||||
$Teapot::Bot::Brain::VERSION = '0.022';
|
$Teapot::Bot::Brain::VERSION = '0.022';
|
||||||
|
|
||||||
@@ -76,7 +84,7 @@ sub think {
|
|||||||
$self->init();
|
$self->init();
|
||||||
|
|
||||||
$self->_add_getUpdates_handler;
|
$self->_add_getUpdates_handler;
|
||||||
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
|
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,8 +111,18 @@ sub getChatMember {
|
|||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
|
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
croak 'No chat_id supplied to getChatMember()' unless $args->{chat_id};
|
|
||||||
croak 'No user_id supplied to getChatMember()' unless $args->{user_id};
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to getChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($args->{user_id}) {
|
||||||
|
cluck 'No user_id supplied to getChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
$send_args->{user_id} = $args->{user_id};
|
$send_args->{user_id} = $args->{user_id};
|
||||||
|
|
||||||
@@ -121,13 +139,73 @@ sub getChatMember {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sub banChatMember {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to banChatMember?';
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to banChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($args->{user_id}) {
|
||||||
|
cluck 'No user_id supplied to banChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
$send_args->{user_id} = $args->{user_id};
|
||||||
|
$send_args->{until_date} = $args->{until_date} if exists $args->{until_date};
|
||||||
|
$send_args->{revoke_messages} = $args->{revoke_messages} if exists $args->{revoke_messages};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/banChatMember";
|
||||||
|
my $api_response = $self->_post_request($url, $send_args);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub unbanChatMember {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to unbanChatMember?';
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to unbanChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($args->{user_id}) {
|
||||||
|
cluck 'No user_id supplied to unbanChatMember()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
$send_args->{user_id} = $args->{user_id};
|
||||||
|
$send_args->{only_if_banned} = $args->{only_if_banned} if exists $args->{only_if_banned};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/unbanChatMember";
|
||||||
|
my $api_response = $self->_post_request($url, $send_args);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
sub getChat {
|
sub getChat {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
|
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
croak 'No chat_id supplied to getChat()' unless $args->{chat_id};
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to getChat()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
my $token = $self->token || croak 'No token supplied to getChat()?';
|
my $token = $self->token || croak 'No token supplied to getChat()?';
|
||||||
@@ -144,15 +222,46 @@ sub getChat {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
sub leaveChat {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to getChat()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to getChat()?';
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/leaveChat";
|
||||||
|
my $api_response = $self->_post_request($url, $send_args);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
sub sendMessage {
|
sub sendMessage {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
|
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
croak 'No chat_id supplied in sendMessage()' unless $args->{chat_id};
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in sendMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
croak 'No text supplied in sendMessage()' unless $args->{text};
|
unless ($args->{text}) {
|
||||||
|
cluck 'No text supplied in sendMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{text} = $args->{text};
|
$send_args->{text} = $args->{text};
|
||||||
|
|
||||||
# these are optional, send if they are supplied
|
# these are optional, send if they are supplied
|
||||||
@@ -169,7 +278,8 @@ sub sendMessage {
|
|||||||
ref($reply_markup) ne 'Teapot::Bot::Object::ReplyKeyboardMarkup' &&
|
ref($reply_markup) ne 'Teapot::Bot::Object::ReplyKeyboardMarkup' &&
|
||||||
ref($reply_markup) ne 'Teapot::Bot::Object::ReplyKeyboardRemove' &&
|
ref($reply_markup) ne 'Teapot::Bot::Object::ReplyKeyboardRemove' &&
|
||||||
ref($reply_markup) ne 'Teapot::Bot::Object::ForceReply' ) {
|
ref($reply_markup) ne 'Teapot::Bot::Object::ForceReply' ) {
|
||||||
croak 'Incorrect reply_markup in sendMessage()';
|
cluck 'Incorrect reply_markup in sendMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
}
|
}
|
||||||
|
|
||||||
$send_args->{reply_markup} = $reply_markup;
|
$send_args->{reply_markup} = $reply_markup;
|
||||||
@@ -192,13 +302,26 @@ sub forwardMessage {
|
|||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
croak 'No chat_id supplied in forwardMessage()' unless $args->{chat_id};
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in forwardMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
croak 'No from_chat_id supplied in forwardMessage()' unless $args->{from_chat_id};
|
unless ($args->{from_chat_id}) {
|
||||||
|
cluck 'No from_chat_id supplied in forwardMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{from_chat_id} = $args->{from_chat_id};
|
$send_args->{from_chat_id} = $args->{from_chat_id};
|
||||||
|
|
||||||
croak 'No message_id supplied in forwardMessage()' unless $args->{message_id};
|
unless ($args->{message_id}) {
|
||||||
|
cluck 'No message_id supplied in forwardMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{message_id} = $args->{message_id};
|
$send_args->{message_id} = $args->{message_id};
|
||||||
|
|
||||||
# these are optional, send if they are supplied
|
# these are optional, send if they are supplied
|
||||||
@@ -216,22 +339,63 @@ sub forwardMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# TODO: Check that message is no older than 48 hrs
|
||||||
|
sub deleteMessage {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in deleteMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
|
unless ($args->{message_id}) {
|
||||||
|
cluck 'No message_id supplied in deleteMessage()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{message_id} = $args->{message_id};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to deleteMessage()?';
|
||||||
|
|
||||||
|
if (Teapot::Bot::Object::ChatMember->canDeleteMessage($self, $args->{chat_id})) {
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/deleteMessage";
|
||||||
|
$self->_post_request($url, $send_args);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
sub sendPhoto {
|
sub sendPhoto {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
|
|
||||||
croak 'No chat_id supplied to sendPhoto()' unless $args->{chat_id};
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied to sendPhoto()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
# photo can be a string (which might be either a URL for telegram servers
|
# photo can be a string (which might be either a URL for telegram servers
|
||||||
# to fetch, or a file_id string) or a file on disk to upload - we need
|
# to fetch, or a file_id string) or a file on disk to upload - we need
|
||||||
# to handle that last case here as it changes the way we create the HTTP
|
# to handle that last case here as it changes the way we create the HTTP
|
||||||
# request
|
# request
|
||||||
croak 'No photo supplied in sendPhoto()' unless $args->{photo};
|
unless ($args->{photo}) {
|
||||||
|
cluck 'No photo supplied in sendPhoto()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
if (-e $args->{photo}) {
|
if (-e $args->{photo}) {
|
||||||
$send_args->{photo} = { photo => { file => $args->{photo} } };
|
$send_args->{photo} = { file => $args->{photo} };
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
$send_args->{photo} = $args->{photo};
|
$send_args->{photo} = $args->{photo};
|
||||||
@@ -255,7 +419,11 @@ sub sendChatAction {
|
|||||||
my $args = shift || {};
|
my $args = shift || {};
|
||||||
my $send_args = {};
|
my $send_args = {};
|
||||||
|
|
||||||
croak 'No chat_id supplied in sendChatAction()' unless $args->{chat_id};
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in sendChatAction()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
$send_args->{chat_id} = $args->{chat_id};
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
unless (defined $args->{action}) {
|
unless (defined $args->{action}) {
|
||||||
@@ -272,11 +440,11 @@ sub sendChatAction {
|
|||||||
elsif ($args->{action} eq 'upload_video') {
|
elsif ($args->{action} eq 'upload_video') {
|
||||||
$send_args->{action} = 'upload_video';
|
$send_args->{action} = 'upload_video';
|
||||||
}
|
}
|
||||||
elsif ($args->{action} eq 'record_audio') {
|
elsif ($args->{action} eq 'record_voice') {
|
||||||
$send_args->{action} = 'record_audio';
|
$send_args->{action} = 'record_voice';
|
||||||
}
|
}
|
||||||
elsif ($args->{action} eq 'upload_audio') {
|
elsif ($args->{action} eq 'upload_voice') {
|
||||||
$send_args->{action} = 'upload_audio';
|
$send_args->{action} = 'upload_voice';
|
||||||
}
|
}
|
||||||
elsif ($args->{action} eq 'upload_document') {
|
elsif ($args->{action} eq 'upload_document') {
|
||||||
$send_args->{action} = 'upload_document';
|
$send_args->{action} = 'upload_document';
|
||||||
@@ -290,6 +458,9 @@ sub sendChatAction {
|
|||||||
elsif ($args->{action} eq 'upload_video_note') {
|
elsif ($args->{action} eq 'upload_video_note') {
|
||||||
$send_args->{action} = 'upload_video_note';
|
$send_args->{action} = 'upload_video_note';
|
||||||
}
|
}
|
||||||
|
elsif ($args->{action} eq 'choose_sticker') {
|
||||||
|
$send_args->{action} = 'choose_sticker';
|
||||||
|
}
|
||||||
else {
|
else {
|
||||||
$send_args->{action} = 'typing';
|
$send_args->{action} = 'typing';
|
||||||
}
|
}
|
||||||
@@ -301,6 +472,121 @@ sub sendChatAction {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sub exportChatInviteLink {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to createChatInviteLink()?';
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in createChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/exportChatInviteLink";
|
||||||
|
my $api_response = $self->_post_request($url);
|
||||||
|
|
||||||
|
if ($api_response) {
|
||||||
|
return $api_response;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub createChatInviteLink {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to createChatInviteLink()?';
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in createChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
$send_args->{expire_date} = $args->{expire_date} if exists $args->{expire_date};
|
||||||
|
$send_args->{member_limit} = $args->{member_limit} if exists $args->{member_limit};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/createChatInviteLink";
|
||||||
|
my $api_response = $self->_post_request($url);
|
||||||
|
|
||||||
|
if ($api_response) {
|
||||||
|
return Teapot::Bot::Object::ChatInviteLink->create_from_hash($api_response, $self);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub editChatInviteLink {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to editChatInviteLink()?';
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in editChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($args->{invite_link}) {
|
||||||
|
cluck 'No invite_link supplied in editChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
$send_args->{invite_link} = $args->{invite_link};
|
||||||
|
$send_args->{expire_date} = $args->{expire_date} if exists $args->{expire_date};
|
||||||
|
$send_args->{member_limit} = $args->{member_limit} if exists $args->{member_limit};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/editChatInviteLink";
|
||||||
|
my $api_response = $self->_post_request($url);
|
||||||
|
|
||||||
|
if ($api_response) {
|
||||||
|
return Teapot::Bot::Object::ChatInviteLink->create_from_hash($api_response, $self);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sub revokeChatInviteLink {
|
||||||
|
my $self = shift;
|
||||||
|
my $args = shift || {};
|
||||||
|
my $send_args = {};
|
||||||
|
|
||||||
|
my $token = $self->token || croak 'No token supplied to revokeChatInviteLink()?';
|
||||||
|
|
||||||
|
unless ($args->{chat_id}) {
|
||||||
|
cluck 'No chat_id supplied in revokeChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
unless ($args->{invite_link}) {
|
||||||
|
cluck 'No invite_link supplied in revokeChatInviteLink()';
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
$send_args->{chat_id} = $args->{chat_id};
|
||||||
|
$send_args->{invite_link} = $args->{invite_link};
|
||||||
|
|
||||||
|
my $url = "https://api.telegram.org/bot${token}/revokeChatInviteLink";
|
||||||
|
my $api_response = $self->_post_request($url);
|
||||||
|
|
||||||
|
if ($api_response) {
|
||||||
|
return Teapot::Bot::Object::ChatInviteLink->create_from_hash($api_response, $self);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
sub _add_getUpdates_handler {
|
sub _add_getUpdates_handler {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
@@ -319,11 +605,18 @@ sub _add_getUpdates_handler {
|
|||||||
|
|
||||||
$self->ua->get($updateURL => sub {
|
$self->ua->get($updateURL => sub {
|
||||||
my ($ua, $tx) = @_;
|
my ($ua, $tx) = @_;
|
||||||
my $res = $tx->res->json;
|
my $res = eval { $tx->res->json; };
|
||||||
my $items = $res->{result};
|
|
||||||
foreach my $item (@{$items}) {
|
# it looks like we can catch an error here if timeout or something bad occurs,
|
||||||
$last_update_id = $item->{update_id};
|
# try not to die in this case or we risk to stuck with $http_active=1 forever
|
||||||
$self->_process_message($item);
|
if ((defined $res) && $res ne '') {
|
||||||
|
my $items = $res->{result};
|
||||||
|
foreach my $item (@{$items}) {
|
||||||
|
$last_update_id = $item->{update_id};
|
||||||
|
$self->_process_message($item);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cluck "Unable to get update from API: $EVAL_ERROR";
|
||||||
}
|
}
|
||||||
|
|
||||||
$http_active = 0;
|
$http_active = 0;
|
||||||
@@ -342,21 +635,43 @@ sub _process_message {
|
|||||||
# There can be several types of responses. But only one response.
|
# There can be several types of responses. But only one response.
|
||||||
# https://core.telegram.org/bots/api#update
|
# https://core.telegram.org/bots/api#update
|
||||||
my $update;
|
my $update;
|
||||||
$update = Teapot::Bot::Object::Message->create_from_hash($item->{message}, $self) if $item->{message};
|
$update = Teapot::Bot::Object::Message->create_from_hash($item->{message}, $self) if $item->{message};
|
||||||
$update = Teapot::Bot::Object::Message->create_from_hash($item->{edited_message}, $self) if $item->{edited_message};
|
$update = Teapot::Bot::Object::Message->create_from_hash($item->{edited_message}, $self) if $item->{edited_message};
|
||||||
$update = Teapot::Bot::Object::Message->create_from_hash($item->{channel_post}, $self) if $item->{channel_post};
|
$update = Teapot::Bot::Object::Message->create_from_hash($item->{channel_post}, $self) if $item->{channel_post};
|
||||||
$update = Teapot::Bot::Object::Message->create_from_hash($item->{edited_channel_post}, $self) if $item->{edited_channel_post};
|
$update = Teapot::Bot::Object::Message->create_from_hash($item->{edited_channel_post}, $self) if $item->{edited_channel_post};
|
||||||
$update = Teapot::Bot::Object::Message->create_from_hash($item->{poll}, $self) if $item->{poll};
|
# Not yet implemented, we have no InlineQuery object yet
|
||||||
|
#$update = Teapot::Bot::Object::InlineQuery->create_from_hash($tem->{inline_query}, $self) if $item->{inline_query};
|
||||||
|
# Not yet implemented, we have no ChosenInlineResult object yet
|
||||||
|
#$update = Teapot::Bot::Object::ChosenInlineResult->create_from_hash($tem->{chosen_inline_result}, $self) if $item->{chosen_inline_result};
|
||||||
|
# Not yet implemented, we have no callback_query object yet, because we do not use this mechanism, s API should not gi us that shit
|
||||||
|
#$update = Teapot::Bot::Object::CallbackQuery->create_from_hash($tem->{callback_query}, $self) if $item->{callback_query};
|
||||||
|
# Not yet implemented, we have no ShippingQuery object yet
|
||||||
|
#$update = Teapot::Bot::Object::ShippingQuery->create_from_hash($tem->{shipping_query}, $self) if $item->{shipping_query};
|
||||||
|
# Not yet implemented, we have no PreCheckoutQuery object yet
|
||||||
|
#$update = Teapot::Bot::Object::PreCheckoutQuery->create_from_hash($tem->{pre_checkout_query}, $self) if $item->{pre_checkout_query};
|
||||||
|
$update = Teapot::Bot::Object::Poll->create_from_hash($item->{poll}, $self) if $item->{poll};
|
||||||
|
$update = Teapot::Bot::Object::PollAnswer->create_from_hash($item->{poll_answer}, $self) if $item->{poll_answer};
|
||||||
|
$update = Teapot::Bot::Object::ChatMemberUpdated->create_from_hash($item->{my_chat_member}, $self) if $item->{my_chat_member};
|
||||||
|
$update = Teapot::Bot::Object::ChatMemberUpdated->create_from_hash($item->{chat_member}, $self) if $item->{chat_member};
|
||||||
|
|
||||||
# if we got to this point without creating a response, it must be a type we
|
# if we got to this point without creating a response, it must be a type we
|
||||||
# don't handle yet
|
# don't handle yet
|
||||||
if (! $update) {
|
if (! $update) {
|
||||||
cluck 'Do not know how to handle this update: ' . Dumper($item);
|
cluck 'Do not know how to handle this update: ' . Dumper($item);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach my $listener (@{ $self->listeners }) {
|
foreach my $listener (@{ $self->listeners }) {
|
||||||
# call the listener code, supplying ourself and the update
|
# call the listener code, supplying ourself and the update
|
||||||
$listener->($self, $update);
|
my $evalRet = eval {
|
||||||
|
$listener->($self, $update);
|
||||||
|
return 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
unless ($evalRet) {
|
||||||
|
cluck "An error occured during update processing: $EVAL_ERROR";
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@@ -493,6 +808,25 @@ of Chat User.
|
|||||||
|
|
||||||
On error returns hash reference with error set to 1
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 banChatMember
|
||||||
|
|
||||||
|
This is the wrapper around the C<banChatMember> API method. See
|
||||||
|
L<https://core.telegram.org/bots/api#banchatmember>.
|
||||||
|
|
||||||
|
Takes chat_id, and user_id as arguments. And optionally until_date and
|
||||||
|
revoke_messages.
|
||||||
|
|
||||||
|
Returns nothing, it's send-only method (Telegram API returns true on success)
|
||||||
|
|
||||||
|
=head2 unbanChatMember
|
||||||
|
|
||||||
|
This is the wrapper around the C<unbanChatMember> API method. See
|
||||||
|
L<https://core.telegram.org/bots/api#unbanchatmember>.
|
||||||
|
|
||||||
|
Takes chat_id, and user_id as arguments. And optionally only_if_banned.
|
||||||
|
|
||||||
|
Returns nothing, it's send-only method (Telegram API returns true on success)
|
||||||
|
|
||||||
=head2 getChat
|
=head2 getChat
|
||||||
|
|
||||||
This is the wrapper around the C<getChat> API method. See
|
This is the wrapper around the C<getChat> API method. See
|
||||||
@@ -504,6 +838,15 @@ Returns the L<Teapot::Bot::Object::Chat> that represents properties of Chat.
|
|||||||
|
|
||||||
On error returns hash reference with error set to 1
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 leaveChat
|
||||||
|
|
||||||
|
This is the wrapper around the C<leaveChat> API method. See
|
||||||
|
L<https://core.telegram.org/bots/api#leavechat>.
|
||||||
|
|
||||||
|
Takes chat_id as argument.
|
||||||
|
|
||||||
|
Returns nothing, it's send-only method (Telegram API returns true on success)
|
||||||
|
|
||||||
=head2 sendMessage
|
=head2 sendMessage
|
||||||
|
|
||||||
See L<https://core.telegram.org/bots/api#sendmessage>.
|
See L<https://core.telegram.org/bots/api#sendmessage>.
|
||||||
@@ -520,6 +863,14 @@ Returns a L<Teapot::Bot::Object::Message> object.
|
|||||||
|
|
||||||
On error returns hash reference with error set to 1
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 deleteMessage
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#deletemessage>.
|
||||||
|
|
||||||
|
Returns a L<Teapot::Bot::Object::Message> object.
|
||||||
|
|
||||||
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
=head2 sendPhoto
|
=head2 sendPhoto
|
||||||
|
|
||||||
See L<https://core.telegram.org/bots/api#sendphoto>.
|
See L<https://core.telegram.org/bots/api#sendphoto>.
|
||||||
@@ -533,6 +884,47 @@ See L<https://core.telegram.org/bots/api#sendchataction>.
|
|||||||
|
|
||||||
Returns nothing, it's send-only method (Telegram API returns true on success)
|
Returns nothing, it's send-only method (Telegram API returns true on success)
|
||||||
|
|
||||||
|
=head2 exportChatInviteLink
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#exportchatinvitelink>
|
||||||
|
|
||||||
|
Takes chat_id as argument.
|
||||||
|
|
||||||
|
Returns a raw api answer.
|
||||||
|
|
||||||
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 createChatInviteLink
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#createchatinvitelink>
|
||||||
|
|
||||||
|
Takes chat_id as argument. And optionally expire_date and member_limit.
|
||||||
|
|
||||||
|
Returns a L<Teapot::Bot::Object::ChatInviteLink> object.
|
||||||
|
|
||||||
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 editChatInviteLink
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#editchatinvitelink>
|
||||||
|
|
||||||
|
Takes chat_id and invite_link as arguments. And optionally expire_date
|
||||||
|
and member_limit.
|
||||||
|
|
||||||
|
Returns a L<Teapot::Bot::Object::ChatInviteLink> object.
|
||||||
|
|
||||||
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
|
=head2 revokeChatInviteLink
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#revokechatinvitelink>
|
||||||
|
|
||||||
|
Takes chat_id and invite_link as arguments.
|
||||||
|
|
||||||
|
Returns a L<Teapot::Bot::Object::ChatInviteLink> object.
|
||||||
|
|
||||||
|
On error returns hash reference with error set to 1
|
||||||
|
|
||||||
=head1 SEE ALSO
|
=head1 SEE ALSO
|
||||||
|
|
||||||
=over 4
|
=over 4
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use Carp qw/croak/;
|
|||||||
$Teapot::Bot::Object::Animation::VERSION = '0.022';
|
$Teapot::Bot::Object::Animation::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'width';
|
has 'width';
|
||||||
has 'height';
|
has 'height';
|
||||||
has 'duration';
|
has 'duration';
|
||||||
@@ -17,7 +18,8 @@ has 'mime_type';
|
|||||||
has 'file_size';
|
has 'file_size';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { scalar => [qw/file_id width height duration file_name mime_type file_size/],
|
return { scalar => [qw/file_id file_unique_id width height duration file_name mime_type
|
||||||
|
file_size/],
|
||||||
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/],
|
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,15 +6,18 @@ use Mojo::Base 'Teapot::Bot::Object::Base';
|
|||||||
$Teapot::Bot::Object::Audio::VERSION = '0.022';
|
$Teapot::Bot::Object::Audio::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'duration';
|
has 'duration';
|
||||||
has 'performer';
|
has 'performer'; # Optional. Performer of the audio as defined by sender or by audio tags
|
||||||
has 'title';
|
has 'title'; # Optional. Title of the audio as defined by sender or by audio tags
|
||||||
has 'mime_type';
|
has 'file_name'; # Optional. Original filename as defined by sender
|
||||||
has 'file_size';
|
has 'mime_type'; # Optional. MIME type of the file as defined by sender
|
||||||
has 'thumb'; #PhotoSize
|
has 'file_size'; # Optional. File size
|
||||||
|
has 'thumb'; # Optional. Thumbnail of the album cover to which the music file belongs
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { scalar => [qw/file_id duration performer title mime_type file_size/],
|
return { scalar => [qw/file_id file_unique_id duration performer title file_name mime_type
|
||||||
|
file_size/],
|
||||||
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/],
|
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package Teapot::Bot::Object::Base;
|
|||||||
|
|
||||||
use Mojo::Base -base;
|
use Mojo::Base -base;
|
||||||
use List::Util qw/any/;
|
use List::Util qw/any/;
|
||||||
use Carp qw/croak/;
|
use Carp qw/croak cluck/;
|
||||||
|
use Data::Dumper;
|
||||||
|
use JSON::PP ();
|
||||||
|
|
||||||
$Teapot::Bot::Object::Base::VERSION = '0.022';
|
$Teapot::Bot::Object::Base::VERSION = '0.022';
|
||||||
|
|
||||||
@@ -14,6 +16,11 @@ sub arrays { return qw// } # override if needed
|
|||||||
sub _field_is_array {
|
sub _field_is_array {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $field = shift;
|
my $field = shift;
|
||||||
|
|
||||||
|
unless (defined $field) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (any { /^$field$/ } $self->arrays) {
|
if (any { /^$field$/ } $self->arrays) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@@ -25,12 +32,39 @@ sub array_of_arrays { return qw// } #override if needed
|
|||||||
sub _field_is_array_of_arrays {
|
sub _field_is_array_of_arrays {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $field = shift;
|
my $field = shift;
|
||||||
|
|
||||||
|
unless (defined $field) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (any { /^$field$/ } $self->array_of_arrays) {
|
if (any { /^$field$/ } $self->array_of_arrays) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sub create_from_array {
|
||||||
|
my $class = shift;
|
||||||
|
my $array = shift;
|
||||||
|
my $brain = shift || croak 'No brain supplied to create_from_array()';
|
||||||
|
my $obj = shift || $class->new(_brain => $brain);
|
||||||
|
|
||||||
|
unless (defined $array) {
|
||||||
|
cluck 'Array is undef';
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
unless (ref ($array) eq 'ARRAY') {
|
||||||
|
cluck 'Not array ' . Dumper ($array);
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
cluck "Dumping class: " . Dumper ($class);
|
||||||
|
cluck "Dumping array: " . Dumper ($array);
|
||||||
|
|
||||||
|
# it's stub, return $obj
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
# create an object from a hash. Needs to deal with the nested types, and
|
# create an object from a hash. Needs to deal with the nested types, and
|
||||||
# arrays
|
# arrays
|
||||||
@@ -40,11 +74,27 @@ sub create_from_hash {
|
|||||||
my $brain = shift || croak 'No brain supplied to create_from_hash()';
|
my $brain = shift || croak 'No brain supplied to create_from_hash()';
|
||||||
my $obj = $class->new(_brain => $brain);
|
my $obj = $class->new(_brain => $brain);
|
||||||
|
|
||||||
|
unless (defined $hash) {
|
||||||
|
cluck 'Hash is undef';
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
unless (ref ($hash) eq 'HASH') {
|
||||||
|
if (ref ($hash) eq 'ARRAY') {
|
||||||
|
return create_from_array($class, $hash, $brain);
|
||||||
|
}
|
||||||
|
|
||||||
|
cluck 'Not a hash ' . Dumper ($hash);
|
||||||
|
return $obj;
|
||||||
|
}
|
||||||
|
|
||||||
# deal with each type of field
|
# deal with each type of field
|
||||||
foreach my $type (keys %{ $class->fields }) {
|
foreach my $type (keys %{ $class->fields }) {
|
||||||
my @fields_of_this_type = @{ $class->fields->{$type} };
|
my @fields_of_this_type = @{ $class->fields->{$type} };
|
||||||
|
|
||||||
foreach my $field (@fields_of_this_type) {
|
foreach my $field (@fields_of_this_type) {
|
||||||
|
# ignore undefined fields (sic!)
|
||||||
|
next if (! defined $field);
|
||||||
|
|
||||||
# ignore fields for which we have no value in the hash
|
# ignore fields for which we have no value in the hash
|
||||||
next if (! defined $hash->{$field} );
|
next if (! defined $hash->{$field} );
|
||||||
|
|||||||
@@ -5,33 +5,46 @@ use Mojo::Base 'Teapot::Bot::Object::Base';
|
|||||||
use Teapot::Bot::Object::ChatPhoto;
|
use Teapot::Bot::Object::ChatPhoto;
|
||||||
use Teapot::Bot::Object::Message;
|
use Teapot::Bot::Object::Message;
|
||||||
use Teapot::Bot::Object::ChatPermissions;
|
use Teapot::Bot::Object::ChatPermissions;
|
||||||
|
use Teapot::Bot::Object::ChatLocation;
|
||||||
|
|
||||||
$Teapot::Bot::Object::Chat::VERSION = '0.022';
|
$Teapot::Bot::Object::Chat::VERSION = '0.022';
|
||||||
|
|
||||||
has 'id';
|
has 'id';
|
||||||
has 'type';
|
has 'type';
|
||||||
has 'title'; # Optional.
|
has 'title'; # Optional.
|
||||||
has 'username'; # Optional.
|
has 'username'; # Optional.
|
||||||
has 'first_name'; # Optional.
|
has 'first_name'; # Optional.
|
||||||
has 'last_name'; # Optional.
|
has 'last_name'; # Optional.
|
||||||
has 'photo'; # Teapot::Bot::Object::ChatPhoto. Optional. Returned only in getChat.
|
has 'photo'; # Teapot::Bot::Object::ChatPhoto. Optional. Returned only in getChat.
|
||||||
has 'description'; # Optional. Returned only in getChat.
|
has 'bio'; # Optional. Bio of the other party in a private chat. Returned only in getChat.
|
||||||
has 'invite_link'; # Optional. Returned only in getChat.
|
has 'has_private_forwards'; # Optional. True, if privacy settings of the other party in the private chat allows to
|
||||||
has 'pinned_message'; # Teapot::Bot::Object::Message
|
# use tg://user?id=<user_id> links only in chats with the user.
|
||||||
has 'permissions'; # Teapot::Bot::Object::ChatPermissions. Optional. Default chat member permissions, for
|
# Returned only in getChat.
|
||||||
# groups and supergroups. Returned only in getChat.
|
has 'description'; # Optional. Returned only in getChat.
|
||||||
has 'slow_mode_delay'; # Optional. Returned only in getChat.
|
has 'invite_link'; # Optional. Returned only in getChat.
|
||||||
has 'sticker_set_name'; # Optional. Returned only in getChat.
|
has 'pinned_message'; # Teapot::Bot::Object::Message
|
||||||
has 'can_set_sticker_set'; # Optional. Returned only in getChat.
|
has 'permissions'; # Teapot::Bot::Object::ChatPermissions. Optional. Default chat member permissions, for
|
||||||
|
# groups and supergroups. Returned only in getChat.
|
||||||
|
has 'slow_mode_delay'; # Optional. Returned only in getChat.
|
||||||
|
has 'message_auto_delete_time'; # Optional. The time after which all messages sent to the chat will be automatically
|
||||||
|
# deleted; in seconds. Returned only in getChat.
|
||||||
|
has 'has_protected_content'; # Optional. True, if messages from the chat can't be forwarded to other chats.
|
||||||
|
# Returned only in getChat.
|
||||||
|
has 'sticker_set_name'; # Optional. Returned only in getChat.
|
||||||
|
has 'can_set_sticker_set'; # Optional. Returned only in getChat.
|
||||||
|
has 'linked_chat_id'; # Optional. greater than 32 bits, smaller than 52 bits
|
||||||
|
has 'location'; # Optional. Returned only in getChat.
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
'scalar' => [qw/id type title username first_name last_name description
|
'scalar' => [qw/id type title username first_name last_name bio
|
||||||
invite_link slow_mode_delay sticker_set_name
|
has_private_forwards description invite_link slow_mode_delay
|
||||||
can_set_sticker_set /],
|
message_auto_delete_time has_protected_content
|
||||||
|
sticker_set_name can_set_sticker_set linked_chat_id/],
|
||||||
'Teapot::Bot::Object::ChatPhoto' => [qw/photo/],
|
'Teapot::Bot::Object::ChatPhoto' => [qw/photo/],
|
||||||
'Teapot::Bot::Object::Message' => [qw/pinned_message/],
|
'Teapot::Bot::Object::Message' => [qw/pinned_message/],
|
||||||
'Teapot::Bot::Object::ChatPermissions' => [qw/permissions/],
|
'Teapot::Bot::Object::ChatPermissions' => [qw/permissions/],
|
||||||
|
'Teapot::Bot::Object::ChatLocation' => [qw/location/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
61
lib/Teapot/Bot/Object/ChatInviteLink.pm
Normal file
61
lib/Teapot/Bot/Object/ChatInviteLink.pm
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package Teapot::Bot::Object::ChatInviteLink;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'ChatInviteLink' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
use Teapot::Bot::Object::User;
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::ChatInviteLink::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'invite_link';
|
||||||
|
has 'creator';
|
||||||
|
has 'creates_join_request';
|
||||||
|
has 'is_primary';
|
||||||
|
has 'is_revoked';
|
||||||
|
has 'name';
|
||||||
|
has 'expire_date'; # Optional. Point in time (Unix timestamp) when the link will expire or has been expired
|
||||||
|
has 'member_limit'; # Optional. Maximum number of users that can be members of the chat simultaneously after joining
|
||||||
|
# the chat via this invite link; 1-99999
|
||||||
|
has 'pending_join_request_count';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'scalar' => [qw/invite_link creates_join_request is_primary is_revoked name expire_date
|
||||||
|
member_limit pending_join_request_count/],
|
||||||
|
'Teapot::Bot::Object::User' => [qw/creator/],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::ChatInviteLink - The base class for Telegram message 'ChatInviteLink' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'ChatInviteLink' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#chatinvitelink> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::ChatInviteLink> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
51
lib/Teapot/Bot/Object/ChatLocation.pm
Normal file
51
lib/Teapot/Bot/Object/ChatLocation.pm
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package Teapot::Bot::Object::ChatLocation;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'ChatLocation' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::ChatLocation::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'location';
|
||||||
|
has 'address';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'Teapot::Bot::Object::Location' => [qw/location/],
|
||||||
|
'scalar' => [qw/address/],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::ChatLocation - The base class for Telegram message 'ChatLocation' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'ChatLocation' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#chatlocation> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::ChatLocation> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2019 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
@@ -3,39 +3,127 @@ package Teapot::Bot::Object::ChatMember;
|
|||||||
|
|
||||||
use Mojo::Base 'Teapot::Bot::Object::Base';
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
use Teapot::Bot::Object::User;
|
use Teapot::Bot::Object::User;
|
||||||
|
use Carp qw(cluck);
|
||||||
|
|
||||||
$Teapot::Bot::Object::ChatMember::VERSION = '0.022';
|
$Teapot::Bot::Object::ChatMember::VERSION = '0.022';
|
||||||
|
|
||||||
has 'user';
|
# ChatMemberOwner
|
||||||
has 'status';
|
has 'user';
|
||||||
has 'custom_title'; # optional. Owner and administrators only.
|
has 'status';
|
||||||
has 'until'; # optional. Restricted and kicked only.
|
has 'custom_title'; # optional. Owner and administrators only.
|
||||||
has 'can_be_edited'; # optional. Administrators only.
|
has 'is_anonymous'; # Optional. Owner and administrators only.
|
||||||
has 'can_post_messages'; # optional. Administrators only.
|
|
||||||
has 'can_edit_messages'; # optional. Administrators only.
|
# ChatMemberAdministrator
|
||||||
has 'can_delete_messages'; # optional. Administrators only.
|
# has 'user';
|
||||||
has 'can_restrict_members'; # optional. Administrators only.
|
# has 'status';
|
||||||
has 'can_promote_members'; # optional. Administrators only.
|
has 'can_be_edited'; # optional. Administrators only.
|
||||||
has 'can_change_info'; # optional. Administrators and restricted only.
|
# has 'custom_title'; # optional. Owner and administrators only.
|
||||||
has 'can_invite_users'; # optional. Administrators and restricted only.
|
# has 'is_anonymous'; # Optional. Owner and administrators only.
|
||||||
has 'can_pin_messages'; # optional. Administrators and restricted only.
|
has 'can_manage_chat'; # Optional. Administrators only. True, if the administrator can access the chat event
|
||||||
has 'is_member'; # optional. Restricted only.
|
# log, chat statistics, message statistics in channels, see channel members, see
|
||||||
has 'can_send_messages'; # optional. Restricted only.
|
# anonymous administrators in supergroups and ignore slow mode. Implied by any other
|
||||||
has 'can_send_media_messages'; # optional. Restricted only.
|
# administrator privilege
|
||||||
has 'can_send_polls'; # optional. Restricted only.
|
has 'can_post_messages'; # optional. Administrators only.
|
||||||
has 'can_send_other_messages'; # optional. Restricted only.
|
has 'can_edit_messages'; # optional. Administrators only.
|
||||||
has 'can_add_web_page_previews'; # optional. Restricted only.
|
has 'can_delete_messages'; # optional. Administrators only.
|
||||||
|
has 'can_manage_voice_chats'; # Optional. Administrators only. True, if the administrator can manage voice chats
|
||||||
|
has 'can_restrict_members'; # optional. Administrators only.
|
||||||
|
has 'can_promote_members'; # optional. Administrators only.
|
||||||
|
has 'can_change_info'; # optional. Administrators and restricted only.
|
||||||
|
has 'can_invite_users'; # optional. Administrators and restricted only.
|
||||||
|
has 'can_pin_messages'; # optional. Administrators and restricted only.
|
||||||
|
|
||||||
|
# ChatMemberMember
|
||||||
|
# has 'status';
|
||||||
|
# has 'user';
|
||||||
|
|
||||||
|
# ChatMemberRestricted
|
||||||
|
# has 'status';
|
||||||
|
# has 'user';
|
||||||
|
has 'is_member'; # optional. Restricted only.
|
||||||
|
# has 'can_change_info'; # optional. Administrators and restricted only.
|
||||||
|
# has 'can_invite_users'; # optional. Administrators and restricted only.
|
||||||
|
# has 'can_pin_messages'; # optional. Administrators and restricted only.
|
||||||
|
has 'can_send_messages'; # optional. Restricted only.
|
||||||
|
has 'can_send_media_messages'; # optional. Restricted only.
|
||||||
|
has 'can_send_polls'; # optional. Restricted only.
|
||||||
|
has 'can_send_other_messages'; # optional. Restricted only.
|
||||||
|
has 'can_add_web_page_previews'; # optional. Restricted only.
|
||||||
|
has 'until_date'; # optional. Restricted and kicked only.
|
||||||
|
|
||||||
|
# ChatMemberLeft
|
||||||
|
# has 'status';
|
||||||
|
# has 'user';
|
||||||
|
|
||||||
|
# ChatMemberBanned
|
||||||
|
# has 'status';
|
||||||
|
# has 'user';
|
||||||
|
# has 'until_date'; # optional. Restricted and kicked only.
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
'scalar' => [qw/status custom_title until can_be_edited can_post_messages can_edit_messages
|
'scalar' => [qw/status custom_title is_anonymous can_be_edited can_manage_chat can_post_messages
|
||||||
can_delete_messages can_restrict_members can_promote_members can_change_info
|
can_edit_messages can_delete_messages can_manage_voice_chats can_restrict_members
|
||||||
can_invite_users can_pin_messages is_member can_send_messages
|
can_promote_members can_change_info can_invite_users can_pin_messages is_member
|
||||||
can_send_media_messages can_send_polls can_send_other_messages can_add_web_page_previews/],
|
can_send_messages can_send_media_messages can_send_polls can_send_other_messages
|
||||||
|
can_add_web_page_previews until_date/],
|
||||||
'Teapot::Bot::Object::User' => [qw/user/],
|
'Teapot::Bot::Object::User' => [qw/user/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
sub canDeleteMessage {
|
||||||
|
my $self = shift;
|
||||||
|
my $chatid = shift;
|
||||||
|
|
||||||
|
my $can_delete = 0;
|
||||||
|
|
||||||
|
if ($chatid < 0) {
|
||||||
|
# group chat
|
||||||
|
my $chatobj = $self->getChat ({ 'chat_id' => $chatid });
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($chatobj == 0 || $chatobj->{error}) {
|
||||||
|
cluck "Unable to get chat info for $chatid from telegram API";
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $myObj = $self->getMe ();
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($myObj == 0 || $myObj->{error}) {
|
||||||
|
cluck "Unable to get chat info for $chatid from telegram API";
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $myid = $myObj->id;
|
||||||
|
my $me = $self->getChatMember ({ 'chat_id' => $chatid, 'user_id' => $myid });
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($me == 0 || $me->{error}) {
|
||||||
|
cluck 'Unable to get chat info for bot itself from telegram API';
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
# bot can delete msg if it is group and it is admin there.
|
||||||
|
if ($chatobj->{'type'} eq 'group') {
|
||||||
|
if ($me->{'status'} eq 'administrator') {
|
||||||
|
$can_delete = 1;
|
||||||
|
}
|
||||||
|
# in supergroup bot must be granted with can_delete_messages
|
||||||
|
} elsif (($chatobj->{'type'} eq 'supergroup') || ($chatobj->{'type'} eq 'channel')) {
|
||||||
|
if ($me->{'can_delete_messages'}) {
|
||||||
|
$can_delete = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
# 1 on 1 chat with user
|
||||||
|
$can_delete = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $can_delete;
|
||||||
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|
||||||
__END__
|
__END__
|
||||||
@@ -58,6 +146,14 @@ The base class for Telegram 'ChatMember' type objects.
|
|||||||
See L<https://core.telegram.org/bots/api#chatmember> for details of the
|
See L<https://core.telegram.org/bots/api#chatmember> for details of the
|
||||||
attributes available for L<Teapot::Bot::Object::ChatMember> objects.
|
attributes available for L<Teapot::Bot::Object::ChatMember> objects.
|
||||||
|
|
||||||
|
=head1 METHODS
|
||||||
|
|
||||||
|
=head2 canDeleteMessage
|
||||||
|
|
||||||
|
A convenience method to check if bot can delete message in given conversation.
|
||||||
|
|
||||||
|
Returns true if the bot can delete the message in given conversation, otherwise false.
|
||||||
|
|
||||||
=head1 AUTHOR
|
=head1 AUTHOR
|
||||||
|
|
||||||
Sergei Fedosov <eleksir@gmail.com>
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|||||||
67
lib/Teapot/Bot/Object/ChatMemberUpdated.pm
Normal file
67
lib/Teapot/Bot/Object/ChatMemberUpdated.pm
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package Teapot::Bot::Object::ChatMemberUpdated;
|
||||||
|
# ABSTRACT: The base class for Telegram 'ChatMemberUpdated' type objects
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
use Teapot::Bot::Object::Chat;
|
||||||
|
use Teapot::Bot::Object::User;
|
||||||
|
use Teapot::Bot::Object::ChatMember;
|
||||||
|
use Teapot::Bot::Object::ChatInviteLink;
|
||||||
|
use Teapot::Bot::Object::Voice;
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::ChatMemberUpdated::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'chat';
|
||||||
|
has 'from';
|
||||||
|
has 'date';
|
||||||
|
has 'old_chat_member';
|
||||||
|
has 'new_chat_member';
|
||||||
|
has 'text'; # Undocumented as of Bot API 5.2
|
||||||
|
has 'voice'; # Undocumented as of Bot API 5.2
|
||||||
|
has 'invite_link'; # Optional. Chat invite link, which was used by the user to join the chat; for joining by
|
||||||
|
# invite link events only.
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'Teapot::Bot::Object::Chat' => [qw/chat/],
|
||||||
|
'Teapot::Bot::Object::User' => [qw/from/],
|
||||||
|
'scalar' => [qw/date text/],
|
||||||
|
'Teapot::Bot::Object::ChatMember' => [qw/old_chat_member new_chat_member/],
|
||||||
|
'Teapot::Bot::Object::Voice' => [qw/voice/],
|
||||||
|
'Teapot::Bot::Object::ChatInviteLink' => [qw/invite_link/]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::ChatMemberUpdated - The base class for Telegram 'ChatMemberUpdated' type objects
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram 'ChatMemberUpdated' type objects.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#chatmemberupdated> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::ChatMemberUpdated> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package Teapot::Bot::Object::ChatPermissions;
|
package Teapot::Bot::Object::ChatPermissions;
|
||||||
# ABSTRACT: The base class for Telegram 'ChatPermissions' type objects
|
# ABSTRACT: The base class for Telegram 'ChatPermissions' type objects
|
||||||
|
use Carp qw(carp);
|
||||||
use Mojo::Base 'Teapot::Bot::Object::Base';
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
$Teapot::Bot::Object::ChatPermissions::VERSION = '0.022';
|
$Teapot::Bot::Object::ChatPermissions::VERSION = '0.022';
|
||||||
@@ -28,6 +28,53 @@ sub fields {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sub canTalk {
|
||||||
|
my $self = shift;
|
||||||
|
my $chatid = shift;
|
||||||
|
|
||||||
|
my $can_talk = 0;
|
||||||
|
|
||||||
|
if ($chatid < 0) {
|
||||||
|
# group chat
|
||||||
|
my $chatobj = $self->_brain->getChat ({ 'chat_id' => $chatid });
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($chatobj == 0 || $chatobj->{error}) {
|
||||||
|
carp "Unable to get chat info for $chatid from telegram API";
|
||||||
|
return $can_talk;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $myObj = $self->_brain->getMe ();
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($myObj == 0 || $myObj->{error}) {
|
||||||
|
carp "Unable to get chat info for $chatid from telegram API";
|
||||||
|
return $can_talk;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $myid = $myObj->id;
|
||||||
|
my $me = $self->_brain->getChatMember ({ 'chat_id' => $chatid, 'user_id' => $myid });
|
||||||
|
|
||||||
|
# on api error, keep silence
|
||||||
|
if ($me == 0 || $me->{error}) {
|
||||||
|
carp 'Unable to get chat info for bot itself from telegram API';
|
||||||
|
return $can_talk;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($me->{'status'} eq 'administrator') {
|
||||||
|
$can_talk = 1;
|
||||||
|
} else {
|
||||||
|
my $group_talk = int ($chatobj->{permissions}->{can_send_messages});
|
||||||
|
$can_talk = $group_talk;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
# 1 on 1 chat with user
|
||||||
|
$can_talk = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $can_talk;
|
||||||
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|
||||||
__END__
|
__END__
|
||||||
@@ -50,6 +97,14 @@ The base class for Telegram 'ChatPermissions' type objects.
|
|||||||
See L<https://core.telegram.org/bots/api#chatpermissions> for details of the
|
See L<https://core.telegram.org/bots/api#chatpermissions> for details of the
|
||||||
attributes available for L<Teapot::Bot::Object::ChatPermissions> objects.
|
attributes available for L<Teapot::Bot::Object::ChatPermissions> objects.
|
||||||
|
|
||||||
|
=head1 METHODS
|
||||||
|
|
||||||
|
=head2 canTalk
|
||||||
|
|
||||||
|
A convenience method to check if bot can talk in given conversation.
|
||||||
|
|
||||||
|
Returns true if the bot can talk in given conversation, otherwise false.
|
||||||
|
|
||||||
=head1 AUTHOR
|
=head1 AUTHOR
|
||||||
|
|
||||||
Sergei Fedosov <eleksir@gmail.com>
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ use Mojo::Base 'Teapot::Bot::Object::Base';
|
|||||||
$Teapot::Bot::Object::ChatPhoto::VERSION = '0.022';
|
$Teapot::Bot::Object::ChatPhoto::VERSION = '0.022';
|
||||||
|
|
||||||
has 'small_file_id';
|
has 'small_file_id';
|
||||||
|
has 'small_file_unique_id';
|
||||||
has 'big_file_id';
|
has 'big_file_id';
|
||||||
|
has 'big_file_unique_id';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
'scalar' => [qw/small_file_id big_file_id/],
|
'scalar' => [qw/small_file_id small_file_unique_id big_file_id big_file_unique_id/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,11 @@ has 'phone_number';
|
|||||||
has 'first_name';
|
has 'first_name';
|
||||||
has 'last_name';
|
has 'last_name';
|
||||||
has 'user_id';
|
has 'user_id';
|
||||||
|
has 'vcard';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
scalar => [qw/phone_number first_name last_name user_id/],
|
scalar => [qw/phone_number first_name last_name user_id vcard/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
48
lib/Teapot/Bot/Object/Dice.pm
Normal file
48
lib/Teapot/Bot/Object/Dice.pm
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package Teapot::Bot::Object::Dice;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'Dice' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::Dice::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'emoji';
|
||||||
|
has 'value';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return { scalar => [qw/emoji value/] };
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::Dice - The base class for Telegram message 'Dice' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'Dice' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#dice> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::dice> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2019 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
@@ -8,6 +8,7 @@ use Teapot::Bot::Object::PhotoSize;
|
|||||||
$Teapot::Bot::Object::Document::VERSION = '0.022';
|
$Teapot::Bot::Object::Document::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'thumb'; #PhotoSize
|
has 'thumb'; #PhotoSize
|
||||||
has 'file_name';
|
has 'file_name';
|
||||||
has 'mime_type';
|
has 'mime_type';
|
||||||
@@ -15,7 +16,7 @@ has 'file_size';
|
|||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
scalar => [qw/file_id file_name mime_type file_size/],
|
scalar => [qw/file_id file_unique_id file_name mime_type file_size/],
|
||||||
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/]
|
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ has 'pay';
|
|||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { 'scalar' => [qw/text url callback_data switch_inline_query
|
return { 'scalar' => [qw/text url callback_data switch_inline_query
|
||||||
switch_inline_query_current_chat switch_inline_query_current_chat
|
switch_inline_query_current_chat pay/],
|
||||||
pay/],
|
|
||||||
'Teapot::Bot::Object::LoginUrl' => [qw/login_url/],
|
'Teapot::Bot::Object::LoginUrl' => [qw/login_url/],
|
||||||
'Teapot::Bot::Object::CallbackGame' => [qw/callback_game/],
|
'Teapot::Bot::Object::CallbackGame' => [qw/callback_game/],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,9 +7,13 @@ $Teapot::Bot::Object::Location::VERSION = '0.022';
|
|||||||
|
|
||||||
has 'longitude';
|
has 'longitude';
|
||||||
has 'latitude';
|
has 'latitude';
|
||||||
|
has 'horizontal_accuracy';
|
||||||
|
has 'live_period';
|
||||||
|
has 'heading';
|
||||||
|
has 'proximity_alert_radius';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { scalar => [qw/longitude latitude/] };
|
return { scalar => [qw/longitude latitude horizontal_accuracy live_period heading proximity_alert_radius/] };
|
||||||
}
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|||||||
@@ -27,48 +27,56 @@ use Teapot::Bot::Object::Venue;
|
|||||||
use Teapot::Bot::Object::SuccessfulPayment;
|
use Teapot::Bot::Object::SuccessfulPayment;
|
||||||
use Teapot::Bot::Object::PassportData;
|
use Teapot::Bot::Object::PassportData;
|
||||||
use Teapot::Bot::Object::InlineKeyboardMarkup;
|
use Teapot::Bot::Object::InlineKeyboardMarkup;
|
||||||
|
use Teapot::Bot::Object::ProximityAlertTriggered;
|
||||||
|
use Teapot::Bot::Object::Dice;
|
||||||
|
use Teapot::Bot::Object::MessageAutoDeleteTimerChanged;
|
||||||
|
use Teapot::Bot::Object::VoiceChatScheduled;
|
||||||
|
use Teapot::Bot::Object::VoiceChatStarted;
|
||||||
|
use Teapot::Bot::Object::VoiceChatEnded;
|
||||||
|
use Teapot::Bot::Object::VoiceChatParticipantsInvited;
|
||||||
|
|
||||||
use Data::Dumper;
|
use Data::Dumper;
|
||||||
|
use Carp qw(cluck);
|
||||||
|
|
||||||
$Teapot::Bot::Object::Message::VERSION = '0.022';
|
$Teapot::Bot::Object::Message::VERSION = '0.022';
|
||||||
|
|
||||||
# basic message stuff
|
# basic message stuff
|
||||||
has 'message_id';
|
has 'message_id';
|
||||||
has 'from'; # User
|
has 'from'; # User
|
||||||
|
has 'sender_chat'; # Chat
|
||||||
has 'date';
|
has 'date';
|
||||||
has 'chat'; # Chat
|
has 'chat'; # Chat
|
||||||
|
|
||||||
has 'forward_from'; # User
|
has 'forward_from'; # User
|
||||||
has 'forward_from_chat'; # Chat
|
has 'forward_from_chat'; # Chat
|
||||||
has 'forward_from_message_id';
|
has 'forward_from_message_id';
|
||||||
has 'forward_signature';
|
has 'forward_signature';
|
||||||
has 'forward_sender_name';
|
has 'forward_sender_name';
|
||||||
has 'forward_date';
|
has 'forward_date';
|
||||||
|
has 'is_automatic_forward';
|
||||||
has 'reply_to_message'; # Message
|
has 'reply_to_message'; # Message
|
||||||
has 'via_bot'; # User
|
has 'via_bot'; # User
|
||||||
has 'edit_date';
|
has 'edit_date';
|
||||||
|
has 'has_protected_content';
|
||||||
has 'media_group_id';
|
has 'media_group_id';
|
||||||
has 'author_signature';
|
has 'author_signature';
|
||||||
has 'text';
|
has 'text';
|
||||||
has 'entities'; # Array of MessageEntity
|
has 'entities'; # Array of MessageEntity
|
||||||
|
has 'animation'; # Animation
|
||||||
has 'caption_entities'; # Array of MessageEntity
|
|
||||||
|
|
||||||
has 'audio'; # Audio
|
has 'audio'; # Audio
|
||||||
has 'document'; # Document
|
has 'document'; # Document
|
||||||
has 'animation'; # Animation
|
|
||||||
has 'game'; # Game
|
|
||||||
has 'photo'; # Array of PhotoSize
|
has 'photo'; # Array of PhotoSize
|
||||||
has 'sticker'; # Sticker
|
has 'sticker'; # Sticker
|
||||||
has 'video'; # Video
|
has 'video'; # Video
|
||||||
has 'voice'; # Voice
|
|
||||||
has 'video_note'; # VideoNote
|
has 'video_note'; # VideoNote
|
||||||
|
has 'voice'; # Voice
|
||||||
has 'caption';
|
has 'caption';
|
||||||
|
has 'caption_entities'; # Array of MessageEntity
|
||||||
has 'contact'; # Contact
|
has 'contact'; # Contact
|
||||||
has 'location'; # Location
|
has 'dice';
|
||||||
has 'venue'; # Venue
|
has 'game';
|
||||||
has 'poll'; # Poll
|
has 'poll'; # Poll
|
||||||
|
has 'venue'; # Venue
|
||||||
|
has 'location'; # Location
|
||||||
has 'new_chat_members'; # Array of User
|
has 'new_chat_members'; # Array of User
|
||||||
has 'left_chat_member'; # User
|
has 'left_chat_member'; # User
|
||||||
has 'new_chat_title';
|
has 'new_chat_title';
|
||||||
@@ -77,6 +85,7 @@ has 'delete_chat_photo';
|
|||||||
has 'group_chat_created';
|
has 'group_chat_created';
|
||||||
has 'supergroup_chat_created';
|
has 'supergroup_chat_created';
|
||||||
has 'channel_chat_created';
|
has 'channel_chat_created';
|
||||||
|
has 'message_auto_delete_timer_changed'; # Optional. Service message: auto-delete timer settings changed in the chat
|
||||||
has 'migrate_to_chat_id';
|
has 'migrate_to_chat_id';
|
||||||
has 'migrate_from_chat_id';
|
has 'migrate_from_chat_id';
|
||||||
has 'pinned_message'; # Message
|
has 'pinned_message'; # Message
|
||||||
@@ -84,21 +93,26 @@ has 'invoice'; # Invoice
|
|||||||
has 'successful_payment'; # SuccessfulPayment
|
has 'successful_payment'; # SuccessfulPayment
|
||||||
has 'connected_website';
|
has 'connected_website';
|
||||||
has 'passport_data'; # PassportData
|
has 'passport_data'; # PassportData
|
||||||
|
has 'proximity_alert_triggered';
|
||||||
|
has 'voice_chat_scheduled'; # Optional. Service message: voice chat scheduled
|
||||||
|
has 'voice_chat_started'; # Optional. Service message: voice chat started
|
||||||
|
has 'voice_chat_ended'; # Optional. Service message: voice chat ended
|
||||||
|
has 'voice_chat_participants_invited'; # Optional. Service message: new participants invited to a voice chat
|
||||||
has 'reply_markup'; # Array of InlineKeyboardMarkup
|
has 'reply_markup'; # Array of InlineKeyboardMarkup
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
'scalar' => [qw/message_id date forward_from_message_id
|
'scalar' => [qw/message_id date forward_from_message_id
|
||||||
forward_signature forward_sender_name
|
forward_signature forward_sender_name
|
||||||
forward_date edit_date media_group_id
|
forward_date is_automatic_forward edit_date has_protected_content
|
||||||
author_signature text caption
|
media_group_id author_signature text caption
|
||||||
new_chat_title delete_chat_photo
|
new_chat_title delete_chat_photo
|
||||||
group_chat_created supergroup_chat_created
|
group_chat_created supergroup_chat_created
|
||||||
channel_chat_created migrate_to_chat_id
|
channel_chat_created migrate_to_chat_id
|
||||||
migrate_from_chat_id connected_website/],
|
migrate_from_chat_id connected_website/],
|
||||||
'Teapot::Bot::Object::User' => [qw/from forward_from via_bot new_chat_members left_chat_member /],
|
'Teapot::Bot::Object::User' => [qw/from forward_from via_bot new_chat_members left_chat_member /],
|
||||||
|
|
||||||
'Teapot::Bot::Object::Chat' => [qw/chat forward_from_chat/],
|
'Teapot::Bot::Object::Chat' => [qw/sender_chat chat forward_from_chat/],
|
||||||
'Teapot::Bot::Object::Message' => [qw/reply_to_message pinned_message/],
|
'Teapot::Bot::Object::Message' => [qw/reply_to_message pinned_message/],
|
||||||
'Teapot::Bot::Object::MessageEntity' => [qw/entities caption_entities /],
|
'Teapot::Bot::Object::MessageEntity' => [qw/entities caption_entities /],
|
||||||
|
|
||||||
@@ -122,7 +136,13 @@ sub fields {
|
|||||||
'Teapot::Bot::Object::SuccessfulPayment' => [qw/successful_payment/],
|
'Teapot::Bot::Object::SuccessfulPayment' => [qw/successful_payment/],
|
||||||
'Teapot::Bot::Object::PassportData' => [qw/passport_data/],
|
'Teapot::Bot::Object::PassportData' => [qw/passport_data/],
|
||||||
'Teapot::Bot::Object::InlineKeyboardMarkup' => [qw/reply_markup/],
|
'Teapot::Bot::Object::InlineKeyboardMarkup' => [qw/reply_markup/],
|
||||||
|
'Teapot::Bot::Object::ProximityAlertTriggered' => [qw/proximity_alert_triggered/],
|
||||||
|
'Teapot::Bot::Object::Dice' => [qw/dice/],
|
||||||
|
'Teapot::Bot::Object::MessageAutoDeleteTimerChanged' => [qw/message_auto_delete_timer_changed/],
|
||||||
|
'Teapot::Bot::Object::VoiceChatScheduled' => [qw/voice_chat_scheduled/],
|
||||||
|
'Teapot::Bot::Object::VoiceChatStarted' => [qw/voice_chat_started/],
|
||||||
|
'Teapot::Bot::Object::VoiceChatEnded' => [qw/voice_chat_ended/],
|
||||||
|
'Teapot::Bot::Object::VoiceChatParticipantsInvited' => [qw/voice_chat_participants_invited/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,12 +154,44 @@ sub arrays {
|
|||||||
sub reply {
|
sub reply {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
my $text = shift;
|
my $text = shift;
|
||||||
return $self->_brain->sendMessage({chat_id => $self->chat->id, text => $text});
|
|
||||||
|
my $chatid = $self->chat->id;
|
||||||
|
|
||||||
|
if (Teapot::Bot::Object::ChatPermissions->canTalk($self, $chatid)) {
|
||||||
|
return $self->_brain->sendMessage({chat_id => $chatid, text => $text});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {'error' => 1};
|
||||||
|
}
|
||||||
|
|
||||||
|
sub replyMd {
|
||||||
|
my $self = shift;
|
||||||
|
my $text = shift;
|
||||||
|
|
||||||
|
my $chatid = $self->chat->id;
|
||||||
|
|
||||||
|
if (Teapot::Bot::Object::ChatPermissions->canTalk ($self, $chatid)) {
|
||||||
|
my $send_args;
|
||||||
|
$send_args->{text} = $text;
|
||||||
|
$send_args->{parse_mode} = 'Markdown';
|
||||||
|
$send_args->{chat_id} = $chatid;
|
||||||
|
|
||||||
|
return $self->_brain->sendMessage($send_args);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {'error' => 1};
|
||||||
}
|
}
|
||||||
|
|
||||||
sub typing {
|
sub typing {
|
||||||
my $self = shift;
|
my $self = shift;
|
||||||
return $self->_brain->sendChatAction({chat_id => $self->chat->id});
|
|
||||||
|
my $chatid = $self->chat->id;
|
||||||
|
|
||||||
|
if (Teapot::Bot::Object::ChatPermissions->canTalk ($self, $chatid)) {
|
||||||
|
return $self->_brain->sendChatAction({chat_id => $chatid});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {'error' => 1};
|
||||||
}
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|||||||
49
lib/Teapot/Bot/Object/MessageAutoDeleteTimerChanged.pm
Normal file
49
lib/Teapot/Bot/Object/MessageAutoDeleteTimerChanged.pm
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package Teapot::Bot::Object::MessageAutoDeleteTimerChanged;
|
||||||
|
# ABSTRACT: The base class for Telegram 'MessageAutoDeleteTimerChanged' type objects
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::MessageAutoDeleteTimerChanged::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'message_auto_delete_time';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'scalar' => [qw/message_auto_delete_time/],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::MessageAutoDeleteTimerChanged - The base class for Telegram 'MessageAutoDeleteTimerChanged' type objects
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram 'MessageAutoDeleteTimerChanged' type objects.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#messageautodeletetimerchanged> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::MessageAutoDeleteTimerChanged> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
@@ -7,12 +7,13 @@ use Carp qw/croak/;
|
|||||||
$Teapot::Bot::Object::PhotoSize::VERSION = '0.022';
|
$Teapot::Bot::Object::PhotoSize::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'width';
|
has 'width';
|
||||||
has 'height';
|
has 'height';
|
||||||
has 'file_size';
|
has 'file_size';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { scalar => [qw/file_id width height file_size/] };
|
return { scalar => [qw/file_id file_unique_id width height file_size/] };
|
||||||
}
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|||||||
@@ -9,17 +9,28 @@ $Teapot::Bot::Object::Poll::VERSION = '0.022';
|
|||||||
has 'id';
|
has 'id';
|
||||||
has 'question';
|
has 'question';
|
||||||
has 'options'; # Array of PollOption
|
has 'options'; # Array of PollOption
|
||||||
|
has 'total_voter_count';
|
||||||
has 'is_closed';
|
has 'is_closed';
|
||||||
|
has 'is_anonymous';
|
||||||
|
has 'type';
|
||||||
|
has 'allows_multiple_answers';
|
||||||
|
has 'correct_option_id';
|
||||||
|
has 'explanation';
|
||||||
|
has 'explanation_entities';
|
||||||
|
has 'open_period';
|
||||||
|
has 'close_date';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
scalar => [qw/id question is_closed/],
|
scalar => [qw/id question total_voter_count is_closed is_anonymous type
|
||||||
|
allows_multiple_answers correct_option_id explanation
|
||||||
|
explanation_entities open_period close_date/],
|
||||||
'Teapot::Bot::Object::PollOption' => [qw/options/],
|
'Teapot::Bot::Object::PollOption' => [qw/options/],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
sub arrays {
|
sub arrays {
|
||||||
return qw/options/;
|
return qw/options explanation_entities/;
|
||||||
}
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|||||||
56
lib/Teapot/Bot/Object/PollAnswer.pm
Normal file
56
lib/Teapot/Bot/Object/PollAnswer.pm
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package Teapot::Bot::Object::PollAnswer;
|
||||||
|
# ABSTRACT: The base class for Telegram 'PollOption' type objects
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::PollAnswer::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'poll_id';
|
||||||
|
has 'user';
|
||||||
|
has 'option_ids';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'scalar' => [qw/poll_id option_ids/],
|
||||||
|
'Teapot::Bot::Object::User' => [qw/user/],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
sub arrays {
|
||||||
|
return qw/option_ids/;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::PollAnswer - The base class for Telegram 'PollAnswer' type objects
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram 'PollAnswer' type objects.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#pollanswer> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::PollAnswer> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
52
lib/Teapot/Bot/Object/ProximityAlertTriggered.pm
Normal file
52
lib/Teapot/Bot/Object/ProximityAlertTriggered.pm
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package Teapot::Bot::Object::ProximityAlertTriggered;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'ProximityAlertTriggered' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::ProximityAlertTriggered::VERSION = '0.022';
|
||||||
|
|
||||||
|
has 'traveler'; # User
|
||||||
|
has 'watcher'; # User
|
||||||
|
has 'distance';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return {
|
||||||
|
'Teapot::Bot::Object::User' => [qw/traveler watcher/],
|
||||||
|
'scalar' => [qw/distance/],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::ProximityAlertTriggered - The base class for Telegram message 'ProximityAlertTriggered' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'ProximityAlertTriggered' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#proximityalerttriggered> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::ProximityAlertTriggered> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2020 Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
@@ -11,10 +11,12 @@ has 'title';
|
|||||||
has 'address';
|
has 'address';
|
||||||
has 'foursquare_id';
|
has 'foursquare_id';
|
||||||
has 'foursquare_type';
|
has 'foursquare_type';
|
||||||
|
has 'google_place_id';
|
||||||
|
has 'google_place_type';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
'scalar' => [qw/title address foursquare_id foursquare_type/],
|
'scalar' => [qw/title address foursquare_id foursquare_type google_place_id google_place_type/],
|
||||||
'Teapot::Bot::Object::Location' => [qw/location/]
|
'Teapot::Bot::Object::Location' => [qw/location/]
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,16 +7,19 @@ use Teapot::Bot::Object::PhotoSize;
|
|||||||
$Teapot::Bot::Object::Video::VERSION = '0.022';
|
$Teapot::Bot::Object::Video::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'width';
|
has 'width';
|
||||||
has 'height';
|
has 'height';
|
||||||
has 'duration';
|
has 'duration';
|
||||||
has 'thumb'; #PhotoSize
|
has 'thumb'; # Optional. Video thumbnail
|
||||||
has 'mime_type';
|
has 'file_name'; # Optional. Original filename as defined by sender
|
||||||
has 'file_size';
|
has 'mime_type'; # Optional. Mime type of a file as defined by sender
|
||||||
|
has 'file_size'; # Optional. File size
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
scalar => [qw/file_id width height duration mime_type file_size/],
|
scalar => [qw/file_id file_unique_id width height duration file_name mime_type
|
||||||
|
file_size/],
|
||||||
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/]
|
'Teapot::Bot::Object::PhotoSize' => [qw/thumb/]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use Teapot::Bot::Object::PhotoSize;
|
|||||||
$Teapot::Bot::Object::VideoNote::VERSION = '0.022';
|
$Teapot::Bot::Object::VideoNote::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'length';
|
has 'length';
|
||||||
has 'duration';
|
has 'duration';
|
||||||
has 'mime_type';
|
has 'mime_type';
|
||||||
@@ -16,7 +17,7 @@ has 'file_size';
|
|||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return {
|
return {
|
||||||
scalar => [qw/file_id length duration mime_type file_size/],
|
scalar => [qw/file_id file_unique_id length duration mime_type file_size/],
|
||||||
'Teapot::Bot::Object::PhotoSize' => [qw/thumb /],
|
'Teapot::Bot::Object::PhotoSize' => [qw/thumb /],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,13 @@ use Mojo::Base 'Teapot::Bot::Object::Base';
|
|||||||
$Teapot::Bot::Object::Voice::VERSION = '0.022';
|
$Teapot::Bot::Object::Voice::VERSION = '0.022';
|
||||||
|
|
||||||
has 'file_id';
|
has 'file_id';
|
||||||
|
has 'file_unique_id';
|
||||||
has 'duration';
|
has 'duration';
|
||||||
has 'mime_type';
|
has 'mime_type';
|
||||||
has 'file_size';
|
has 'file_size';
|
||||||
|
|
||||||
sub fields {
|
sub fields {
|
||||||
return { scalar => [qw/file_id duration mime_type file_size/] };
|
return { scalar => [qw/file_id file_unique_id duration mime_type file_size/] };
|
||||||
}
|
}
|
||||||
|
|
||||||
1;
|
1;
|
||||||
|
|||||||
48
lib/Teapot/Bot/Object/VoiceChatEnded.pm
Normal file
48
lib/Teapot/Bot/Object/VoiceChatEnded.pm
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package Teapot::Bot::Object::VoiceChatEnded;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'VoiceChatEnded' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::VoiceChatEnded::VERSION = '0.022';
|
||||||
|
|
||||||
|
# This object represents a service message about a voice chat started in the chat. Currently holds no information.
|
||||||
|
has 'duration';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return { scalar => [qw/duration/] };
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::VoiceChatEnded - The base class for Telegram message 'VoiceChatEnded' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'VoiceChatEnded' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#voicechatended> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::VoiceChatEnded> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
53
lib/Teapot/Bot/Object/VoiceChatParticipantsInvited.pm
Normal file
53
lib/Teapot/Bot/Object/VoiceChatParticipantsInvited.pm
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package Teapot::Bot::Object::VoiceChatParticipantsInvited;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'VoiceChatParticipantsInvited' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
use Teapot::Bot::Object::User;
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::VoiceChatParticipantsInvited::VERSION = '0.022';
|
||||||
|
|
||||||
|
# This object represents a service message about a voice chat started in the chat. Currently holds no information.
|
||||||
|
has 'users';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return { 'Teapot::Bot::Object::User' => [qw/users/] };
|
||||||
|
}
|
||||||
|
|
||||||
|
sub arrays {
|
||||||
|
return qw/users/;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::VoiceChatParticipantsInvited - The base class for Telegram message 'VoiceChatParticipantsInvited' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'VoiceChatParticipantsInvited' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#voicechatparticipantsinvited> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::VoiceChatParticipantsInvited> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
48
lib/Teapot/Bot/Object/VoiceChatScheduled.pm
Normal file
48
lib/Teapot/Bot/Object/VoiceChatScheduled.pm
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package Teapot::Bot::Object::VoiceChatScheduled;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'VoiceChatEnded' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::VoiceChatScheduled::VERSION = '0.022';
|
||||||
|
|
||||||
|
# This object represents a service message about a voice chat started in the chat. Currently holds no information.
|
||||||
|
has 'start_date';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return { scalar => [qw/start_date/] };
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::VoiceChatScheduled - The base class for Telegram message 'VoiceChatScheduled' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'VoiceChatScheduled' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#voicechatscheduled> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::VoiceChatScheduled> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
48
lib/Teapot/Bot/Object/VoiceChatStarted.pm
Normal file
48
lib/Teapot/Bot/Object/VoiceChatStarted.pm
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package Teapot::Bot::Object::VoiceChatStarted;
|
||||||
|
# ABSTRACT: The base class for Telegram message 'VoiceChatStarted' type.
|
||||||
|
|
||||||
|
use Mojo::Base 'Teapot::Bot::Object::Base';
|
||||||
|
|
||||||
|
$Teapot::Bot::Object::VoiceChatStarted::VERSION = '0.022';
|
||||||
|
|
||||||
|
# This object represents a service message about a voice chat started in the chat. Currently holds no information.
|
||||||
|
has 'stub';
|
||||||
|
|
||||||
|
sub fields {
|
||||||
|
return { scalar => [qw/stub/] };
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
__END__
|
||||||
|
|
||||||
|
=pod
|
||||||
|
|
||||||
|
=encoding UTF-8
|
||||||
|
|
||||||
|
=head1 NAME
|
||||||
|
|
||||||
|
Teapot::Bot::Object::VoiceChatStarted - The base class for Telegram message 'VoiceChatStarted' type
|
||||||
|
|
||||||
|
=head1 VERSION
|
||||||
|
|
||||||
|
version 0.022
|
||||||
|
|
||||||
|
=head1 DESCRIPTION
|
||||||
|
The base class for Telegram message 'VoiceChatStarted' type.
|
||||||
|
|
||||||
|
See L<https://core.telegram.org/bots/api#voicechatstarted> for details of the
|
||||||
|
attributes available for L<Teapot::Bot::Object::VoiceChatStarted> objects.
|
||||||
|
|
||||||
|
=head1 AUTHOR
|
||||||
|
|
||||||
|
Sergei Fedosov <eleksir@gmail.com>
|
||||||
|
|
||||||
|
=head1 LICENSE AND COPYRIGHT
|
||||||
|
|
||||||
|
This software is copyright (c) 2021 by Sergei Fedosov <eleksir@gmail.com>.
|
||||||
|
|
||||||
|
This is free software; you can redistribute it and/or modify it under
|
||||||
|
the same terms as the Perl 5 programming language system itself.
|
||||||
|
|
||||||
|
=cut
|
||||||
439
lib/TelegramBot.pm
Normal file
439
lib/TelegramBot.pm
Normal file
@@ -0,0 +1,439 @@
|
|||||||
|
package TelegramBot;
|
||||||
|
# main bot gears are here
|
||||||
|
|
||||||
|
use 5.018;
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use utf8;
|
||||||
|
use open qw (:std :utf8);
|
||||||
|
use English qw ( -no_match_vars );
|
||||||
|
use Carp qw (cluck carp);
|
||||||
|
use File::Path qw (make_path);
|
||||||
|
use Hailo;
|
||||||
|
use Log::Any qw ($log);
|
||||||
|
use Math::Random::Secure qw (irand);
|
||||||
|
use Mojo::Base 'Teapot::Bot::Brain';
|
||||||
|
use BotLib::Admin qw (FortuneToggleList);
|
||||||
|
use BotLib qw (RandomCommonPhrase Command Highlight BotSleep IsCensored);
|
||||||
|
use BotLib::Conf qw (LoadConf);
|
||||||
|
use BotLib::Fortune qw (Fortune);
|
||||||
|
use BotLib::Image qw (Oboobs Obutts);
|
||||||
|
use BotLib::Karma qw (KarmaSet);
|
||||||
|
use BotLib::Util qw (trim fmatch);
|
||||||
|
|
||||||
|
use version; our $VERSION = qw (1.0);
|
||||||
|
use Exporter qw (import);
|
||||||
|
our @EXPORT_OK = qw (RunTelegramBot);
|
||||||
|
|
||||||
|
my $c = LoadConf ();
|
||||||
|
my $hailo;
|
||||||
|
my $myid;
|
||||||
|
my $myusername;
|
||||||
|
my $myfirst_name;
|
||||||
|
my $mylast_name;
|
||||||
|
my $myfullname;
|
||||||
|
|
||||||
|
has token => $c->{telegrambot}->{token};
|
||||||
|
|
||||||
|
sub __cron {
|
||||||
|
my $self = shift;
|
||||||
|
|
||||||
|
# fortune mod
|
||||||
|
my @intro = (
|
||||||
|
'Сегодняшний день пройдёт под эгидой фразы:',
|
||||||
|
'Крылатая фраза на сегодня:',
|
||||||
|
'Сегодняшняя фраза дня:',
|
||||||
|
);
|
||||||
|
|
||||||
|
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime (time);
|
||||||
|
|
||||||
|
if ($hour == 8 && ($min >= 0 && $min <= 14)) {
|
||||||
|
foreach my $enabledfortunechat (FortuneToggleList ()) {
|
||||||
|
my $send_args;
|
||||||
|
$send_args->{text} = sprintf "%s\n```\n%s\n```\n", $intro[irand ($#intro + 1)], trim (Fortune ());
|
||||||
|
$send_args->{chat_id} = $enabledfortunechat;
|
||||||
|
$send_args->{parse_mode} = 'Markdown';
|
||||||
|
$self->sendMessage ($send_args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub __on_msg {
|
||||||
|
my ($self, $msg) = @_;
|
||||||
|
# chat info
|
||||||
|
my $chatid;
|
||||||
|
my $chatname = 'Noname chat';
|
||||||
|
# user sending message info
|
||||||
|
my ($userid, $username, $fullname, $highlight, $vis_a_vi) = BotLib::Highlight ($msg);
|
||||||
|
my $csign = $c->{telegrambot}->{csign};
|
||||||
|
|
||||||
|
unless ($myid) {
|
||||||
|
my $myObj = $self->getMe ();
|
||||||
|
|
||||||
|
unless ($myObj) {
|
||||||
|
$log->error ('[ERROR] Unable to get chatid, API Error?');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$myid = $myObj->id;
|
||||||
|
$myusername = $myObj->username;
|
||||||
|
$myfirst_name = $myObj->first_name;
|
||||||
|
$mylast_name = $myObj->last_name;
|
||||||
|
|
||||||
|
if (defined ($myfirst_name) && ($myfirst_name ne '') && defined ($mylast_name) && ($mylast_name ne '')) {
|
||||||
|
$myfullname = $myfirst_name . ' ' . $mylast_name;
|
||||||
|
} elsif (defined ($myfirst_name) && ($myfirst_name ne '')) {
|
||||||
|
$myfullname = $myfirst_name;
|
||||||
|
} elsif (defined ($mylast_name) && ($mylast_name ne '')) {
|
||||||
|
$myfullname = $mylast_name;
|
||||||
|
} else {
|
||||||
|
$myfullname = $myusername;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($msg->chat->can ('id') && defined ($msg->chat->id)) {
|
||||||
|
$chatid = $msg->chat->id;
|
||||||
|
|
||||||
|
if ($msg->chat->can ('username') && defined ($msg->chat->username)) {
|
||||||
|
$chatname = $msg->chat->username ;
|
||||||
|
} else {
|
||||||
|
if ($msg->chat->can ('title') && defined ($msg->chat->title)) {
|
||||||
|
$chatname = $msg->chat->title;
|
||||||
|
} else {
|
||||||
|
$chatname = 'Noname chat';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$log->warn ('[INFO] Unable to get chatid');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $phrase = '';
|
||||||
|
|
||||||
|
# Newcommer event, greet our new member and suggest to introduce themself.
|
||||||
|
if ($msg->can ('new_chat_members') && defined ($msg->new_chat_members)) {
|
||||||
|
my @members;
|
||||||
|
my @introduce = (
|
||||||
|
'Дратути',
|
||||||
|
'Дарована',
|
||||||
|
'Доброе утро, день или вечер',
|
||||||
|
'Добро пожаловать в наше скромное коммунити',
|
||||||
|
'Наше вам с кисточкой тут, на канальчике',
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach my $member (@{$msg->new_chat_members}) {
|
||||||
|
my $member_str = '';
|
||||||
|
|
||||||
|
# avoid naming people by spacing symbols, or empty names
|
||||||
|
if ($member->can ('first_name') && defined ($member->first_name) && $member->first_name !~ /^\s+$/ui) {
|
||||||
|
$member_str .= $member->first_name;
|
||||||
|
|
||||||
|
if ($member->can ('last_name') && defined ($member->last_name) && $member->last_name !~ /^\s+$/ui) {
|
||||||
|
$member_str .= ' ' . $member->last_name;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if ($member->can ('last_name') && defined ($member->last_name) && $member->last_name !~ /^\s+$/ui) {
|
||||||
|
$member_str .= ' ' . $member->last_name;
|
||||||
|
# username must be uniq and should contain only english letters and numbers, so...
|
||||||
|
} elsif ($member->can ('username') && defined ($member->username)) {
|
||||||
|
$member_str .= '@' . $member->username;
|
||||||
|
# fallback to id if uose trying to be smartass and use only spacing chars in it's firstname and/or lastname
|
||||||
|
} else {
|
||||||
|
$member_str .= $member->id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
push @members, sprintf '[%s](tg://user?id=%s)', $member_str, $member->id;
|
||||||
|
};
|
||||||
|
|
||||||
|
if ($#members > 1) {
|
||||||
|
my $lastone = pop @members;
|
||||||
|
$phrase = sprintf '%s, %s и %s. Представьтес, пожалуйста, и расскажите, что вас сюда привело.', $introduce[irand ($#introduce + 1)], join (', ', @members), $lastone;
|
||||||
|
} else {
|
||||||
|
$phrase = sprintf '%s, %s. Представьтес, пожалуйста, и расскажите, что вас сюда привело.', $introduce[irand ($#introduce + 1)], $members[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
BotSleep $msg;
|
||||||
|
$msg->replyMd ($phrase);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# lazy init chat-bot brains
|
||||||
|
unless (defined $hailo->{$chatid}) {
|
||||||
|
my $brainname = sprintf '%s/%s.brain.sqlite', $c->{telegrambot}->{braindir}, $chatid;
|
||||||
|
|
||||||
|
$hailo->{$chatid} = Hailo->new (
|
||||||
|
# we'll got file like this: data/telegrambot-brains/-1001332512695.brain.sqlite
|
||||||
|
brain => $brainname,
|
||||||
|
order => 3
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($chatid < 0) {
|
||||||
|
$log->info ("[INFO] Initialized brain for public chat $chatname ($chatid): $brainname");
|
||||||
|
} else {
|
||||||
|
$log->info ("[INFO] Initialized brain for private chat $chatname ($chatid): $brainname");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# is this a 1-on-1 ?
|
||||||
|
if ($msg->chat->type eq 'private') {
|
||||||
|
unless (defined $msg->text) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
my $text = $msg->text;
|
||||||
|
$log->debug (sprintf ('[DEBUG] Private chat %s say to bot: %s', $vis_a_vi, $text));
|
||||||
|
my $reply = 'Давайте ещё пообщаемся, а то я ещё не научилась от вас плохому.';
|
||||||
|
|
||||||
|
if (substr ($text, 0, 1) eq $csign) {
|
||||||
|
$reply = Command ($self, $msg, $text, $userid);
|
||||||
|
} else {
|
||||||
|
my $just_message_in_chat = 0;
|
||||||
|
|
||||||
|
# is it karma adjustment?
|
||||||
|
if (substr ($text, -2) eq '++' || substr ($text, -2) eq '--') {
|
||||||
|
my @arr = split /\n/, $text;
|
||||||
|
|
||||||
|
if ($#arr < 1) {
|
||||||
|
$reply = KarmaSet ($chatid, trim (substr ($text, 0, -2)), substr ($text, -2));
|
||||||
|
} else {
|
||||||
|
$just_message_in_chat = 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$just_message_in_chat = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($just_message_in_chat) {
|
||||||
|
if ($text =~ /^ *кто +все +эти +люди *\?$/ui) {
|
||||||
|
$reply = 'Какие "люди"? Мы здесь вдвоём, только ты и я.';
|
||||||
|
} elsif ($text =~ /^ *кто +я *\?$/ui) {
|
||||||
|
$reply = 'Где?';
|
||||||
|
} elsif ($text =~ /^ *кто +(здесь|тут) *\?$/ui) {
|
||||||
|
$reply = 'Ты да я, да мы с тобой.';
|
||||||
|
} elsif ($text =~ /покажи +(сиськи|сиси|титьки) *$/ui) {
|
||||||
|
$reply = Oboobs ();
|
||||||
|
} elsif ($text =~ /show +(titts|tities|boobs) *$/i) {
|
||||||
|
$reply = Oboobs ();
|
||||||
|
} elsif ($text =~ /покажи +(попку|попу) *$/ui) {
|
||||||
|
$reply = Obutts ();
|
||||||
|
} elsif ($text =~ /show +(ass|butt|butty) *$/i) {
|
||||||
|
$reply = Obutts ();
|
||||||
|
} else {
|
||||||
|
my $str = $hailo->{$msg->chat->id}->learn_reply ($text);
|
||||||
|
|
||||||
|
if (defined ($str) && $str ne '') {
|
||||||
|
$reply = $str;
|
||||||
|
$phrase = trim $text;
|
||||||
|
|
||||||
|
while ($phrase =~ /[\.|\,|\?|\!]$/) {
|
||||||
|
chop $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
$phrase = lc $phrase;
|
||||||
|
|
||||||
|
if (fmatch (lc ($reply), $phrase)) {
|
||||||
|
$reply = RandomCommonPhrase ();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined $reply) {
|
||||||
|
$msg->typing ();
|
||||||
|
sleep 1;
|
||||||
|
$log->debug (sprintf ('[DEBUG] Private chat bot reply to %s: %s', $vis_a_vi, $reply));
|
||||||
|
$msg->reply ($reply);
|
||||||
|
}
|
||||||
|
# group chat
|
||||||
|
} elsif (($msg->chat->type eq 'supergroup') or ($msg->chat->type eq 'group')) {
|
||||||
|
my $reply;
|
||||||
|
|
||||||
|
if (IsCensored $msg) {
|
||||||
|
$log->info (sprintf '[INFO] In public chat %s (%s) message from %s was censored', $chatname, $chatid, $vis_a_vi);
|
||||||
|
$self->deleteMessage ({chat_id => $chatid, message_id => $msg->{message_id}});
|
||||||
|
}
|
||||||
|
|
||||||
|
# detect and log messages without text, noop here
|
||||||
|
unless (defined $msg->text) {
|
||||||
|
$log->debug (sprintf ('[DEBUG] No text in message from %s', $vis_a_vi));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# we have text here! so potentially we can chit-chat
|
||||||
|
my $text = $msg->text;
|
||||||
|
$log->debug (sprintf ('[DEBUG] In public chat %s (%s) %s say: %s', $chatname, $chatid, $vis_a_vi, $text));
|
||||||
|
|
||||||
|
# are they quote something, maybe, us?
|
||||||
|
if (defined ($msg->reply_to_message) &&
|
||||||
|
defined ($msg->reply_to_message->from) &&
|
||||||
|
defined ($msg->reply_to_message->from->username) &&
|
||||||
|
($msg->reply_to_message->from->username eq $myusername)) {
|
||||||
|
$log->debug (sprintf ('[DEBUG] In public chat %s (%s) %s quote us!', $chatname, $chatid, $vis_a_vi));
|
||||||
|
|
||||||
|
# do not answer back if someone quote our new member greet
|
||||||
|
if (substr ($msg->reply_to_message->text, -61) eq 'Представьтес, пожалуйста, и расскажите, что вас сюда привело.') {
|
||||||
|
my @hello = (
|
||||||
|
'Дратути, ',
|
||||||
|
'Дарована, ',
|
||||||
|
'Доброе утро, день или вечер, ',
|
||||||
|
'Добро пожаловать в наше скромное коммунити, ',
|
||||||
|
'Наше вам с кисточкой тут, на канальчике, ',
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach my $hi (@hello) {
|
||||||
|
if (substr ($msg->reply_to_message->text, 0, length $hi) eq $hi) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# remove our name from users reply, just in case
|
||||||
|
my $pat1 = quotemeta ('@' . $myusername);
|
||||||
|
my $pat2 = quotemeta $myfullname;
|
||||||
|
$phrase = $text;
|
||||||
|
$phrase =~ s/$pat1//g;
|
||||||
|
$phrase =~ s/$pat2//g;
|
||||||
|
|
||||||
|
# figure out reply :)
|
||||||
|
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase) if (length ($phrase) > 3);
|
||||||
|
# simple commands
|
||||||
|
} elsif (substr ($text, 0, 1) eq $csign) {
|
||||||
|
$reply = Command ($self, $msg, $text, $chatid);
|
||||||
|
} elsif (
|
||||||
|
($text eq $myusername) or
|
||||||
|
($text eq '@' . $myusername) or
|
||||||
|
($text eq '@' . $myusername . ' ') or
|
||||||
|
($text eq $myfullname) or
|
||||||
|
($text eq $myfullname . ' ')
|
||||||
|
) {
|
||||||
|
$reply = 'Чего?';
|
||||||
|
} else {
|
||||||
|
my $qname = quotemeta ('@' . $myusername);
|
||||||
|
my $qtname = quotemeta $myfullname;
|
||||||
|
|
||||||
|
# phrase directed to bot
|
||||||
|
if ((lc ($text) =~ /^${qname}[\,|\:]? (.+)/) or (lc ($text) =~ /^${qtname}[\,|\:]? (.+)/)){
|
||||||
|
$phrase = $1;
|
||||||
|
|
||||||
|
if ($phrase =~ /^ *кто +все +эти +люди *\?$/ui) {
|
||||||
|
$reply = 'Кто здесь?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +я *?$/ui){
|
||||||
|
$reply = 'Где?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +(здесь|тут) *\?$/ui) {
|
||||||
|
$reply = 'Здесь все: Никита, Стас, Гена, Турбо и Дюша Метёлкин.';
|
||||||
|
} else {
|
||||||
|
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase);
|
||||||
|
}
|
||||||
|
# bot mention by name
|
||||||
|
} elsif ((lc ($text) =~ /.+ ${qname}[\,|\!|\?|\.| ]/) or (lc ($text) =~ / $qname$/)) {
|
||||||
|
$phrase = $text;
|
||||||
|
|
||||||
|
if ($phrase =~ /^ *кто +все +эти +люди *\?$/ui) {
|
||||||
|
$reply = 'Кто здесь?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +я *?$/ui){
|
||||||
|
$reply = 'Где?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +(здесь|тут) *\?$/ui) {
|
||||||
|
$reply = 'Здесь все: Никита, Стас, Гена, Турбо и Дюша Метёлкин.';
|
||||||
|
} else {
|
||||||
|
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase);
|
||||||
|
}
|
||||||
|
# bot mention by telegram name
|
||||||
|
} elsif ((lc ($text) =~ /.+ ${qtname}[\,|\!|\?|\.| ]/) or (lc ($text) =~ / $qtname$/)) {
|
||||||
|
$phrase = $text;
|
||||||
|
|
||||||
|
if ($phrase =~ /^ *кто +все +эти +люди *\?$/ui) {
|
||||||
|
$reply = 'Кто здесь?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +я *?$/ui){
|
||||||
|
$reply = 'Где?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +(здесь|тут) *\?$/ui) {
|
||||||
|
$reply = 'Здесь все: Никита, Стас, Гена, Турбо и Дюша Метёлкин.';
|
||||||
|
} else {
|
||||||
|
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase);
|
||||||
|
}
|
||||||
|
# karma adjustment
|
||||||
|
} elsif (substr ($text, -2) eq '++' || substr ($text, -2) eq '--') {
|
||||||
|
my @arr = split /\n/, $text;
|
||||||
|
|
||||||
|
if ($#arr < 1) {
|
||||||
|
$reply = KarmaSet ($chatid, trim (substr ($text, 0, -2)), substr ($text, -2));
|
||||||
|
} else {
|
||||||
|
# just message in chat
|
||||||
|
$hailo->{$msg->chat->id}->learn ($text);
|
||||||
|
}
|
||||||
|
# just message in chat
|
||||||
|
} else {
|
||||||
|
if ($text =~ /^ *кто +все +эти +люди *\?$/ui) {
|
||||||
|
$reply = 'Кто здесь?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +я *?$/ui){
|
||||||
|
$reply = 'Где?';
|
||||||
|
} elsif ($phrase =~ /^ *кто +(здесь|тут) *\?$/ui) {
|
||||||
|
$reply = 'Здесь все: Никита, Стас, Гена, Турбо и Дюша Метёлкин.';
|
||||||
|
} else {
|
||||||
|
$hailo->{$msg->chat->id}->learn ($text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (defined ($reply) && $reply ne '') {
|
||||||
|
# work a bit more on input phrase
|
||||||
|
$phrase = trim $phrase;
|
||||||
|
|
||||||
|
while ($phrase =~ /[\.|\,|\?|\!]$/) {
|
||||||
|
chop $phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
$phrase = lc $phrase;
|
||||||
|
|
||||||
|
if (fmatch (lc ($reply), $phrase)) {
|
||||||
|
$reply = RandomCommonPhrase ();
|
||||||
|
}
|
||||||
|
|
||||||
|
$msg->typing ();
|
||||||
|
sleep (irand 2);
|
||||||
|
$log->debug (sprintf ('[DEBUG] In public chat %s (%s) bot reply to %s: %s', $chatname, $chatid, $vis_a_vi, $reply));
|
||||||
|
$msg->reply ($reply);
|
||||||
|
} else {
|
||||||
|
$log->debug (sprintf ('[DEBUG] In public chat %s (%s) bot is not required to reply to %s', $chatname, $chatid, $vis_a_vi));
|
||||||
|
}
|
||||||
|
|
||||||
|
# should be channel, so we can't talk
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# setup our bot
|
||||||
|
sub init {
|
||||||
|
my $self = shift;
|
||||||
|
my $braindir = $c->{telegrambot}->{braindir};
|
||||||
|
|
||||||
|
unless (-d $braindir) {
|
||||||
|
make_path ($braindir, 0, 0755) or do { ## no critic (ValuesAndExpressions::ProhibitLeadingZeros)
|
||||||
|
$log->fatal ("[FATAL] Unable to create $braindir: $OS_ERROR");
|
||||||
|
exit 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$self->add_listener (\&__on_msg);
|
||||||
|
$self->add_repeating_task (900, \&__cron);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub RunTelegramBot {
|
||||||
|
while (sleep 3) {
|
||||||
|
eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
|
||||||
|
TelegramBot->new->think;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
1;
|
||||||
|
|
||||||
|
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
||||||
248
lib/botlib.pm
248
lib/botlib.pm
@@ -1,248 +0,0 @@
|
|||||||
package botlib;
|
|
||||||
# store here utility functions that are not protocol-specified
|
|
||||||
|
|
||||||
use 5.018;
|
|
||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use utf8;
|
|
||||||
use open qw(:std :utf8);
|
|
||||||
use English qw( -no_match_vars );
|
|
||||||
|
|
||||||
use HTTP::Tiny;
|
|
||||||
use URI::URL;
|
|
||||||
use JSON::XS qw(decode_json encode_json);
|
|
||||||
use Digest::MD5 qw(md5_base64);
|
|
||||||
use DB_File;
|
|
||||||
|
|
||||||
use conf qw(loadConf);
|
|
||||||
|
|
||||||
use vars qw/$VERSION/;
|
|
||||||
|
|
||||||
use Exporter qw(import);
|
|
||||||
our @EXPORT_OK = qw(weather logger trim randomCommonPhrase);
|
|
||||||
|
|
||||||
$VERSION = '1.0';
|
|
||||||
|
|
||||||
my $c = loadConf();
|
|
||||||
|
|
||||||
sub __urlencode {
|
|
||||||
my $str = shift;
|
|
||||||
my $urlobj = url $str;
|
|
||||||
$str = $urlobj->as_string;
|
|
||||||
$urlobj = undef; undef $urlobj;
|
|
||||||
return $str;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub logger {
|
|
||||||
my $msg = shift;
|
|
||||||
|
|
||||||
if ($c->{debug_log}) {
|
|
||||||
my @date = localtime();
|
|
||||||
my @month = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
|
|
||||||
my $t = sprintf ('%02s %02d %02d:%02d:%02d ', $month[$date[4]], $date[3], $date[2], $date[1], $date[0]);
|
|
||||||
|
|
||||||
my $mode = '>';
|
|
||||||
$mode = '>>' if (-f $c->{debug_log});
|
|
||||||
|
|
||||||
if (open my $LOG, $mode, $c->{debug_log}) {
|
|
||||||
print $LOG $t . $msg . "\n"; ## no critic (InputOutput::RequireCheckedSyscalls)
|
|
||||||
close $LOG; ## no critic (InputOutput::RequireCheckedSyscalls)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub trim {
|
|
||||||
my $str = shift;
|
|
||||||
|
|
||||||
while (substr ($str, 0, 1) =~ /^\s$/xms) {
|
|
||||||
$str = substr ($str, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (substr ($str, -1, 1) =~ /^\s$/xms) {
|
|
||||||
chop ($str);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $str;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
sub weather {
|
|
||||||
my $city = shift;
|
|
||||||
$city = trim ($city);
|
|
||||||
|
|
||||||
return 'Мне нужно ИМЯ города.' if ($city eq '');
|
|
||||||
return 'Длинновато для названия города.' if (length($city) > 80);
|
|
||||||
|
|
||||||
$city = ucfirst ($city);
|
|
||||||
my $w = __weather ($city);
|
|
||||||
my $reply;
|
|
||||||
|
|
||||||
if ($w) {
|
|
||||||
if ($w->{temperature_min} == $w->{temperature_max}) {
|
|
||||||
$reply = sprintf ("Погода в городе %s, %s:\n%s, ветер %s %s м/c, температура %s°C, ощущается как %s°C, относительная влажность %s%%, давление %s мм.рт.с",
|
|
||||||
$w->{name},
|
|
||||||
$w->{country},
|
|
||||||
ucfirst ($w->{description}),
|
|
||||||
$w->{wind_direction},
|
|
||||||
$w->{wind_speed},
|
|
||||||
$w->{temperature_min},
|
|
||||||
$w->{temperature_feelslike},
|
|
||||||
$w->{humidity},
|
|
||||||
$w->{pressure}
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
$reply = sprintf ("Погода в городе %s, %s:\n%s, ветер %s %s м/c, температура %s-%s°C, ощущается как %s°C, относительная влажность %s%%, давление %s мм.рт.ст",
|
|
||||||
$w->{name},
|
|
||||||
$w->{country},
|
|
||||||
ucfirst ($w->{description}),
|
|
||||||
$w->{wind_direction},
|
|
||||||
$w->{wind_speed},
|
|
||||||
$w->{temperature_min},
|
|
||||||
$w->{temperature_max},
|
|
||||||
$w->{temperature_feelslike},
|
|
||||||
$w->{humidity},
|
|
||||||
$w->{pressure}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$reply = "Я не знаю, какая погода в $city";
|
|
||||||
}
|
|
||||||
|
|
||||||
return $reply;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub __weather {
|
|
||||||
my $city = shift;
|
|
||||||
$city = __urlencode ($city);
|
|
||||||
my $id = md5_base64 ($city);
|
|
||||||
my $appid = $c->{openweathermap}->{appid};
|
|
||||||
my $now = time ();
|
|
||||||
my $fc;
|
|
||||||
my $w;
|
|
||||||
|
|
||||||
# attach to cache data
|
|
||||||
tie my %cachetime, 'DB_File', $c->{openweathermap}->{cachetime} or do {
|
|
||||||
logger "Something nasty happen when cachetime ties to its data: $OS_ERROR";
|
|
||||||
return undef;
|
|
||||||
};
|
|
||||||
|
|
||||||
tie my %cachedata, 'DB_File', $c->{openweathermap}->{cachedata} or do {
|
|
||||||
logger "Something nasty happen when cachedata ties to its data: $OS_ERROR";
|
|
||||||
return undef;
|
|
||||||
};
|
|
||||||
|
|
||||||
# lookup cache
|
|
||||||
if (defined ($cachetime{$id}) && ($now - $cachetime{$id}) < 10800) {
|
|
||||||
$fc = decode_json ($cachedata{$id});
|
|
||||||
} else {
|
|
||||||
my $r;
|
|
||||||
|
|
||||||
# try 3 times and giveup
|
|
||||||
for (1..3) {
|
|
||||||
next if ($r->{success});
|
|
||||||
my $http = HTTP::Tiny->new (timeout => 3);
|
|
||||||
$r = $http->get (sprintf ('http://api.openweathermap.org/data/2.5/weather?q=%s&lang=ru&APPID=%s', $city, $appid));
|
|
||||||
sleep 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
# all 3 times can give error, so check it here
|
|
||||||
if ($r->{success}) {
|
|
||||||
$fc = eval { decode_json ($r->{content}) };
|
|
||||||
|
|
||||||
if ($EVAL_ERROR) {
|
|
||||||
logger "[WARN] openweathermap returns corrupted json: $EVAL_ERROR";
|
|
||||||
untie %cachetime;
|
|
||||||
untie %cachedata;
|
|
||||||
return undef;
|
|
||||||
};
|
|
||||||
|
|
||||||
$cachetime{$id} = $now;
|
|
||||||
$cachedata{$id} = encode_json ($fc);
|
|
||||||
} else {
|
|
||||||
untie %cachetime;
|
|
||||||
untie %cachedata;
|
|
||||||
return undef;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
untie %cachetime;
|
|
||||||
untie %cachedata;
|
|
||||||
|
|
||||||
# TODO: check all of this for existance
|
|
||||||
$w->{'name'} = $fc->{name};
|
|
||||||
$w->{'state'} = $fc->{state};
|
|
||||||
$w->{'country'} = $fc->{sys}->{country};
|
|
||||||
$w->{'longitude'} = $fc->{coord}->{lon};
|
|
||||||
$w->{'latitude'} = $fc->{coord}->{lat};
|
|
||||||
$w->{'temperature_min'} = int ($fc->{main}->{temp_min} - 273.15);
|
|
||||||
$w->{'temperature_max'} = int ($fc->{main}->{temp_max} - 273.15);
|
|
||||||
$w->{'temperature_feelslike'} = int ($fc->{main}->{feels_like} - 273.15);
|
|
||||||
$w->{'humidity'} = $fc->{main}->{humidity};
|
|
||||||
$w->{'pressure'} = int ($fc->{main}->{pressure} * 0.75006375541921);
|
|
||||||
$w->{'description'} = $fc->{weather}->[0]->{description};
|
|
||||||
$w->{'wind_speed'} = $fc->{wind}->{speed};
|
|
||||||
$w->{'wind_direction'} = 'разный';
|
|
||||||
my $dir = int ($fc->{wind}->{deg} + 0);
|
|
||||||
|
|
||||||
if ($dir == 0) {
|
|
||||||
$w->{'wind_direction'} = 'северный';
|
|
||||||
} elsif ($dir > 0 && $dir <= 30) {
|
|
||||||
$w->{'wind_direction'} = 'северо-северо-восточный';
|
|
||||||
} elsif ($dir > 30 && $dir <= 60) {
|
|
||||||
$w->{'wind_direction'} = 'северо-восточный';
|
|
||||||
} elsif ($dir > 60 && $dir < 90) {
|
|
||||||
$w->{'wind_direction'} = 'восточно-северо-восточный';
|
|
||||||
} elsif ($dir == 90) {
|
|
||||||
$w->{'wind_direction'} = 'восточный';
|
|
||||||
} elsif ($dir > 90 && $dir <= 120) {
|
|
||||||
$w->{'wind_direction'} = 'восточно-юго-восточный';
|
|
||||||
} elsif ($dir > 120 && $dir <= 150) {
|
|
||||||
$w->{'wind_direction'} = 'юговосточный';
|
|
||||||
} elsif ($dir > 150 && $dir < 180) {
|
|
||||||
$w->{'wind_direction'} = 'юго-юго-восточный';
|
|
||||||
} elsif ($dir == 180) {
|
|
||||||
$w->{'wind_direction'} = 'южный';
|
|
||||||
} elsif ($dir > 180 && $dir <= 210) {
|
|
||||||
$w->{'wind_direction'} = 'юго-юго-западный';
|
|
||||||
} elsif ($dir > 210 && $dir <= 240) {
|
|
||||||
$w->{'wind_direction'} = 'юго-западный';
|
|
||||||
} elsif ($dir > 240 && $dir < 270) {
|
|
||||||
$w->{'wind_direction'} = 'западно-юго-западный';
|
|
||||||
} elsif ($dir == 270) {
|
|
||||||
$w->{'wind_direction'} = 'западный';
|
|
||||||
} elsif ($dir > 270 && $dir <= 300) {
|
|
||||||
$w->{'wind_direction'} = 'западно-северо-западный';
|
|
||||||
} elsif ($dir > 300 && $dir <= 330) {
|
|
||||||
$w->{'wind_direction'} = 'северо-западный';
|
|
||||||
} elsif ($dir > 330 && $dir < 360) {
|
|
||||||
$w->{'wind_direction'} = 'северо-северо-западный';
|
|
||||||
} elsif ($dir == 360) {
|
|
||||||
$w->{'wind_direction'} = 'северный';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $w;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub randomCommonPhrase {
|
|
||||||
my @myphrase = (
|
|
||||||
'Так, блядь...',
|
|
||||||
'*Закатывает рукава* И ради этого ты меня позвал?',
|
|
||||||
'Ну чего ты начинаешь, нормально же общались',
|
|
||||||
'Повтори свой вопрос, не поняла',
|
|
||||||
'Выйди и зайди нормально',
|
|
||||||
'Я подумаю',
|
|
||||||
'Даже не знаю что на это ответить',
|
|
||||||
'Ты упал такие вопросы девочке задавать?',
|
|
||||||
'Можно и так, но не уверена',
|
|
||||||
'А как ты думаешь?',
|
|
||||||
'А ви, таки, почему интересуетесь?',
|
|
||||||
);
|
|
||||||
|
|
||||||
return $myphrase[rand ($#myphrase -1)];
|
|
||||||
}
|
|
||||||
|
|
||||||
1;
|
|
||||||
|
|
||||||
# vim: set ft=perl noet ai ts=4 sw=4 sts=4:
|
|
||||||
76
lib/lat.pm
76
lib/lat.pm
@@ -1,76 +0,0 @@
|
|||||||
package lat;
|
|
||||||
# famous latin phases taken from https://ru.wikipedia.org/wiki/Список_крылатых_латинских_выражений
|
|
||||||
|
|
||||||
use 5.018;
|
|
||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use utf8;
|
|
||||||
use open qw(:std :utf8);
|
|
||||||
use English qw( -no_match_vars );
|
|
||||||
|
|
||||||
use vars qw/$VERSION/;
|
|
||||||
use Exporter qw(import);
|
|
||||||
our @EXPORT_OK = qw(train latAnswer);
|
|
||||||
|
|
||||||
$VERSION = '1.0';
|
|
||||||
|
|
||||||
use Hailo;
|
|
||||||
use File::Basename qw(dirname);
|
|
||||||
use File::Path qw(mkpath);
|
|
||||||
use conf qw(loadConf);
|
|
||||||
use botlib qw(logger);
|
|
||||||
|
|
||||||
my $c = loadConf();
|
|
||||||
my $brain = $c->{lat}->{brain};
|
|
||||||
|
|
||||||
# swallow phrase and return answer
|
|
||||||
sub train () {
|
|
||||||
my $braindir = dirname ($brain);
|
|
||||||
|
|
||||||
unless (-d $braindir) {
|
|
||||||
mkpath ($braindir) or do {
|
|
||||||
logger "Unable to create $braindir: $OS_ERROR";
|
|
||||||
exit 1;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
my $lat = Hailo->new (
|
|
||||||
brain => $brain,
|
|
||||||
# in our case mean amount of words in phase is 3
|
|
||||||
order => 2
|
|
||||||
);
|
|
||||||
|
|
||||||
$lat->train('data/phrases.txt');
|
|
||||||
my ($tokens, $expressions) = ($lat->stats())[0,1];
|
|
||||||
printf "Total tokens: %s\nTotal expressins: %s\n", $tokens, $expressions;
|
|
||||||
$lat->save();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
# just return answer
|
|
||||||
sub latAnswer () {
|
|
||||||
my $braindir = dirname ($brain);
|
|
||||||
|
|
||||||
unless (-d $braindir) {
|
|
||||||
logger ("No lat module data: $braindir is absent! Train lat first.");
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
unless (-f $brain) {
|
|
||||||
logger ("No lat module data: $brain is absent! Train lat first.");
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
my $lat = Hailo->new (
|
|
||||||
brain => $brain,
|
|
||||||
# in our case mean amount of words in phase is 3
|
|
||||||
order => 2,
|
|
||||||
save_on_exit => 0
|
|
||||||
);
|
|
||||||
|
|
||||||
return $lat->reply();
|
|
||||||
}
|
|
||||||
|
|
||||||
1;
|
|
||||||
|
|
||||||
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
|
||||||
@@ -1,448 +0,0 @@
|
|||||||
package telegrambot;
|
|
||||||
# main bot gears are here
|
|
||||||
|
|
||||||
use 5.018;
|
|
||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use vars qw/$VERSION/;
|
|
||||||
use utf8;
|
|
||||||
use Data::Dumper;
|
|
||||||
use open qw(:std :utf8);
|
|
||||||
use File::Path qw( mkpath );
|
|
||||||
use Hailo;
|
|
||||||
use Mojo::Base 'Teapot::Bot::Brain';
|
|
||||||
|
|
||||||
use conf qw(loadConf);
|
|
||||||
use botlib qw(weather logger trim randomCommonPhrase);
|
|
||||||
use telegramlib qw(visavi);
|
|
||||||
use lat qw(latAnswer);
|
|
||||||
|
|
||||||
use Exporter qw(import);
|
|
||||||
our @EXPORT_OK = qw(run_telegrambot);
|
|
||||||
|
|
||||||
$VERSION = '1.0';
|
|
||||||
|
|
||||||
my $c = loadConf();
|
|
||||||
my $hailo;
|
|
||||||
my $myid;
|
|
||||||
my $myusername;
|
|
||||||
my $myfirst_name;
|
|
||||||
my $mylast_name;
|
|
||||||
my $myfullname;
|
|
||||||
# guess it later
|
|
||||||
my $can_talk = 0;
|
|
||||||
|
|
||||||
has token => $c->{telegrambot}->{token};
|
|
||||||
|
|
||||||
# i promise, i'll make use of this sub
|
|
||||||
sub __cron { ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines)
|
|
||||||
my $self = shift;
|
|
||||||
# noop
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub __on_msg {
|
|
||||||
my ($self, $msg) = @_;
|
|
||||||
# chat info
|
|
||||||
my $chatid;
|
|
||||||
my $chatname = 'Noname chat';
|
|
||||||
# user sending message info
|
|
||||||
my $userid;
|
|
||||||
my $username;
|
|
||||||
my $fullname;
|
|
||||||
my $vis_a_vi = 'unknown';
|
|
||||||
|
|
||||||
$can_talk = 0;
|
|
||||||
|
|
||||||
unless ($myid) {
|
|
||||||
my $myObj = Teapot::Bot::Brain::getMe ($self);
|
|
||||||
|
|
||||||
unless ($myObj) {
|
|
||||||
sleep 3;
|
|
||||||
$myObj = Teapot::Bot::Brain::getMe ($self);
|
|
||||||
}
|
|
||||||
|
|
||||||
$myid = $myObj->id;
|
|
||||||
# TODO: use these values instead of pre-defined in config!
|
|
||||||
$myusername = $myObj->username;
|
|
||||||
$myfirst_name = $myObj->first_name;
|
|
||||||
$mylast_name = $myObj->last_name;
|
|
||||||
|
|
||||||
if (defined ($myfirst_name) && ($myfirst_name ne '') && defined ($mylast_name) && ($mylast_name ne '')) {
|
|
||||||
$myfullname = $myfirst_name . ' ' . $mylast_name;
|
|
||||||
} elsif (defined ($myfirst_name) && ($myfirst_name ne '')) {
|
|
||||||
$myfullname = $myfirst_name;
|
|
||||||
} elsif (defined ($mylast_name) && ($mylast_name ne '')) {
|
|
||||||
$myfullname = $mylast_name;
|
|
||||||
} else {
|
|
||||||
$myfullname = $myusername;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($msg->chat->can ('id') && defined ($msg->chat->id)) {
|
|
||||||
$chatid = $msg->chat->id;
|
|
||||||
my $group_talk = 0;
|
|
||||||
|
|
||||||
if ($msg->chat->can ('username') && defined ($msg->chat->username)) {
|
|
||||||
$chatname = $msg->chat->username ;
|
|
||||||
} else {
|
|
||||||
if ($msg->chat->can ('title') && defined ($msg->chat->title)) {
|
|
||||||
$chatname = $msg->chat->title;
|
|
||||||
} else {
|
|
||||||
$chatname = 'Noname chat';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# because of bot api restriction there is no events about changing permissions
|
|
||||||
# in chat sent to bot so before sending any answer, we should check if we can do so
|
|
||||||
|
|
||||||
# N.B. there is situation when we do not recieve any messages from chat: if we
|
|
||||||
# are in exception list, even if it allows any kind of events for bot
|
|
||||||
|
|
||||||
# If we are just member of chat, it looks like we obey general chat restrictions,
|
|
||||||
# so we need only to query getChat in this case
|
|
||||||
# If we admin, we can get|send messages even if group by itself disallows it.
|
|
||||||
|
|
||||||
# works only for public chats, so id shoud be < 0.
|
|
||||||
if ($chatid < 0) {
|
|
||||||
my $chatobj = Teapot::Bot::Brain::getChat ($self, { 'chat_id' => $chatid });
|
|
||||||
|
|
||||||
unless ($chatobj) {
|
|
||||||
sleep 3;
|
|
||||||
$chatobj = Teapot::Bot::Brain::getChat ($self, { 'chat_id' => $chatid });
|
|
||||||
}
|
|
||||||
|
|
||||||
# actually evaluates to 1 for true and to 0 for false
|
|
||||||
$group_talk = int ($chatobj->{permissions}->{can_send_messages});
|
|
||||||
my $me = Teapot::Bot::Brain::getChatMember ($self, { 'chat_id' => $chatid, 'user_id' => $myid });
|
|
||||||
|
|
||||||
unless ($me) {
|
|
||||||
sleep 3;
|
|
||||||
$me = Teapot::Bot::Brain::getChatMember ($self, { 'chat_id' => $chatid, 'user_id' => $myid });
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($me->{'status'} eq 'administrator') {
|
|
||||||
logger "I can talk in group chat $chatname ($chatid)";
|
|
||||||
$can_talk = 1;
|
|
||||||
} else {
|
|
||||||
logger "I can talk in group chat $chatname ($chatid)" if ($group_talk);
|
|
||||||
logger "I can not talk in group chat $chatname ($chatid)" unless ($group_talk);
|
|
||||||
$can_talk = $group_talk;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
# private chat, so definely bot can talk
|
|
||||||
logger "I can talk in private chat $chatname ($chatid)";
|
|
||||||
$can_talk = 1;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger 'Unable to get chatid';
|
|
||||||
}
|
|
||||||
|
|
||||||
# according api user must have username and/or first_name and/or last_name at least one of these fields
|
|
||||||
if ($msg->can ('from') && defined ($msg->from)) {
|
|
||||||
$userid = $msg->from->id; # it must be filled, so do not check it
|
|
||||||
$username = $msg->from->username if ($msg->from->can ('username') && defined($msg->from->username));
|
|
||||||
|
|
||||||
if ($msg->from->can ('first_name') && defined ($msg->from->first_name)) {
|
|
||||||
$fullname = $msg->from->first_name;
|
|
||||||
|
|
||||||
if ($msg->from->can('last_name') && defined ($msg->from->last_name)) {
|
|
||||||
$fullname .= ' ' . $msg->from->last_name;
|
|
||||||
}
|
|
||||||
} elsif ($msg->from->can ('last_name') && defined ($msg->from->last_name)) {
|
|
||||||
$fullname .= $msg->from->last_name;
|
|
||||||
}
|
|
||||||
|
|
||||||
$vis_a_vi = visavi ($userid, $username, $fullname);
|
|
||||||
}
|
|
||||||
|
|
||||||
my $phrase = '';
|
|
||||||
|
|
||||||
# Newcommer event, greet our new member and suggest to introduce themself.
|
|
||||||
if ($msg->can ('new_chat_members') && defined ($msg->new_chat_members)) {
|
|
||||||
my $send_args;
|
|
||||||
$send_args->{parse_mode} = 'Markdown';
|
|
||||||
$send_args->{chat_id} = $chatid;
|
|
||||||
|
|
||||||
if (defined ($username)) {
|
|
||||||
if (defined ($fullname)) {
|
|
||||||
logger "Newcommer in $chatname ($chatid): \@$username, $fullname ($userid)";
|
|
||||||
$send_args->{text} = "Дратути, [$fullname](tg://user?id=$userid). Представьтес, пожалуйста, и расскажите, что вас сюда привело.";
|
|
||||||
} else {
|
|
||||||
logger "Newcommer in $chatname ($chatid): \@$username ($userid)";
|
|
||||||
$send_args->{text} = "Дратути, [$username](tg://user?id=$userid). Представьтес, пожалуйста, и расскажите, что вас сюда привело.";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger "Newcommer in $chatname ($chatid): $fullname ($userid)";
|
|
||||||
$send_args->{text} = "Дратути, [$fullname](tg://user?id=$userid). Представьтес, пожалуйста, и расскажите, что вас сюда привело.";
|
|
||||||
}
|
|
||||||
|
|
||||||
# let's emulate real human and delay answer
|
|
||||||
sleep (int ( rand (2) + 1));
|
|
||||||
|
|
||||||
for (0..(4 + int (rand (3)))) {
|
|
||||||
$msg->typing();
|
|
||||||
sleep(3);
|
|
||||||
sleep 3 unless ($_);
|
|
||||||
}
|
|
||||||
|
|
||||||
sleep ( 3 + int ( rand (2)));
|
|
||||||
|
|
||||||
Teapot::Bot::Brain::sendMessage ($self, $send_args);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
# lazy init chat-bot brains
|
|
||||||
unless (defined ($hailo->{$chatid})) {
|
|
||||||
my $brainname = sprintf ('%s/%s.brain.sqlite', $c->{telegrambot}->{braindir}, $chatid);
|
|
||||||
|
|
||||||
$hailo->{$chatid} = Hailo->new (
|
|
||||||
# we'll got file like this: data/telegrambot-brains/-1001332512695.brain.sqlite
|
|
||||||
brain => $brainname,
|
|
||||||
order => 3
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($chatid < 0) {
|
|
||||||
logger "Initialized brain for public chat $chatname ($chatid): $brainname";
|
|
||||||
} else {
|
|
||||||
logger "Initialized for private chat $chatname ($chatid): $brainname";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# is this a 1-on-1 ?
|
|
||||||
if ($msg->chat->type eq 'private') {
|
|
||||||
# TODO: what about stickers, photos, documents, audio, video, etc... We should log em at least.
|
|
||||||
return unless ($msg->can ('text') && defined ($msg->text));
|
|
||||||
|
|
||||||
my $text = $msg->text;
|
|
||||||
logger sprintf ('Private chat %s say to bot: %s', $vis_a_vi, $text);
|
|
||||||
my $csign = quotemeta ($c->{telegrambot}->{csign});
|
|
||||||
my $reply = 'Давайте ещё пообщаемся, а то я ещё не научилась от вас плохому.';
|
|
||||||
|
|
||||||
# TODO: Process commands in separate sub, they are same for public and private chats.
|
|
||||||
if (substr ($text, 0, 1) eq $c->{telegrambot}->{csign}) {
|
|
||||||
if (substr ($text, 1) eq 'ping') {
|
|
||||||
$reply = 'Pong.';
|
|
||||||
} elsif (substr ($text, 1) eq 'пинг') {
|
|
||||||
$reply = 'Понг.';
|
|
||||||
} elsif (substr ($text, 1, 2) eq 'w ' || substr ($text, 1, 2) eq 'п ') {
|
|
||||||
my $city = substr ($text, 2);
|
|
||||||
$reply = weather ($city);
|
|
||||||
} elsif ((length ($text) == 4) && (substr ($text, 1, 3) eq 'lat' || substr ($text, 1, 2) eq 'лат')) {
|
|
||||||
$reply = latAnswer();
|
|
||||||
} else {
|
|
||||||
$reply = 'Чего?';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
my $str = $hailo->{$msg->chat->id}->learn_reply ($text);
|
|
||||||
|
|
||||||
if (defined ($str) && $str ne '') {
|
|
||||||
$reply = $str;
|
|
||||||
# TODO: move it to telegramlib.pm/botlib.pm!
|
|
||||||
$phrase = trim ($text);
|
|
||||||
|
|
||||||
while ($phrase =~ /[\.|\,|\?|\!]$/) {
|
|
||||||
chop $phrase;
|
|
||||||
}
|
|
||||||
|
|
||||||
$phrase = lc ($phrase);
|
|
||||||
|
|
||||||
if (lc ($reply) eq $phrase) {
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
} elsif (lc ($reply) eq substr ($phrase, 0, -1)) {
|
|
||||||
# in case of trailing dot
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
} elsif (substr (lc ($reply), 0, -1) eq $phrase) {
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$msg->typing();
|
|
||||||
sleep 1;
|
|
||||||
logger sprintf ("Private chat bot reply to $vis_a_vi: %s", $reply);
|
|
||||||
$msg->reply ($reply);
|
|
||||||
# group chat
|
|
||||||
} elsif (($msg->chat->type eq 'supergroup') or ($msg->chat->type eq 'group')) {
|
|
||||||
my $reply;
|
|
||||||
|
|
||||||
# detect and log messages without text, noop here
|
|
||||||
unless (defined ($msg->text)) {
|
|
||||||
logger sprintf('No text in message from %s', $vis_a_vi);
|
|
||||||
|
|
||||||
if ($msg->can ('document') && defined ($msg->document)) {
|
|
||||||
if (defined ($msg->document->{'file_name'})) {
|
|
||||||
my $docsize = 'unknown';
|
|
||||||
$docsize = $msg->document->{'file_size'} if (defined ($msg->document->{'file_size'}));
|
|
||||||
my $type = 'unknown';
|
|
||||||
$type = $msg->document->{'mime_type'} if (defined ($msg->document->{'mime_type'}));
|
|
||||||
logger sprintf ('In public chat %s (%s) %s send document type %s named %s, size %s bytes', $chatname, $chatid, $vis_a_vi, $type, $msg->document->{'file_name'}, $docsize);
|
|
||||||
} else {
|
|
||||||
logger sprintf ('In public chat %s (%s) %s send unknown document', $chatname, $chatid, $vis_a_vi);
|
|
||||||
}
|
|
||||||
} elsif ($msg->can ('sticker') && defined ($msg->sticker)) {
|
|
||||||
my $set_name = 'unknown';
|
|
||||||
$set_name = $msg->sticker->set_name if ($msg->sticker->can ('set_name') && defined ($msg->sticker->set_name));
|
|
||||||
my $emoji = 'unknown';
|
|
||||||
$emoji = $msg->sticker->emoji if ($msg->sticker->can ('emoji') && defined ($msg->sticker->emoji));
|
|
||||||
logger sprintf ('In public chat %s (%s) %s reacted with sticker %s from pack %s', $chatname, $chatid, $vis_a_vi, $emoji, $set_name);
|
|
||||||
} elsif ($msg->can ('photo') && defined ($msg->photo)) {
|
|
||||||
# actually it is an array! duh, hate arrays!
|
|
||||||
logger sprintf ('In public chat %s (%s) %s send photo', $chatname, $chatid, $vis_a_vi);
|
|
||||||
} else {
|
|
||||||
logger Dumper ($msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
# we have text here! so potentially we can chit-chat
|
|
||||||
my $text = $msg->text;
|
|
||||||
logger sprintf ('In public chat %s (%s) %s say: %s', $chatname, $chatid, $vis_a_vi, $text);
|
|
||||||
my $qname = quotemeta ($c->{telegrambot}->{name});
|
|
||||||
my $qtname = quotemeta ($c->{telegrambot}->{tname});
|
|
||||||
my $csign = quotemeta ($c->{telegrambot}->{csign});
|
|
||||||
|
|
||||||
# are they quote something, maybe, us?
|
|
||||||
if (defined ($msg->reply_to_message) &&
|
|
||||||
defined ($msg->reply_to_message->from) &&
|
|
||||||
defined ($msg->reply_to_message->from->username) &&
|
|
||||||
($msg->reply_to_message->from->username eq $myusername)) {
|
|
||||||
logger sprintf ('In public chat %s (%s) %s quote us!', $chatname, $chatid, $vis_a_vi);
|
|
||||||
# remove our name from users reply, just in case
|
|
||||||
my $pat1 = quotemeta ('@' . $myusername);
|
|
||||||
my $pat2 = quotemeta ($myfullname);
|
|
||||||
$phrase = $text;
|
|
||||||
$phrase =~ s/$pat1//g;
|
|
||||||
$phrase =~ s/$pat2//g;
|
|
||||||
|
|
||||||
# figure out reply :)
|
|
||||||
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase);
|
|
||||||
# simple commands
|
|
||||||
# TODO: Process commands in separate sub, they are same for public and private chats.
|
|
||||||
# TODO: Log commands and answers
|
|
||||||
} elsif (substr ($text, 0, 1) eq $c->{telegrambot}->{csign}) {
|
|
||||||
if (substr ($text, 1) eq 'help') {
|
|
||||||
unless ($can_talk) {
|
|
||||||
return ;
|
|
||||||
}
|
|
||||||
|
|
||||||
my $send_args;
|
|
||||||
$send_args->{text} = << 'MYHELP';
|
|
||||||
```
|
|
||||||
!help | !помощь - список команд
|
|
||||||
!w город | !п город - погода в указанном городе
|
|
||||||
!ping | !пинг - попинговать бота
|
|
||||||
!lat | !лат - сгенерировать фразу из крылатых латинских выражений
|
|
||||||
```
|
|
||||||
Но на самом деле я бот больше для общения, чем для исполнения команд.
|
|
||||||
Поговоришь со мной?
|
|
||||||
MYHELP
|
|
||||||
$send_args->{parse_mode} = 'Markdown';
|
|
||||||
$send_args->{chat_id} = $chatid;
|
|
||||||
Teapot::Bot::Brain::sendMessage ($self, $send_args);
|
|
||||||
return;
|
|
||||||
} elsif (substr ($text, 1) eq 'ping') {
|
|
||||||
$reply = 'Pong.';
|
|
||||||
} elsif (substr ($text, 1) eq 'пинг') {
|
|
||||||
$reply = 'Понг.';
|
|
||||||
} elsif (substr ($text, 1) eq 'pong') {
|
|
||||||
$reply = 'Wat?';
|
|
||||||
} elsif (substr ($text, 1) eq 'понг') {
|
|
||||||
$reply = 'Шта?';
|
|
||||||
} elsif (substr ($text, 1, 2) eq 'w ' || substr ($text, 1, 2) eq 'п ') {
|
|
||||||
my $city = substr ($text, 3);
|
|
||||||
$reply = weather ($city);
|
|
||||||
} elsif (length ($text) == 4 && (substr ($text, 1, 3) eq 'lat' || substr ($text, 1, 3) eq 'лат')) {
|
|
||||||
$reply = latAnswer();
|
|
||||||
}
|
|
||||||
} elsif (
|
|
||||||
($text eq $qname) or
|
|
||||||
($text eq sprintf ('%s', $qtname)) or
|
|
||||||
($text eq sprintf ("@%s_bot", $qname)) or # :(
|
|
||||||
($text eq sprintf ('%s ', $qtname))
|
|
||||||
) {
|
|
||||||
$reply = 'Чего?';
|
|
||||||
} else {
|
|
||||||
# phrase directed to bot
|
|
||||||
if ((lc ($text) =~ /^${qname}[\,|\:]? (.+)/) or (lc ($text) =~ /^${qtname}[\,|\:]? (.+)/)){
|
|
||||||
$phrase = $1;
|
|
||||||
$reply = $hailo->{$msg->chat->id}->learn_reply ($phrase);
|
|
||||||
# bot mention by name
|
|
||||||
} elsif ((lc ($text) =~ /.+ ${qname}[\,|\!|\?|\.| ]/) or (lc ($text) =~ / $qname$/)) {
|
|
||||||
$phrase = $text;
|
|
||||||
$reply = $hailo->{$msg->chat->id}->reply($phrase);
|
|
||||||
# bot mention by telegram name
|
|
||||||
} elsif ((lc ($text) =~ /.+ ${qtname}[\,|\!|\?|\.| ]/) or (lc ($text) =~ / $qtname$/)) {
|
|
||||||
$phrase = $text;
|
|
||||||
$reply = $hailo->{$msg->chat->id}->reply ($phrase);
|
|
||||||
# just message in chat
|
|
||||||
} else {
|
|
||||||
$hailo->{$msg->chat->id}->learn ($text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (defined ($reply) && $reply ne '' && $can_talk) {
|
|
||||||
# work a bit more on input phrase
|
|
||||||
$phrase = trim ($phrase);
|
|
||||||
|
|
||||||
while ($phrase =~ /[\.|\,|\?|\!]$/) {
|
|
||||||
chop $phrase;
|
|
||||||
}
|
|
||||||
|
|
||||||
$phrase = lc ($phrase);
|
|
||||||
|
|
||||||
if (lc ($reply) eq $phrase) {
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
} elsif (lc ($reply) eq substr ($phrase, 0, -1)) {
|
|
||||||
# in case of trailing dot
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
} elsif (substr(lc ($reply), 0, -1) eq $phrase) {
|
|
||||||
$reply = randomCommonPhrase();
|
|
||||||
}
|
|
||||||
|
|
||||||
$msg->typing();
|
|
||||||
sleep (int (rand (2)));
|
|
||||||
logger sprintf ('In public chat %s (%s) bot reply to %s: %s', $chatname, $chatid, $vis_a_vi, $reply);
|
|
||||||
$msg->reply ($reply);
|
|
||||||
} else {
|
|
||||||
if ($can_talk) {
|
|
||||||
logger sprintf ('In public chat %s (%s) bot is not required to reply to %s', $chatname, $chatid, $vis_a_vi);
|
|
||||||
} else {
|
|
||||||
logger sprintf ('In public chat %s (%s) bot can\'t talk, but reply to %s is: %s', $chatname, $chatid, $vis_a_vi, $reply);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# should be channel, so we can't talk
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
# setup our bot
|
|
||||||
sub init {
|
|
||||||
unless (-d $c->{telegrambot}->{braindir}) {
|
|
||||||
mkpath ($c->{telegrambot}->{braindir}, 0, 0755); ## no critic (ValuesAndExpressions::ProhibitLeadingZeros)
|
|
||||||
}
|
|
||||||
|
|
||||||
my $self = shift;
|
|
||||||
$self->add_listener (\&__on_msg);
|
|
||||||
# $self->add_repeating_task(900, \&__cron);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sub run_telegrambot {
|
|
||||||
while (sleep 3) {
|
|
||||||
eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval)
|
|
||||||
telegrambot->new->think;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
1;
|
|
||||||
|
|
||||||
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package telegramlib;
|
|
||||||
# store here functions that are not implemented in Teapot::Bot
|
|
||||||
|
|
||||||
use 5.018;
|
|
||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use utf8;
|
|
||||||
use open qw(:std :utf8);
|
|
||||||
|
|
||||||
use botlib qw(trim);
|
|
||||||
use Teapot::Bot::Brain;
|
|
||||||
|
|
||||||
# module shit
|
|
||||||
use vars qw/$VERSION/;
|
|
||||||
use Exporter qw(import);
|
|
||||||
our @EXPORT_OK = qw(visavi);
|
|
||||||
|
|
||||||
$VERSION = '1.0';
|
|
||||||
|
|
||||||
sub visavi {
|
|
||||||
my ($userid, $username, $fullname) = @_;
|
|
||||||
my $name = '';
|
|
||||||
|
|
||||||
if (defined ($username)) {
|
|
||||||
$name .= '@' . $username;
|
|
||||||
$name .= ', ' . $fullname if (defined ($fullname));
|
|
||||||
} else {
|
|
||||||
$name .= $fullname;
|
|
||||||
}
|
|
||||||
|
|
||||||
$name .= " ($userid)";
|
|
||||||
return $name;
|
|
||||||
}
|
|
||||||
|
|
||||||
1;
|
|
||||||
|
|
||||||
# vim: ft=perl noet ai ts=4 sw=4 sts=4:
|
|
||||||
Reference in New Issue
Block a user