Compare commits

..

156 Commits

Author SHA1 Message Date
github-actions[bot]
d17cfa4132 Updated modules.json after parse 2026-06-18 02:53:20 2026-06-18 02:53:20 +00:00
github-actions[bot]
ea3567f38a Added and updated repositories 2026-06-18 02:52:50 2026-06-18 02:52:50 +00:00
2770ae1ccc fix: now supports video / gif baners 2026-06-12 12:15:31 +03:00
Macsim
c3390a5887 Merge pull request #315 from MuRuLOSE/update-submodules_d33e49b6967d97ab3dc83dc74e03537a26defd62
Update of repositories 2026-06-12 08:37:40
2026-06-12 11:59:03 +03:00
github-actions[bot]
2ff79975c2 Updated modules.json after parse 2026-06-12 08:37:15 2026-06-12 08:37:15 +00:00
github-actions[bot]
ab03f6ed94 Added and updated repositories 2026-06-12 08:36:40 2026-06-12 08:36:40 +00:00
d33e49b696 fix 2026-06-12 11:34:55 +03:00
04cc1dc4b3 New developer 2026-06-12 11:24:33 +03:00
6b6afb7493 fix: Ported fix from stable, in python version below 3.12 you can't use " with f-strings 2026-06-08 09:46:37 +03:00
Macsim
2ed246b9ad Merge pull request #301 from MuRuLOSE/update-submodules_d279789b37a939b3d9ececce6b4d0e1992293c23
Update of repositories 2026-05-31 02:48:09
2026-06-01 00:23:40 +03:00
github-actions[bot]
837784206f Updated modules.json after parse 2026-05-31 02:47:46 2026-05-31 02:47:46 +00:00
github-actions[bot]
811beb2b74 Added and updated repositories 2026-05-31 02:47:15 2026-05-31 02:47:16 +00:00
Zahar Vanilovv
d279789b37 Merge pull request #273 from MuRuLOSE/update-submodules_63944822139e8b6869fe2250ad8c650e9db06765
Update of repositories 2026-05-03 02:11:45
2026-05-03 05:14:12 +03:00
github-actions[bot]
74dfe4caf8 Updated modules.json after parse 2026-05-03 02:11:26 2026-05-03 02:11:26 +00:00
github-actions[bot]
18b8247e21 Added and updated repositories 2026-05-03 02:10:53 2026-05-03 02:10:53 +00:00
6394482213 fix: banners now will be visible no matter what 2026-04-25 09:23:54 +03:00
43a0e578c1 fix: 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 21:58:27 +03:00
3112e6d4bf python-magic is shit so its replaced with filetype due to magic requires its own binary in order to work 2026-04-24 21:43:29 +03:00
18bb817239 fix: if server does not return Content-Type in header we will try determine MIME-type offline
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 21:37:39 +03:00
24f1983e2a fix: not awaited update function 2026-04-24 21:16:36 +03:00
74638c14d0 feat: now you can see version if module updated
Co-authored-by: Copilot <copilot@github.com>
2026-04-24 20:56:58 +03:00
Macsim
db62a5aee1 Merge pull request #264 from MuRuLOSE/update-submodules_49956ba865b533dca03b344d048f96465a6be62e
Update of repositories 2026-04-24 17:42:48
2026-04-24 20:43:54 +03:00
github-actions[bot]
4d2a2899f4 Updated modules.json after parse 2026-04-24 17:42:27 2026-04-24 17:42:27 +00:00
github-actions[bot]
2a27c56d83 Added and updated repositories 2026-04-24 17:41:57 2026-04-24 17:41:57 +00:00
49956ba865 version bump 2026-04-24 20:33:45 +03:00
f0d2a28105 removed H.modules
feat: added force index update

Co-authored-by: Copilot <copilot@github.com>
2026-04-24 20:10:52 +03:00
13d091c56c removed H.Modules by request 2026-04-19 16:10:58 +03:00
d7cf406b78 feat: Added 'by developer' if meta developer in module and event if module new
fix: if some event happened with module, changes message will not be sended
2026-04-19 14:40:13 +03:00
Macsim
0f30a78990 Merge pull request #257 from MuRuLOSE/update-submodules_e50c7c1688b89901690bc01609544e5c3e238097
Update of repositories 2026-04-19 02:02:27
2026-04-19 14:16:50 +03:00
github-actions[bot]
16adfac8b5 Updated modules.json after parse 2026-04-19 02:02:03 2026-04-19 02:02:03 +00:00
github-actions[bot]
7ddb190b35 Added and updated repositories 2026-04-19 02:01:35 2026-04-19 02:01:35 +00:00
e50c7c1688 drop: debug log 2026-04-18 14:08:04 +03:00
f3682ed87a fix: version displaying wrong and some shit idk 2026-04-18 13:41:49 +03:00
be47e59d97 fix: some broken strings
feat: install button and new limoka version update notification
drop: watcher that installs module  from bot (temporary)
2026-04-18 13:19:24 +03:00
eb71e39fcf Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-18 11:01:48 +03:00
Macsim
7d713e36c0 Merge pull request #256 from MuRuLOSE/update-submodules_a424d6bac4fb0d52521fca595af24968162bcc87
Update of repositories 2026-04-18 01:50:07
2026-04-18 10:58:20 +03:00
github-actions[bot]
a8fde5e498 Updated modules.json after parse 2026-04-18 01:49:43 2026-04-18 01:49:43 +00:00
github-actions[bot]
4a03c6cb1a Added and updated repositories 2026-04-18 01:49:10 2026-04-18 01:49:10 +00:00
Macsim
a424d6bac4 Merge pull request #254 from MuRuLOSE/update-submodules_59564f07b5b57f12eec78ff6e8f0574c70e37f8b
Update of repositories 2026-04-16 02:02:29
2026-04-16 07:39:02 +03:00
github-actions[bot]
fc8344ca05 Updated modules.json after parse 2026-04-16 02:02:11 2026-04-16 02:02:11 +00:00
github-actions[bot]
3e62dc0b69 Added and updated repositories 2026-04-16 02:01:42 2026-04-16 02:01:42 +00:00
41f253b471 feat: deleted files now got dedicated notification too 2026-04-15 18:02:16 +03:00
Macsim
59564f07b5 Merge pull request #253 from MuRuLOSE/update-submodules_3a193cfb2f731c403bbc542d2408c6144d0bcda7
Update of repositories 2026-04-15 01:54:22
2026-04-15 17:35:17 +03:00
github-actions[bot]
dfe2ae1103 Updated modules.json after parse 2026-04-15 01:53:44 2026-04-15 01:53:44 +00:00
github-actions[bot]
4ca7279309 Added and updated repositories 2026-04-15 01:53:05 2026-04-15 01:53:05 +00:00
3a193cfb2f fix: blockquote not needed here 2026-04-14 18:29:41 +03:00
637f9d82ae fix: another try to fix notifications 2026-04-13 20:24:29 +03:00
316e623c64 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-13 19:30:23 +03:00
57044428fd fix: added some tags 2026-04-13 19:30:20 +03:00
Macsim
2df0f9814f Merge pull request #250 from MuRuLOSE/update-submodules_e1a143311140eb28af693fc48a66f6b0e18ded3c
Update of repositories 2026-04-12 17:39:30
2026-04-12 20:40:03 +03:00
github-actions[bot]
46c955bb7b Updated modules.json after parse 2026-04-12 17:39:10 2026-04-12 17:39:10 +00:00
github-actions[bot]
887a55f798 Added and updated repositories 2026-04-12 17:38:40 2026-04-12 17:38:40 +00:00
e1a1433111 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-12 20:29:10 +03:00
github-actions[bot]
cc99e880ca Updated modules.json after parse 2026-04-12 17:29:01 2026-04-12 17:29:01 +00:00
b99b068fa0 feat: idk i forgot what i did 2026-04-12 20:28:32 +03:00
6d8e2db072 feat: now supports emojies in inline + little refactor 2026-04-12 20:28:13 +03:00
github-actions[bot]
60e7c852e5 Updated modules.json after parse 2026-04-12 16:47:37 2026-04-12 16:47:37 +00:00
de4d449a03 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-12 19:46:43 +03:00
86ebd01cc6 version bump 2026-04-12 19:46:34 +03:00
github-actions[bot]
5aadbb3084 Updated modules.json after parse 2026-04-12 16:46:02 2026-04-12 16:46:02 +00:00
143cbc4787 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-12 19:45:27 +03:00
15623e4a7b feat: no tags entierly if no tags
fix: no <blockquote> in enter_query
fix: fixed module crashing on python <= 3.10.15 - 3.10.20
2026-04-12 19:45:14 +03:00
github-actions[bot]
b20e31a149 Updated modules.json after parse 2026-04-12 16:33:57 2026-04-12 16:33:57 +00:00
75dedbae7c Updated .gitignore up-to-date 2026-04-12 19:33:25 +03:00
github-actions[bot]
4aff88ae13 Updated modules.json after parse 2026-04-12 15:09:46 2026-04-12 15:09:46 +00:00
eedcd4e60b drop: parse dependency for notify_diffs because not needed actually 2026-04-12 18:09:05 +03:00
57bc2c203a Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-04-12 18:07:47 +03:00
eeb49fca81 fix: Update CI workflow to reflect branch name change 2026-04-12 18:05:35 +03:00
Macsim
d3c195f212 Merge pull request #248 from MuRuLOSE/update-submodules_3156a432f050e4eb8bfcb171266bfceadfb9d5a1
Update of repositories 2026-04-12 14:57:57
2026-04-12 18:03:30 +03:00
github-actions[bot]
43f65359cd Updated modules.json after parse 2026-04-12 14:57:35 2026-04-12 14:57:35 +00:00
github-actions[bot]
c4b56bee9b Added and updated repositories 2026-04-12 14:57:04 2026-04-12 14:57:04 +00:00
3156a432f0 Legacy is here! 2026-04-12 17:54:16 +03:00
09523f59a0 fix: pull request update notification 2026-04-12 17:52:18 +03:00
31c9d0c074 fix: now parses all modules that inherits from loader.Module 2026-04-12 17:50:37 +03:00
e7b4c57940 feat: New developers 2026-04-12 17:49:43 +03:00
58316ec8b2 feat: Interface update 2026-04-12 17:49:15 +03:00
Macsim
4818d0fe91 Merge pull request #247 from MuRuLOSE/update-submodules_7555ea280ec5ac2e90f16112979cb31cab38a676
Update of repositories 2026-04-12 13:57:50
2026-04-12 17:24:47 +03:00
Macsim
997f892e06 Cleaned up unused code. 2026-04-12 17:04:41 +03:00
Macsim
1a92b84d89 dead 2026-04-12 17:02:29 +03:00
github-actions[bot]
001a8c5c30 Updated modules.json after parse 2026-04-12 13:57:28 2026-04-12 13:57:28 +00:00
github-actions[bot]
17ae450f8f Added and updated repositories 2026-04-12 13:56:57 2026-04-12 13:56:57 +00:00
Macsim
7555ea280e Merge pull request #226 from MuRuLOSE/update-submodules_e8f808b7dc145caab9c5cc1ce2901adcdb112f03
Update of repositories 2026-03-23 01:31:45
2026-03-23 18:57:25 +03:00
Macsim
59e3bc900f Removed stream.py because of security measures 2026-03-23 18:56:54 +03:00
github-actions[bot]
2d4181c22e Updated modules.json after parse 2026-03-23 01:31:17 2026-03-23 01:31:17 +00:00
github-actions[bot]
9a29d5ec99 Added and updated repositories 2026-03-23 01:30:41 2026-03-23 01:30:41 +00:00
Zahar Vanilovv
e8f808b7dc Merge pull request #214 from MuRuLOSE/update-submodules_02b1aa9f68911e516619089e9065b26a7592e781
Update of repositories 2026-03-11 01:22:36
2026-03-11 04:23:50 +03:00
github-actions[bot]
4cbe96ac7f Updated modules.json after parse 2026-03-11 01:22:17 2026-03-11 01:22:17 +00:00
github-actions[bot]
7fbb379419 Added and updated repositories 2026-03-11 01:21:45 2026-03-11 01:21:45 +00:00
Zahar Vanilovv
02b1aa9f68 Merge pull request #206 from MuRuLOSE/update-submodules_3a1dbc93cdf6f986e42501ce8bb564b7043fd762
Update of repositories 2026-03-03 01:29:31
2026-03-03 04:32:11 +03:00
github-actions[bot]
b32a65e515 Updated modules.json after parse 2026-03-03 01:28:23 2026-03-03 01:28:23 +00:00
github-actions[bot]
06973235e0 Added and updated repositories 2026-03-03 01:27:55 2026-03-03 01:27:55 +00:00
Zahar Vanilovv
3a1dbc93cd Merge pull request #200 from MuRuLOSE/update-submodules_1b01025a6674d1fc0578ed14c51e57a5aaa3971d
Update of repositories 2026-02-25 01:29:41
2026-02-25 15:56:04 +03:00
github-actions[bot]
33e0f03bdc Updated modules.json after parse 2026-02-25 01:29:20 2026-02-25 01:29:20 +00:00
github-actions[bot]
f9aa413329 Added and updated repositories 2026-02-25 01:28:51 2026-02-25 01:28:51 +00:00
Zahar Vanilovv
1b01025a66 Merge pull request #196 from MuRuLOSE/update-submodules_392e33b019901b44d53bc1bb8bd1d5b56ae0c90e
Update of repositories 2026-02-21 01:23:31
2026-02-21 04:29:23 +03:00
github-actions[bot]
2b2fd54185 Updated modules.json after parse 2026-02-21 01:23:09 2026-02-21 01:23:09 +00:00
github-actions[bot]
98e6966695 Added and updated repositories 2026-02-21 01:22:37 2026-02-21 01:22:37 +00:00
Macsim
392e33b019 Merge pull request #191 from MuRuLOSE/update-submodules_ccc67c8327d13e8ce92855a74265f8e1acf29657
Update of repositories 2026-02-16 01:28:14
2026-02-16 10:23:09 +03:00
github-actions[bot]
6ed325f906 Updated modules.json after parse 2026-02-16 01:27:56 2026-02-16 01:27:56 +00:00
github-actions[bot]
39be095e7e Added and updated repositories 2026-02-16 01:27:27 2026-02-16 01:27:27 +00:00
ccc67c8327 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-02-14 19:08:36 +03:00
bcc1d73f0c some fixes to update notifications 2026-02-14 13:48:53 +03:00
d5276c6242 small blacklist fixes 2026-02-14 13:48:18 +03:00
Macsim
005c5fc832 Merge pull request #189 from MuRuLOSE/update-submodules_54229a82664ad0d60b5d0007f099d8823bee5a89
Update of repositories 2026-02-14 06:58:46
2026-02-14 10:00:53 +03:00
github-actions[bot]
430f49f345 Updated modules.json after parse 2026-02-14 06:58:27 2026-02-14 06:58:27 +00:00
54229a8266 nvm 2026-02-14 09:54:25 +03:00
Zahar Vanilovv
6cb625acd8 Merge pull request #183 from MuRuLOSE/update-submodules_61ebb7fa472caa2abd4d6c7523bcf8830258167c
Update of repositories 2026-02-09 01:29:55
2026-02-09 17:25:41 +03:00
github-actions[bot]
bf03595075 Updated modules.json after parse 2026-02-09 01:29:33 2026-02-09 01:29:33 +00:00
github-actions[bot]
8bef604170 Added and updated repositories 2026-02-09 01:29:03 2026-02-09 01:29:03 +00:00
61ebb7fa47 Legacy version is here! 2026-02-08 20:17:50 +03:00
Zahar Vanilovv
2702cd2356 Merge pull request #182 from MuRuLOSE/update-submodules_ab5aaf579b3117a79d44591859b2cd30a6fcd5a1
Update of repositories 2026-02-08 01:59:39
2026-02-08 08:01:47 +03:00
github-actions[bot]
37f53375bc Updated modules.json after parse 2026-02-08 01:59:16 2026-02-08 01:59:16 +00:00
github-actions[bot]
23dade9b9e Added and updated repositories 2026-02-08 01:58:46 2026-02-08 01:58:46 +00:00
Macsim
ab5aaf579b Merge pull request #181 from MuRuLOSE/update-submodules_78a9b0cb76b2d495a5ff23a25614d91699a8757d
Update of repositories 2026-02-07 07:57:35
2026-02-07 11:05:32 +03:00
github-actions[bot]
170809519a Updated modules.json after parse 2026-02-07 07:57:13 2026-02-07 07:57:13 +00:00
78a9b0cb76 added full tds attribute 2026-02-07 10:54:30 +03:00
Macsim
c1d407f885 Merge pull request #180 from MuRuLOSE/update-submodules_7cda8f2685159651f9c2c9ff238215f2b5894d6c
Update of repositories 2026-02-07 07:41:22
2026-02-07 10:43:12 +03:00
github-actions[bot]
cf230d2922 Updated modules.json after parse 2026-02-07 07:41:02 2026-02-07 07:41:02 +00:00
7cda8f2685 fix f-strings while parsing 2026-02-07 10:35:19 +03:00
Macsim
92bdd1510d Merge pull request #179 from MuRuLOSE/update-submodules_a7b8c740b42879d9b3c0d577d275d5b42e4db254
Update of repositories 2026-02-07 01:23:55
2026-02-07 10:34:25 +03:00
github-actions[bot]
52f6fc53c3 Updated modules.json after parse 2026-02-07 01:23:38 2026-02-07 01:23:38 +00:00
github-actions[bot]
5c25eaad81 Added and updated repositories 2026-02-07 01:23:08 2026-02-07 01:23:08 +00:00
a7b8c740b4 Now index locking should be not a problem 2026-02-06 12:27:31 +03:00
44ca8633c6 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-02-06 12:03:00 +03:00
e076d4ab28 lang and dev_username hotfix 2026-02-06 12:02:48 +03:00
Macsim
634861943a Merge pull request #177 from MuRuLOSE/update-submodules_f68d97d09b6ca907775228791cde9446509954c8
Update of repositories 2026-02-06 01:25:04
2026-02-06 07:43:55 +03:00
github-actions[bot]
d20d019c32 Updated modules.json after parse 2026-02-06 01:24:40 2026-02-06 01:24:40 +00:00
github-actions[bot]
041e6ec5f7 Added and updated repositories 2026-02-06 01:24:12 2026-02-06 01:24:12 +00:00
f68d97d09b bolded some text 2026-02-05 20:30:35 +03:00
e624861b64 Blacklisted some module 2026-02-05 20:17:09 +03:00
Macsim
d3f035ec58 Merge pull request #176 from MuRuLOSE/update-submodules_5c2de322d31171b50a220dcbb9862aea611ab15a
Update of repositories 2026-02-05 01:23:39
2026-02-05 20:07:37 +03:00
Macsim
1ced5efae6 Update SpotifyMod.py 2026-02-05 20:01:13 +03:00
github-actions[bot]
3bf476c8a9 Updated modules.json after parse 2026-02-05 01:23:15 2026-02-05 01:23:15 +00:00
github-actions[bot]
abff91c013 Added and updated repositories 2026-02-05 01:22:45 2026-02-05 01:22:45 +00:00
5c2de322d3 new developer 2026-01-30 20:29:03 +03:00
5b2fe145ff b 2026-01-30 17:17:10 +03:00
64d8ceb354 clear histroy 2026-01-30 16:58:22 +03:00
537ae4c485 againfix 2026-01-30 16:50:55 +03:00
52018c8e14 fix not found PeerUser bcs of id 2026-01-30 15:42:57 +03:00
6f95292df1 hotfix again 2026-01-30 15:31:04 +03:00
4a5d4883a9 version bump 2026-01-30 15:22:55 +03:00
ce59b13c94 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-01-30 15:22:26 +03:00
91351cb83d hotfix (i am scared...) 2026-01-30 15:22:01 +03:00
Macsim
118a800856 Merge pull request #170 from MuRuLOSE/update-submodules_51bbb98711dbacc9d018d87706b7f28c77463cc4
Update of repositories 2026-01-30 11:59:59
2026-01-30 15:00:33 +03:00
github-actions[bot]
f14a99c640 Updated modules.json after parse 2026-01-30 11:59:36 2026-01-30 11:59:36 +00:00
github-actions[bot]
c76dcc0fc1 Added and updated repositories 2026-01-30 11:59:07 2026-01-30 11:59:07 +00:00
51bbb98711 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-01-30 14:56:57 +03:00
edd70ad020 бь 2026-01-30 14:56:48 +03:00
Macsim
2c33b08ea0 Merge pull request #169 from MuRuLOSE/update-submodules_88ab2657552874370ef8600b9655bbfe90c2decd
Update of repositories 2026-01-30 11:50:56
2026-01-30 14:52:28 +03:00
github-actions[bot]
e9bb89cf62 Updated modules.json after parse 2026-01-30 11:50:33 2026-01-30 11:50:33 +00:00
github-actions[bot]
51055e6427 Added and updated repositories 2026-01-30 11:50:03 2026-01-30 11:50:03 +00:00
88ab265755 fixed workflow 2026-01-30 14:46:22 +03:00
Macsim
baada2d019 Merge pull request #168 from MuRuLOSE/update-submodules_2dd772b52d052144384a8e0c71f2d33b7c21ff1d
Update of repositories 2026-01-30 11:40:55
2026-01-30 14:42:26 +03:00
github-actions[bot]
ad782a6f46 Updated modules.json after parse 2026-01-30 11:40:21 2026-01-30 11:40:21 +00:00
github-actions[bot]
2435df880e Added and updated repositories 2026-01-30 11:39:54 2026-01-30 11:39:54 +00:00
2dd772b52d fix (wrong json structure) 2026-01-30 14:38:18 +03:00
1432 changed files with 315280 additions and 809 deletions

View File

@@ -10,8 +10,10 @@ on:
pull_request:
branches:
- main
types: [opened, synchronize, reopened, closed]
workflow_dispatch: # Allows manual triggering from GitHub UI
# Environment variables available to all jobs
env:
BRANCH_NAME: "update-submodules_${{ github.sha }}"
@@ -94,13 +96,13 @@ jobs:
git push origin ${{ env.BRANCH_NAME }} --force
parse:
needs: update
runs-on: ubuntu-latest
if: |
github.event_name == 'schedule' ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'push' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged == true)
needs: update
steps:
- name: Set branch ref for parse
id: setref
@@ -208,15 +210,13 @@ jobs:
notify_diffs:
runs-on: ubuntu-latest
if: |
(github.event_name == 'push' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged == true)
needs: parse
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: ${{ env.GIT_DEPTH }}
- name: Configure Git for github-actions[bot]
fetch-depth: 0
- name: Configure Git
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
@@ -224,16 +224,16 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.9'
- name: Install Python dependencies
- name: Install dependencies
run: pip install aiohttp
- name: Send module diffs to channel
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID_UPDATE }}
run: |
git fetch origin main
python3 update_diffs.py --token ${{ secrets.TELEGRAM_BOT_TOKEN }} --chat_id ${{ secrets.TELEGRAM_CHAT_ID_UPDATE }} --base_commit HEAD~1
backup:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch'

6
.gitignore vendored
View File

@@ -175,4 +175,8 @@ cython_debug/
# Limoka specific ignores
*.pem
assets/bot/whitelist.json
assets/bot/whitelist.json
# Configurations for VS Code
.vscode/
pyrightconfig.json

View File

@@ -0,0 +1,125 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Autotime
# Description: Automatic stuff for your profile
# Commands: autoname, autobio, cfgset
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 0, 0)
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.utils import get_display_name
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import Message
from .. import loader, utils
import re
import datetime
import asyncio
@loader.tds
class Autotime(loader.Module):
"""Automatic stuff for your profile"""
strings = {
"name": "Autotime",
"no_time": "<emoji document_id=5289755247298747469>😒</emoji> You didn't place a {time}",
"cfg": "Positive or negative integer from -12 to 12 inclusively"
}
def __init__(self):
self.bio_on = False
self.name_on = False
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Timezone",
"0",
lambda: self.strings["cfg"],
validator=loader.validators.Integer()
)
)
async def client_ready(self):
self.me = await self.client.get_me()
def _time(self):
offset = datetime.timedelta(hours=self.config["Timezone"])
tz = datetime.timezone(offset)
now = datetime.datetime.now(tz)
time = now.strftime("%H:%M")
return time
async def cfgsetcmd(self, message: Message):
""" <number> - specify a timezone
Regarding to UTC+0"""
tz = utils.get_args_raw(message)
q = await self.invoke(
"fconfig",
f"{self.strings('name')} Timezone {tz}",
message.chat.id
)
await self.client.delete_messages(message.chat.id, [message, q])
async def autonamecmd(self, message: Message):
""" <text> - autotime in nickname | {time} must be placed in the text
Write without argument to disable"""
args = utils.get_args_raw(message)
if not args:
self.name_on = False
regex = r"\d\d:\d\d"
name = utils.escape_html(get_display_name(self.me))
name = re.sub(regex, "", name)
name.replace(" ", "")
await self.client(UpdateProfileRequest(first_name=name))
return await message.delete()
if "{time}" not in args:
return await utils.answer(message, self.strings["no_time"])
self.name_on = True
await message.delete()
while self.name_on:
text = args.replace("{time}", self._time())
await self.client(UpdateProfileRequest(first_name=text))
await asyncio.sleep(180)
async def autobiocmd(self, message: Message):
""" <text> - autotime in bio | {time} must be placed in the text
Write without argument to disable"""
args = utils.get_args_raw(message)
if not args:
self.bio_on = False
regex = r"\d\d:\d\d"
bio = (await self.client(GetFullUserRequest(self.tg_id))).full_user.about
bio = re.sub(regex, "", bio)
bio.replace(" ", " ")
await self.client(UpdateProfileRequest(about=bio))
return await message.delete()
if "{time}" not in args:
return await utils.answer(message, self.strings["no_time"])
self.bio_on = True
await message.delete()
while self.bio_on:
text = args.replace("{time}", self._time())
await self.client(UpdateProfileRequest(about=text))
await asyncio.sleep(180)

View File

@@ -0,0 +1,253 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Channel Imitator
# Description: Imitates someone else's channel in yours
# Commands: imitate
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 1, 0)
from .. import loader, utils
from telethon.tl.functions.messages import EditChatAboutRequest
from telethon.tl.functions.channels import (
ToggleSignaturesRequest,
EditPhotoRequest,
GetFullChannelRequest,
EditTitleRequest
)
from telethon.tl.types import (
Message,
MessageMediaUnsupported,
MessageMediaPoll,
Channel,
Chat,
User
)
from telethon.tl.functions.account import UpdateProfileRequest
import asyncio
import io
@loader.tds
class ChannelImitator(loader.Module):
"""
Imitates someone else's channel in yours
Make assured your channel doesn't include avatars before using otherwise stolen ones will be overlayed with them
!!!If your account is experiencing a frequent floodwait limitations specify at least 150 in the Cooldown config!!!
"""
strings = {
"name": "ChannelImitator",
"start": "<emoji document_id=5444965061749644170>👨‍💻</emoji> It will take a few minutes.... probably much more",
"cfg_author": "Specify a text that will appear instead of an absencing real author name",
"cfg_forwarded": "Specify a text that will will appear instead of an absecing real forwarder name",
"cfg_cooldown": "Specify a cooldown time between every sending"
}
def __init__(self):
self.me = await self.client.get_me()
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Your channel",
None,
lambda: "Specify your channel ID",
validator=loader.validators.TelegramID()
),
loader.ConfigValue(
"Another channel",
None,
lambda: "Specify an another channel ID",
validator=loader.validators.TelegramID()
),
loader.ConfigValue(
"Author replacer",
"<i>No author</i>",
lambda: self.strings["cfg_author"],
validator=loader.validators.String()
),
loader.ConfigValue(
"Forwarded replacer",
"<i>Unknown</i>",
lambda: self.strings["cfg_forwarded"],
validator=loader.validators.String()
),
loader.ConfigValue(
"Cooldown",
60,
lambda: self.strings["cfg_cooldown"],
validator=loader.validators.Integer()
)
)
async def checkData(self, iterList, item):
is_ignore = False
is_noneCaption = False
is_fwd = True if item.fwd_from else False
is_media = True if item.media else False
media = None
name = None
name_id = None
author = item.post_author if item.post_author else self.config["Author replacer"]
if is_media and (isinstance(item.media, (MessageMediaUnsupported, MessageMediaPoll)) or hasattr(item.media, "months")):
is_ignore = True
try:
text = item.text
except:
text = "§"
if is_media and text == "":
is_noneCaption = True
media = io.BytesIO(await item.download_media(bytes))
if isinstance(media, MessageMediaUnsupported):
media = None
elif is_ignore:
pass
elif hasattr(item.media, "photo"):
media.name = "photo.png"
else:
media.name = item.media.document.mime_type.replace("/", ".")
if is_fwd:
if item.fwd_from.from_id:
name_id = item.fwd_from.from_id
try:
entity = await self.client.get_entity(name_id)
if isinstance(entity, (Channel, Chat)):
name = entity.title
elif isinstance(entity, User):
if entity.first_name:
name = f"{entity.first_name} {entity.last_name if entity.lastname else ''}"
else:
name = "<i>Deleted</i>"
except:
name = self.config["Forwarded replacer"]
else:
name = item.fwd_from.from_name if item.fwd_from.from_name else self.config["Forwarded replacer"]
_dict = {
"media": media,
"text": text,
"author": author,
"name": name,
"id": name_id,
"is_media": is_media,
"is_noneCaption": is_noneCaption
}
iterList.append(_dict)
return iterList
async def imitatecmd(self, message: Message):
""" [limit: int] [-save] - save all the media and messages from specified channel
-save - simply save without changing title, bio and/or avatars"""
args = (utils.get_args_raw(message)).split()
limit = None
if args:
limit = int(args[0]) if args[0].isdigit() else None
yourChannel = self.config["Your channel"]
anotherChannel = self.config["Another channel"]
if not all(isinstance(i, Channel) for i in [
(await self.client.get_entity(yourChannel)),
(await self.client.get_entity(anotherChannel))
]):
return await utils.answer(message, "Please specify a <i>channel</i> ID")
initName = self.me.first_name
iterList = []
if not "-save" in args:
_photos = []
entity = await self.client(GetFullChannelRequest(anotherChannel))
title = entity.chats[0].title
bio = entity.full_chat.about
photos = await self.client.get_profile_photos(anotherChannel)
if photos:
for photo in photos:
_photos.append(photo)
_photos = _photos[::-1]
await utils.answer(message, self.strings["start"])
try:
if "-save" in args:
await self.client(EditChatAboutRequest(yourChannel, bio))
await self.client(EditTitleRequest(yourChannel, title))
if _photos:
for _photo in _photos:
await self.client(EditPhotoRequest(yourChannel, _photo))
await self.client(ToggleSignaturesRequest(yourChannel, enabled=True))
except:
pass
async for i in self.client.iter_messages(anotherChannel, limit=limit):
await self.checkData(iterList, item=i)
iterList = iterList[::-1]
for i in iterList:
media = i["media"]
text = i["text"]
author = i["author"]
name = i["name"]
name_id = i["id"]
is_media = i["is_media"]
is_noneCaption = i["is_noneCaption"]
if not is_media and text == "§":
continue
if self.me.first_name != author:
await self.client(UpdateProfileRequest(first_name=author))
if is_media and media:
if is_noneCaption:
try:
await message.client.send_file(yourChannel, media)
except:
await message.client.send_message(yourChannel, "<i>Just a poll</i>")
try:
await message.client.send_message(
yourChannel,
f"↑ <b>forwarded from <a href='tg://user?id={name_id}'>{name}</a></b>" if name_id else f"<b>forwarded from {name}</b>" if name else ""
)
except:
pass
else:
await message.client.send_file(
yourChannel,
media,
caption="".join((
f"<b>forwarded from <a href='tg://user?id={name_id}'>{name}</a>:</b>\n\n" if name_id else f"forwarded from <b>{name}:</b>\n\n" if name else "",
text
))
)
await asyncio.sleep(self.config["Cooldown"])
else:
await message.client.send_message(
yourChannel,
"".join((
f"<b>forwarded from <a href='tg://user?id={name_id}'>{name}</a>:</b>\n\n" if name_id else f"<b>forwarded from {name}:</b>\n\n" if name else "",
text
))
)
await asyncio.sleep(self.config["Cooldown"])
await self.client(UpdateProfileRequest(first_name=initName))
await utils.answer(message, "<emoji document_id=5275990731813559483>😎</emoji> Done")

View File

@@ -0,0 +1,95 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Counter
# Description: Inline Clicks Counter
# Commands: count, creset
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 0, 1)
from .. import loader, utils
from telethon.tl.types import Message
from ..inline.types import InlineCall
import asyncio
@loader.tds
class Counter(loader.Module):
"""Inline Clicks Counter"""
strings = {
"name": "Counter",
"count": "Counter: {}"
}
async def client_ready(self):
counts = self.db.get(__name__, "c")
users = self.db.get(__name__, "u")
if not counts:
self.db.set(__name__, "c", 0)
if not users:
self.db.set(__name__, "u", [])
async def cresetcmd(self, message: Message):
""" [-u] [-c] - reset the counter\n-u (users list) -c (counts list)"""
args = (utils.get_args_raw(message)).split()
if all(i not in ["-u", "-c"] for i in args):
return await utils.answer(message, "<emoji document_id=5233657262106485430>🤨</emoji> Incorrect flag")
if "-u" in args:
self.db.set(__name__, "u", [])
if "-c" in args:
self.db.set(__name__, "c", 0)
await message.delete()
async def countcmd(self, message: Message):
""" Creates an inline button for counting a presses"""
counts = self.db.get(__name__, "c")
await self.inline.form(
text=self.strings["count"].format(counts),
message=message,
reply_markup=[
{
"text": "Click",
"callback": self.back
}
],
disable_security=True
)
async def back(self, call: InlineCall):
id = call.from_user.id
if id in self.db.get(__name__, "u"):
return
counts = self.db.get(__name__, "c")
counts += 1
self.db.set(__name__, "c", counts)
users = self.db.get(__name__, "u")
users.append(id)
self.db.set(__name__, "u", users)
await call.edit(
text=self.strings["count"].format(counts),
reply_markup=[
{
"text": "Click",
"callback": self.back
}
],
disable_security=True
)

View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,139 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Message Eraser
# Description: Delete your messages in the current chat
# Commands: purge, stoppurge
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 2, 3)
from .. import loader, utils
from telethon.tl.types import Message
import asyncio
import random
@loader.tds
class MessageEraser(loader.Module):
"""Delete your messages in the current chat"""
strings = {
"name": "MessageEraser",
"enabled": "<emoji document_id=5289755247298747469>😒</emoji> It's not operational now anyway",
"disabled": "<emoji document_id=5237870268541582966>❄️</emoji> Operation status changed to disabled",
"interrupted": "<emoji document_id=5233717529087581343>😀</emoji> The deletion was interrupted because you changed your mind",
"none": "<emoji document_id=5291954734410767857>👁️</emoji> You didn't even intend to delete anything here, but anyway it's disabled now"
}
async def client_ready(self):
status = self.db.get(__name__, "status", None)
if status is None:
self.db.set(__name__, "status", {})
async def stoppurgecmd(self, message: Message):
"""
Interrupt the deletion process
Use in the chat where you've previously started deletion
"""
chat_id = utils.get_chat_id(message)
status = self.db.get(__name__, "status", {})
_status = status.get(chat_id, None)
status[chat_id] = False
self.db.set(__name__, "status", status)
if _status is True:
await utils.answer(message, self.strings["disabled"])
elif _status is False:
await utils.answer(message, self.strings["enabled"])
else:
await utils.answer(message, self.strings["none"])
async def purgecmd(self, message: Message):
"""
[reply] [10s / 10m / 10h / 10d] [-all] - delete all your messages in the current chat or only ones up to the message you replied to
Possible to do with a delay
-all - to delete messages from each topic if this is a forum otherwise flag'll just be ignored
Example: 10h 3d
"""
args = (utils.get_args_raw(message)).split()
if "-all" in args:
is_each = True
args.remove("-all")
else:
is_each = False
reply = await message.get_reply_message()
chat_id = utils.get_chat_id(message)
delay = 0
is_last = False
is_forum = (await self.client.get_entity(chat_id)).forum
status = self.db.get(__name__, "status", {})
status[chat_id] = True
self.db.set(__name__, "status", status)
if args:
for i in args:
if len(i) < 2 or not i[:-1].isdigit():
continue
delay += (
{"d": 86400, "h": 3600, "m": 60, "s": 1}.get(i[-1], 0) * i[:-1]
)
await asyncio.sleep(delay)
batch = []
async for _message in self.client.iter_messages(chat_id):
status = self.db.get(__name__, "status", {})
if status.get(chat_id, None) is not True:
return await utils.answer(message, self.strings["interrupted"])
if _message.from_id != self.tg_id:
continue
if is_forum and not is_each and utils.get_topic(message) != utils.get_topic(_message):
continue
if len(batch) == 10:
await asyncio.sleep(self.getRandomDelay)
await message.client.delete_messages(chat_id, batch)
batch = []
if reply:
if is_last:
break
if _message.id == reply.id:
is_last = True
batch.append(_message.id)
if len(batch) != 0:
await message.client.delete_messages(chat_id, batch)
batch = []
await utils.answer(message, "<emoji document_id=5292186100004036291>🤩</emoji> Done")
def getRandomDelay(self):
"""A self-made function, creatively designed for generating a random float"""
rangeList = random.choice([(2.1, 3.9), (4.4, 6.7), (7.5, 9.1), (9.4, 10.4)])
randomRange = random.uniform(rangeList[0], rangeList[1])
randomSubRange = random.uniform(0.800, 1.399)
randomNum = randomRange * random.random() + (random.random() + 1.0) * randomSubRange
randomNum *= 3.8 if randomNum < 3 else 2.4 if randomNum < 5 else 1.3
return round(randomNum, 3)

View File

@@ -0,0 +1,54 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: PMStat
# Description: Defines how many messages did you and your chat partner write
# Commands: stat
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 0, 0)
from .. import loader, utils
from telethon.tl.types import Message
@loader.tds
class PMStat(loader.Module):
"""Defines how many messages did you and your chat partner write"""
strings = {
"name": "PMStat",
"q": "<emoji document_id=5444965061749644170>👨‍💻</emoji> All in all, {} messages were counted from <b>{}</b>",
"pm": "<emoji document_id=5233657262106485430>🤨</emoji> Use in PM only"
}
async def statcmd(self, message: Message):
""" [-p] [-s] - (-p - counts your chat partner messages) (-s - send result to the saved messages)"""
args = utils.get_args_raw(message)
if not message.is_private:
return await utils.answer(message, self.strings["pm"])
await message.delete()
chat = await self.client.get_entity(message.peer_id.user_id)
target = "you" if "-p" not in args else f"<a href='tg://user?id={chat.id}'>{chat.first_name}</a>"
s = chat.id if "-s" not in args else self.tg_id
count = 0
messagesList = []
async for i in self.client.iter_messages(chat.id):
if "-p" in args:
if i.from_id != self.tg_id:
messagesList.append(i)
else:
if i.from_id == self.tg_id:
messagesList.append(i)
await message.client.send_message(s, self.strings["q"].format(len(messagesList), target))

View File

@@ -0,0 +1,135 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Sticker stealer
# Description: Emoji / Sticker pickpocket
# Commands: steal
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 0, 1)
from .. import loader, utils
from telethon.tl.types import Message
import asyncio
@loader.tds
class StickerStealer(loader.Module):
"""Emoji / Sticker pickpocket"""
strings = {
"name": "StickerStealer",
"incorrect": "<emoji document_id=5233657262106485430>🤨</emoji> It's not a sticker or emoji"
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Emoji pack",
"emsaved",
lambda: "Specify a name of your emoji pack",
),
loader.ConfigValue(
"Animated sticker pack",
"vssaved",
lambda: "Specify a name of your animated sticker pack"
),
loader.ConfigValue(
"Static sticker pack",
"sssaved",
lambda: "Specify a name of your static sticker pack"
)
)
def checkType(self, reply, message):
if hasattr(reply, "media"):
if hasattr(reply.media, "document"):
mime_type = reply.media.document.mime_type.split('/')
if mime_type[1] == "webp":
return 3
elif mime_type[1] == "webm":
return 2
if reply.entities:
return 1
else:
return 0
async def stealcmd(self, message: Message):
""" <reply / quote reply> - add an emoji or sticker to your pack
Emoji: one type of emoji only is possible to be used at time"""
await utils.answer(message, "....")
reply = await message.get_reply_message()
bot = "Stickers"
cfg_ref = {
1: self.config["Emoji pack"],
2: self.config["Animated sticker pack"],
3: self.config["Static sticker pack"]
}
entity_type = {
1: "An emoji",
2: "A sticker",
3: "A sticker"
}
async with self.client.conversation(bot) as bot:
_entity_type = self.checkType(reply, message)
if _entity_type == 0:
return await utils.answer(message, self.strings["incorrect"])
elif _entity_type == 1:
outgoing = await bot.send_message("/addemoji")
else:
outgoing = await bot.send_message("/addsticker")
response = await bot.get_response()
await asyncio.sleep(2)
await outgoing.delete()
await response.delete()
if _entity_type == 1:
outgoing = await bot.send_message(self.config["emoji"])
elif _entity_type == 2:
outgoing = await bot.send_message(self.config["video_sticker"])
else:
outgoing = await bot.send_message(self.config["static_sticker"])
response = await bot.get_response()
await asyncio.sleep(2)
await response.delete()
await outgoing.delete()
if response.text == "Не выбран набор стикеров.":
return await utils.answer(message, f"Create {entity_type[_entity_type].lower()} pack with a public name <b>{cfg_ref[_entity_type]}</b>")
if _entity_type == 1:
emoji = reply.message
toSend = reply
else:
emoji = reply.media.document.attributes[1].alt
toSend = reply
outgoing = await bot.send_message(toSend)
response = await bot.get_response()
await asyncio.sleep(2)
await outgoing.delete()
await response.delete()
outgoing = await bot.send_message(emoji)
response = await bot.get_response()
await asyncio.sleep(2)
await outgoing.delete()
await response.delete()
await utils.answer(message, f"<b>{entity_type[_entity_type]} added</b>")

View File

@@ -0,0 +1,80 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Timer
# Description: Creates fine adorned timer
# Commands: timer
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 0, 0)
from .. import loader, utils
from telethon.tl.types import Message
import re
import asyncio
@loader.tds
class Timer(loader.Module):
"""Creates fine adorned timer"""
strings = {
"name": "Timer",
"q": "<b>Current Timer for {}</b>\n<emoji document_id=5303396278179210513>👾</emoji> {} <b>left</b>"
}
async def parseArgs(self, message, args, parsed):
for arg in args:
if arg[-1] not in ["h", "m", "s"]:
args.remove(arg)
for arg in args:
parsed[arg[-1]] = int(re.sub(r"[^0-9]", "", arg))
return parsed
async def timercmd(self, message: Message):
""" [5h 5m 5s] - launch the timer"""
args = (utils.get_args_raw(message)).split()
parsed = {"h": None, "m": None, "s": None}
if not args:
return await utils.answer(message, "Specify time")
_parsed = await self.parseArgs(message, args, parsed)
if all(_parsed[i] is None for i in parsed):
return await utils.answer(message, "<b>Time isn't specified</b>")
hours = _parsed["h"] * 3600 if _parsed["h"] else 0
mins = _parsed["m"] * 60 if _parsed["m"] else 0
secs = _parsed["s"] if _parsed["s"] else 0
_time = secs + mins + hours
c = f"{hours}:{mins}:{secs}"
pretime = "<i>{}:{}</i>"
while _time > -1:
h = f"{_time//3600}"
m = f"{_time%3600//60}"
s = f"{_time%3600%60}"
if _time > 59:
q = self.strings["q"].format(c, pretime.format(h, m))
else:
q = self.strings["q"].format(c, pretime.format(h, f"{m}:{s}"))
try:
await utils.answer(message, q)
except:
pass
_time -= 1
await asyncio.sleep(1)
regex = r"\..*\<.*?\>.*"
answer = re.sub(regex, "\n<emoji document_id=5222108309795908493>✨</emoji> <b>Time's over</b>", q.replace("\n", "."))
await utils.answer(message, answer)

View File

@@ -0,0 +1,284 @@
# ---------------------------------------------------------------------------------
# Author: @shiro_hikka
# Name: Tracker
# Description: Tracks the change history of usernames and nicknames of users
# Commands: track, addtrack, deltrack, trackstat
# ---------------------------------------------------------------------------------
# © Copyright 2025
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# scope: hikka_only
# meta developer: @shiro_hikka
# meta banner: https://0x0.st/s/FIR0RnhUN5pZV5CZ6sNFEw/8KBz.jpg
# ---------------------------------------------------------------------------------
__version__ = (1, 1, 0)
from .. import loader, utils
from telethon.tl.types import Message
from ..inline.types import InlineCall
import datetime
import time as t
import re
@loader.tds
class Tracker(loader.Module):
"""Tracks the change history of usernames and nicknames of users"""
strings = {
"name": "Tracker",
"enabled": "The tracker successfully enabled",
"disabled": "The tracker successfully disabled",
"no_user": "It seems this user doesn't exist, try another ID/Username",
"change_status": "You just changed a status of tracking the user",
"new_user": "You've successfully added a new user to track",
"no_stat": "You're currently tracking no user",
"only_one": "You're currently tracking only one user",
"removed": "You've removed this user from the track list and each ID was descendingly replaced",
"not_removed": "This user isn't added to the list so there's nobody to remove",
"exists": "This user's already included in the track list, he's ID is {}",
"cfg": "Specify a period of the cooldown between checks"
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Cooldown",
120,
lambda: self.strings["cfg"],
validator = loader.validators.Integer()
)
)
async def client_ready(self):
if not self.db.get(__name__, "status"):
self.db.set(__name__, "status", False)
if not self.db.get(__name__, "users"):
self.db.set(__name__, "users", {})
if not self.db.get(__name__, "time"):
self.db.set(__name__, "time", t.time())
async def trackcmd(self, message: Message):
""" Enable / Disable the tracking"""
status = not(self.db.get(__name__, "status"))
self.db.set(__name__, "status", status)
if status is True:
await utils.answer(message, self.strings["enabled"])
else:
await utils.answer(message, self.strings["disabled"])
async def addtrackcmd(self, message: Message):
""" <ID / Username> - add a new user to track"""
args = utils.get_args_raw(message)
users = self.db.get(__name__, "users")
ID = len(users) + 1
ID = str(ID)
try:
user = await self.client.get_entity(int(args) if args.isdigit() else args)
except Exception:
return await utils.answer(message, self.strings["no_user"])
for _user in users:
if users[_user]["user_id"] == user.id:
return await utils.answer(message, self.strings["exists"].format(_user))
UID = user.id
nick = f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
username = f"@{user.username}" if user.username else "<i>Empty</i>"
time = datetime.datetime.now()
date = str(time.date()).split('-')
hms = str(time.time()).split(':')
users[ID] = {
"nicks": [
"[{}.{}.{} - {}:{}:{}] {}".format(
date[2], date[1], date[0], hms[0], hms[1], hms[2].split('.')[0], nick
)
],
"unames": [
"[{}.{}.{} - {}:{}:{}] {}".format(
date[2], date[1], date[0], hms[0], hms[1], hms[2].split('.')[0], username
)
],
"active": True,
"user_id": UID
}
self.db.set(__name__, "users", users)
await utils.answer(message, self.strings["new_user"])
async def deltrackcmd(self, message: Message):
""" Remove user from the track list"""
args = utils.get_args_raw(message)
users = self.db.get(__name__, "users")
if not users:
return await utils.answer(message, self.strings["no_stat"]+"\nWho do you suppose to remove")
try:
user = await self.client.get_entity(int(args) if args.isdigit() else args)
except Exception:
return await utils.answer(message, self.strings["no_user"])
for _user in users:
if users[_user]["user_id"] == user.id:
ID = int(_user)
del users[_user]
for i in range(ID, len(users)+1):
if i == ID:
continue
users[str(i-1)] = users.pop(str(i))
self.db.set(__name__, "users", users)
return await utils.answer(message, self.strings["removed"])
await utils.answer(message, self.strings["not_removed"])
async def trackstatcmd(self, message: Message):
""" View the statistic about users you're tracking"""
users = self.db.get(__name__, "users")
if not users:
return await utils.answer(message, self.strings["no_stat"])
ID = "1"
user = await self.client.get_entity(users[ID]["user_id"])
status = "In progress" if users[ID]["active"] else "Inactive"
text = (
f"<b>ID:</b> <a href='tg://user?id={user.id}'>{user.id}</a>"+
"\n\n <b>Nicknames</b>\n"+
"\n".join(users[ID]["nicks"])+
"\n\n <b>Usernames</b>\n"+
"\n".join(users[ID]["unames"])
)
await self.inline.form(
text=text,
message=message,
reply_markup=[
[
{
"text": f"Tracking status: {status}",
"callback": lambda call: self.showStat(call, int(ID), "change_status")
}
],
[
{
"text": "Previous user",
"callback": lambda call: self.showStat(call, int(ID), "previous")
},
{
"text": "Next user",
"callback": lambda call: self.showStat(call, int(ID), "next")
}
]
]
)
async def showStat(self, call: InlineCall, ID, action) -> None:
users = self.db.get(__name__, "users")
if not users:
return await call.answer(self.strings["no_stat"])
user = await self.client.get_entity(users[str(ID)]["user_id"])
ID = ID + 1 if action == "next" else ID - 1 if action == "previous" else ID
if ID == 0:
ID = len(users)
elif ID > len(users):
ID = 1
ID = str(ID)
if action == "change_status":
users[ID]["active"] = not(users[ID]["active"])
await call.answer(self.strings["change_status"])
else:
if len(users) == 1:
return await call.answer(self.strings["only_one"])
status = "In progress" if users[ID]["active"] else "Inactive"
self.db.set(__name__, "users", users)
text = (
f"<b>ID:</b> <a href='tg://user?id={user.id}'>{user.id}</a>"+
"\n\n <b>Nicknames</b>\n"+
"\n".join(users[ID]["nicks"])+
"\n\n <b>Usernames</b>\n"+
"\n".join(users[ID]["unames"])
)
await call.edit(
text=text,
reply_markup=[
[
{
"text": f"Tracking status: {status}",
"callback": lambda call: self.showStat(call, int(ID), "change_status")
}
],
[
{
"text": "Previous user",
"callback": lambda call: self.showStat(call, int(ID), "previous")
},
{
"text": "Next user",
"callback": lambda call: self.showStat(call, int(ID), "next")
}
]
]
)
async def watcher(self, message: Message):
diff = t.time() - self.db.get(__name__, "time")
if diff < self.config["Cooldown"]:
return
users = self.db.get(__name__, "users")
if not users:
return
for user in users:
if users[user]["active"] is False:
continue
entity = await self.client.get_entity(users[user]["user_id"])
nick = f"{entity.first_name} {entity.last_name}" if entity.last_name else entity.first_name
username = f"@{entity.username}" if entity.username else "<i>Empty</i>"
time = datetime.datetime.now()
date = str(time.date()).split('-')
hms = str(time.time()).split(':')
if nick != re.sub(r"\[.*\]", "", users[user]["nicks"][-1]).strip():
users[user]["nicks"].append(
"[{}.{}.{} - {}:{}:{}] {}".format(
date[2], date[1], date[0], hms[0], hms[1], hms[2].split('.')[0], nick
)
)
if username != re.sub(r"\[.*\]", "", users[user]["unames"][-1]).strip():
users[user]["unames"].append(
"[{}.{}.{} - {}:{}:{}] {}".format(
date[2], date[1], date[0], hms[0], hms[1], hms[2].split(',')[0], username
)
)
self.db.set(__name__, "users", users)
self.db.set(__name__, "time", t.time())

View File

@@ -0,0 +1,8 @@
Autotime
Counter
PMStat
ChannelImitator
StickerStealer
Timer
MessageEraser
Tracker

454
AlpacaGang/ftg-modules/DND.py Executable file
View File

@@ -0,0 +1,454 @@
# -*- coding: future_fstrings -*-
# Friendly Telegram (telegram userbot)
# By Magical Unicorn (based on official Anti PM & AFK Friendly Telegram modules)
# Copyright (C) 2020 Magical Unicorn
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
import datetime
import time
from telethon import functions, types
logger = logging.getLogger(__name__)
def register(cb):
cb(DoNotDisturbMod())
@loader.tds
class DoNotDisturbMod(loader.Module):
"""
DND (Do Not Disturb) :
-> Prevents people sending you unsolicited private messages.
-> Prevents disturbing when you are unavailable.\n
Commands :
 
"""
strings = {"name": "DND",
"afk": "<b>I'm AFK right now (since</b> <i>{}</i> <b>ago).</b>",
"afk_back": "<b>I'm goin' BACK !</b>",
"afk_gone": "<b>I'm goin' AFK !</b>",
"afk_no_group_off": "<b>AFK status message enabled for group chats.</b>",
"afk_no_group_on": "<b>AFK status message disabled for group chats.</b>",
"afk_no_pm_off": "<b>AFK status message enabled for PMs.</b>",
"afk_no_pm_on": "<b>AFK status message disabled for PMs.</b>",
"afk_notif_off": "<b>Notifications are now disabled during AFK time.</b>",
"afk_notif_on": "<b>Notifications are now enabled during AFK time.</b>",
"afk_rate_limit_off": "<b>AFK status message rate limit disabled.</b>",
"afk_rate_limit_on": ("<b>AFK status message rate limit enabled.</b>"
"\n\n<b>One AFK status message max will be sent per chat.</b>"),
"afk_reason": ("<b>I'm AFK right now (since {} ago).</b>"
"\n\n<b>Reason :</b> <i>{}</i>"),
"arg_on_off": "<b>Argument must be 'off' or 'on' !</b>",
"pm_off": ("<b>Automatic answer for denied PMs disabled."
"\n\nUsers are now free to PM !</b>"),
"pm_on": "<b>An automatic answer is now sent for denied PMs.</b>",
"pm_allowed": "<b>I have allowed</b> <a href='tg://user?id={}'>you</a> <b>to PM now.</b>",
"pm_blocked": ("<b>I don't want any PM from</b> <a href='tg://user?id={}'>you</a>, "
"<b>so you have been blocked !</b>"),
"pm_denied": "<b>I have denied</b> <a href='tg://user?id={}'>you</a> <b>to PM now.</b>",
"pm_go_away": ("Hey there! Unfortunately, I don't accept private messages from strangers."
"\n\nPlease contact me in a group, or <b>wait</b> for me to approve you."),
"pm_reported": "<b>You just got reported to spam !</b>",
"pm_limit_arg": "<b>Argument must be 'off', 'on' or a number between 10 and 1000 !</b>",
"pm_limit_off": "<b>Not allowed users are now free to PM without be automatically blocked.</b>",
"pm_limit_on": "<b>Not allowed users are now blocked after {} PMs.</b>",
"pm_limit_current": "<b>Current limit is {}.</b>",
"pm_limit_current_no": "<b>Automatic user blocking is currently disabled.</b>",
"pm_limit_reset": "<b>Limit reseted to {}.</b>",
"pm_limit_set": "<b>Limit set to {}.</b>",
"pm_notif_off": "<b>Notifications from denied PMs are now disabled.</b>",
"pm_notif_on": "<b>Notifications from denied PMs are now enabled.</b>",
"pm_triggered": ("Hey! I don't appreciate you barging into my PM like this !"
"\nDid you even ask me for approving you to PM ? No ?"
"\nGoodbye then."
"\n\nPS: You've been reported as spam."),
"pm_unblocked": ("<b>Alright fine! I'll forgive them this time. PM has been unblocked for</b> "
"<a href='tg://user?id={}'>this user</a>."),
"unknow": ("An unknow problem as occured."
"\n\nPlease report problem with logs on "
"<a href='https://github.com/LegendaryUnicorn/FTG-Unofficial-Modules'>Github</a>."),
"who_to_allow": "<b>Who shall I allow to PM ?</b>",
"who_to_block": "<b>Specify who to block.</b>",
"who_to_deny": "<b>Who shall I deny to PM ?</b>",
"who_to_report": "<b>Who shall I report ?</b>",
"who_to_unblock": "<b>Specify who to unblock.</b>"}
def __init__(self):
self._me = None
self.default_pm_limit = 50
def config_complete(self):
self.name = self.strings["name"]
async def client_ready(self, client, db):
self._db = db
self._client = client
self._me = await client.get_me(True)
async def afkbackcmd(self, message):
"""Remove the AFK status.\n """
self._db.set(__name__, "afk", False)
self._db.set(__name__, "afk_gone", None)
self._db.set(__name__, "afk_rate", [])
await utils.answer(message, self.strings["afk_back"])
async def afkgocmd(self, message):
"""
.afkgo : Enable AFK status.
.afkgo [message] : Enable AFK status and add a reason.
 
"""
if utils.get_args_raw(message):
self._db.set(__name__, "afk", utils.get_args_raw(message))
else:
self._db.set(__name__, "afk", True)
self._db.set(__name__, "afk_gone", time.time())
self._db.set(__name__, "afk_rate", [])
await utils.answer(message, self.strings["afk_gone"])
async def afknogroupcmd(self, message):
"""
.afknogroup : Disable/Enable AFK status message for group chats.
.afknogroup off : Enable AFK status message for group chats.
.afknogroup on : Disable AFK status message for group chats.
 
"""
if utils.get_args_raw(message):
afknogroup_arg = utils.get_args_raw(message)
if afknogroup_arg == "off":
self._db.set(__name__, "afk_no_group", False)
await utils.answer(message, self.strings["afk_no_group_off"])
elif afknogroup_arg == "on":
self._db.set(__name__, "afk_no_group", True)
await utils.answer(message, self.strings["afk_no_group_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
afknogroup_current = self._db.get(__name__, "afk_no_group")
if afknogroup_current is None or afknogroup_current is False:
self._db.set(__name__, "afk_no_group", True)
await utils.answer(message, self.strings["afk_no_group_on"])
elif afknogroup_current is True:
self._db.set(__name__, "afk_no_group", False)
await utils.answer(message, self.strings["afk_no_group_off"])
else:
await utils.answer(message, self.strings["unknow"])
async def afknopmcmd(self, message):
"""
.afknopm : Disable/Enable AFK status message for PMs.
.afknopm off : Enable AFK status message for PMs.
.afknopm on : Disable AFK status message for PMs.
 
"""
if utils.get_args_raw(message):
afknopm_arg = utils.get_args_raw(message)
if afknopm_arg == "off":
self._db.set(__name__, "afk_no_pm", False)
await utils.answer(message, self.strings["afk_no_pm_off"])
elif afknopm_arg == "on":
self._db.set(__name__, "afk_no_pm", True)
await utils.answer(message, self.strings["afk_no_pm_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
afknopm_current = self._db.get(__name__, "afk_no_pm")
if afknopm_current is None or afknopm_current is False:
self._db.set(__name__, "afk_no_pm", True)
await utils.answer(message, self.strings["afk_no_pm_on"])
elif afknopm_current is True:
self._db.set(__name__, "afk_no_pm", False)
await utils.answer(message, self.strings["afk_no_pm_off"])
else:
await utils.answer(message, self.strings["unknow"])
async def afknotifcmd(self, message):
"""
.afknotif : Disable/Enable the notifications during AFK time.
.afknotif off : Disable the notifications during AFK time.
.afknotif on : Enable the notifications during AFK time.
 
"""
if utils.get_args_raw(message):
afknotif_arg = utils.get_args_raw(message)
if afknotif_arg == "off":
self._db.set(__name__, "afk_notif", False)
await utils.answer(message, self.strings["afk_notif_off"])
elif afknotif_arg == "on":
self._db.set(__name__, "afk_notif", True)
await utils.answer(message, self.strings["afk_notif_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
afknotif_current = self._db.get(__name__, "afk_notif")
if afknotif_current is None or afknotif_current is False:
self._db.set(__name__, "afk_notif", True)
await utils.answer(message, self.strings["afk_notif_on"])
elif afknotif_current is True:
self._db.set(__name__, "afk_notif", False)
await utils.answer(message, self.strings["afk_notif_off"])
else:
await utils.answer(message, self.strings["unknow"])
async def afkratecmd(self, message):
"""
.afkrate : Disable/Enable AFK rate limit.
.afkrate off : Disable AFK rate limit.
.afkrate on : Enable AFK rate limit. One AFK status message max will be sent per chat.
 
"""
if utils.get_args_raw(message):
afkrate_arg = utils.get_args_raw(message)
if afkrate_arg == "off":
self._db.set(__name__, "afk_rate_limit", False)
await utils.answer(message, self.strings["afk_rate_limit_off"])
elif afkrate_arg == "on":
self._db.set(__name__, "afk_rate_limit", True)
await utils.answer(message, self.strings["afk_rate_limit_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
afkrate_current = self._db.get(__name__, "afk_rate_limit")
if afkrate_current is None or afkrate_current is False:
self._db.set(__name__, "afk_rate_limit", True)
await utils.answer(message, self.strings["afk_rate_limit_on"])
elif afkrate_current is True:
self._db.set(__name__, "afk_rate_limit", False)
await utils.answer(message, self.strings["afk_rate_limit_off"])
else:
await utils.answer(message, self.strings["unknow"])
async def allowcmd(self, message):
"""Allow this user to PM.\n """
user = await utils.get_target(message)
if not user:
await utils.answer(message, self.strings["who_to_allow"])
return
self._db.set(__name__, "allow", list(set(self._db.get(__name__, "allow", [])).union({user})))
await utils.answer(message, self.strings["pm_allowed"].format(user))
async def blockcmd(self, message):
"""Block this user to PM without being warned.\n """
user = await utils.get_target(message)
if not user:
await utils.answer(message, self.strings["who_to_block"])
return
await message.client(functions.contacts.BlockRequest(user))
await utils.answer(message, self.strings["pm_blocked"].format(user))
async def denycmd(self, message):
"""Deny this user to PM without being warned.\n """
user = await utils.get_target(message)
if not user:
await utils.answer(message, self.strings["who_to_deny"])
return
self._db.set(__name__, "allow", list(set(self._db.get(__name__, "allow", [])).difference({user})))
await utils.answer(message, self.strings["pm_denied"].format(user))
async def pmcmd(self, message):
"""
.pm : Disable/Enable automatic answer for denied PMs.
.pm off : Disable automatic answer for denied PMs.
.pm on : Enable automatic answer for denied PMs.
 
"""
if utils.get_args_raw(message):
pm_arg = utils.get_args_raw(message)
if pm_arg == "off":
self._db.set(__name__, "pm", True)
await utils.answer(message, self.strings["pm_off"])
elif pm_arg == "on":
self._db.set(__name__, "pm", False)
await utils.answer(message, self.strings["pm_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
pm_current = self._db.get(__name__, "pm")
if pm_current is None or pm_current is False:
self._db.set(__name__, "pm", True)
await utils.answer(message, self.strings["pm_off"])
elif pm_current is True:
self._db.set(__name__, "pm", False)
await utils.answer(message, self.strings["pm_on"])
else:
await utils.answer(message, self.strings["unknow"])
async def pmlimitcmd(self, message):
"""
.pmlimit : Get current max number of PMs before automatically block not allowed user.
.pmlimit off : Disable automatic user blocking.
.pmlimit on : Enable automatic user blocking.
.pmlimit reset : Reset max number of PMs before automatically block not allowed user.
.pmlimit [number] : Modify max number of PMs before automatically block not allowed user.
 
"""
if utils.get_args_raw(message):
pmlimit_arg = utils.get_args_raw(message)
if pmlimit_arg == "off":
self._db.set(__name__, "pm_limit", False)
await utils.answer(message, self.strings["pm_limit_off"])
return
elif pmlimit_arg == "on":
self._db.set(__name__, "pm_limit", True)
pmlimit_on = self.strings["pm_limit_on"].format(self.get_current_limit())
await utils.answer(message, pmlimit_on)
return
elif pmlimit_arg == "reset":
self._db.set(__name__, "pm_limit_max", self.default_pm_limit)
pmlimit_reset = self.strings["pm_limit_reset"].format(self.get_current_pm_limit())
await utils.answer(message, pmlimit_reset)
return
else:
try:
pmlimit_number = int(pmlimit_arg)
if pmlimit_number >= 10 and pmlimit_number <= 1000:
self._db.set(__name__, "pm_limit_max", pmlimit_number)
pmlimit_new = self.strings["pm_limit_set"].format(self.get_current_pm_limit())
await utils.answer(message, pmlimit_new)
return
else:
await utils.answer(message, self.strings["pm_limit_arg"])
return
except ValueError:
await utils.answer(message, self.strings["pm_limit_arg"])
return
await utils.answer(message, self.strings["limit_arg"])
else:
pmlimit = self._db.get(__name__, "pm_limit")
if pmlimit is None or pmlimit is False:
pmlimit_current = self.strings["pm_limit_current_no"]
elif pmlimit is True:
pmlimit_current = self.strings["pm_limit_current"].format(self.get_current_pm_limit())
else:
await utils.answer(message, self.strings["unknow"])
return
await utils.answer(message, pmlimit_current)
async def pmnotifcmd(self, message):
"""
.pmnotif : Disable/Enable the notifications from denied PMs.
.pmnotif off : Disable the notifications from denied PMs.
.pmnotif on : Enable the notifications from denied PMs.
 
"""
if utils.get_args_raw(message):
pmnotif_arg = utils.get_args_raw(message)
if pmnotif_arg == "off":
self._db.set(__name__, "pm_notif", False)
await utils.answer(message, self.strings["pm_notif_off"])
elif pmnotif_arg == "on":
self._db.set(__name__, "pm_notif", True)
await utils.answer(message, self.strings["pm_notif_on"])
else:
await utils.answer(message, self.strings["arg_on_off"])
else:
pmnotif_current = self._db.get(__name__, "pm_notif")
if pmnotif_current is None or pmnotif_current is False:
self._db.set(__name__, "pm_notif", True)
await utils.answer(message, self.strings["pm_notif_on"])
elif pmnotif_current is True:
self._db.set(__name__, "pm_notif", False)
await utils.answer(message, self.strings["pm_notif_off"])
else:
await utils.answer(message, self.strings["unknow"])
async def reportcmd(self, message):
"""Report the user to spam. Use only in PM.\n """
user = await utils.get_target(message)
if not user:
await utils.answer(message, self.strings["who_to_report"])
return
self._db.set(__name__, "allow", list(set(self._db.get(__name__, "allow", [])).difference({user})))
if message.is_reply and isinstance(message.to_id, types.PeerChannel):
await message.client(functions.messages.ReportRequest(peer=message.chat_id,
id=[message.reply_to_msg_id],
reason=types.InputReportReasonSpam()))
else:
await message.client(functions.messages.ReportSpamRequest(peer=message.to_id))
await utils.answer(message, self.strings["pm_reported"])
async def unblockcmd(self, message):
"""Unblock this user to PM."""
user = await utils.get_target(message)
if not user:
await utils.answer(message, self.strings["who_to_unblock"])
return
await message.client(functions.contacts.UnblockRequest(user))
await utils.answer(message, self.strings["pm_unblocked"].format(user))
async def watcher(self, message):
user = await utils.get_user(message)
pm = self._db.get(__name__, "pm")
if getattr(message.to_id, "user_id", None) == self._me.user_id and (pm is None or pm is False):
if not user.is_self and not user.bot and not user.verified and not self.get_allowed(message.from_id):
await utils.answer(message, self.strings["pm_go_away"])
if self._db.get(__name__, "pm_limit") is True:
pms = self._db.get(__name__, "pms", {})
pm_limit = self._db.get(__name__, "pm_limit_max")
pm_user = pms.get(message.from_id, 0)
if isinstance(pm_limit, int) and pm_limit >= 10 and pm_limit <= 1000 and pm_user >= pm_limit:
await utils.answer(message, self.strings["pm_triggered"])
await message.client(functions.contacts.BlockRequest(message.from_id))
await message.client(functions.messages.ReportSpamRequest(peer=message.from_id))
del pms[message.from_id]
self._db.set(__name__, "pms", pms)
else:
self._db.set(__name__, "pms", {**pms, message.from_id: pms.get(message.from_id, 0) + 1})
pm_notif = self._db.get(__name__, "pm_notif")
if pm_notif is None or pm_notif is False:
await message.client.send_read_acknowledge(message.chat_id)
return
if message.mentioned or getattr(message.to_id, "user_id", None) == self._me.user_id:
afk_status = self._db.get(__name__, "afk")
if user.is_self or user.bot or user.verified or afk_status is False:
return
if message.mentioned and self._db.get(__name__, "afk_no_group") is True:
return
afk_no_pm = self._db.get(__name__, "afk_no_pm")
if getattr(message.to_id, "user_id", None) == self._me.user_id and afk_no_pm is True:
return
if self._db.get(__name__, "afk_rate_limit") is True:
afk_rate = self._db.get(__name__, "afk_rate", [])
if utils.get_chat_id(message) in afk_rate:
return
else:
self._db.setdefault(__name__, {}).setdefault("afk_rate", []).append(utils.get_chat_id(message))
self._db.save()
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(self._db.get(__name__, "afk_gone")).replace(microsecond=0)
diff = now - gone
if afk_status is True:
afk_message = self.strings["afk"].format(diff)
elif afk_status is not False:
afk_message = self.strings["afk_reason"].format(diff, afk_status)
await utils.answer(message, afk_message)
_notif = self._db.get(__name__, "_notif")
if _notif is None or _notif is False:
await message.client.send_read_acknowledge(message.chat_id)
def get_allowed(self, id):
return id in self._db.get(__name__, "allow", [])
def get_current_pm_limit(self):
pm_limit = self._db.get(__name__, "pm_limit_max")
if not isinstance(pm_limit, int) or pm_limit < 10 or pm_limit > 1000:
pm_limit = self.default_pm_limit
self._db.set(__name__, "pm_limit_max", pm_limit)
return pm_limit

125
AlpacaGang/ftg-modules/Tag.py Executable file
View File

@@ -0,0 +1,125 @@
# -*- coding: future_fstrings -*-
# Friendly Telegram (telegram userbot)
# By Magical Unicorn (based on official Anti PM & AFK Friendly Telegram modules)
# Copyright (C) 2020 Magical Unicorn
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
from telethon import functions, types
from telethon.tl.types import PeerUser, PeerChat, PeerChannel, ChannelParticipantsAdmins
logger = logging.getLogger(__name__)
def register(cb):
cb(TagMod())
@loader.tds
class TagMod(loader.Module):
"""
Tag :
-> Tag all admins (fast way to report).
-> Tag all bots (why not ?).
-> Tag all members (why not ?).\n
Commands :
 
"""
strings = {"name": "Tag",
"error_chat": "<b>This command can be used in channels and group chats only.</b>",
"unknow": ("An unknow problem as occured."
"\n\nPlease report problem with logs on "
"<a href='https://github.com/LegendaryUnicorn/FTG-Unofficial-Modules'>Github</a>."),
"user_link": "\n• <a href='tg://user?id={}'>{}</a>"}
def config_complete(self):
self.name = self.strings["name"]
async def admincmd(self, message):
"""
.admin : Tag all admins (excepted bots).
.admin [message] : Tag all admins (excepted bots) with message before tags.
 
"""
if isinstance(message.to_id, PeerUser):
await utils.answer(message, self.strings["error_chat"])
return
if utils.get_args_raw(message):
rep = utils.get_args_raw(message)
else:
rep = ""
user = await utils.get_target(message)
if isinstance(message.to_id, PeerChat) or isinstance(message.to_id, PeerChannel):
async for user in message.client.iter_participants(message.to_id, filter=ChannelParticipantsAdmins):
if not user.bot:
user_name = user.first_name
if user.last_name is not None:
user_name += " " + user.last_name
rep += self.strings["user_link"].format(user.id, user_name)
await utils.answer(message, rep)
else:
await utils.answer(message, self.strings["unknow"])
async def allcmd(self, message):
"""
.all : Tag all members.
.all [message] : Tag all members with message before tags.
 
"""
if isinstance(message.to_id, PeerUser):
await utils.answer(message, self.strings["error_chat"])
return
if utils.get_args_raw(message):
rep = utils.get_args_raw(message)
else:
rep = ""
user = await utils.get_target(message)
if isinstance(message.to_id, PeerChat) or isinstance(message.to_id, PeerChannel):
async for user in message.client.iter_participants(message.to_id):
user_name = user.first_name
if user.last_name is not None:
user_name += " " + user.last_name
rep += self.strings["user_link"].format(user.id, user_name)
await utils.answer(message, rep)
else:
await utils.answer(message, self.strings["unknow"])
async def botcmd(self, message):
"""
.bot : Tag all bots.
.bot [message] : Tag all bots with message before tags.
 
"""
if isinstance(message.to_id, PeerUser):
await utils.answer(message, self.strings["error_chat"])
return
if utils.get_args_raw(message):
rep = utils.get_args_raw(message)
else:
rep = ""
user = await utils.get_target(message)
if isinstance(message.to_id, PeerChat) or isinstance(message.to_id, PeerChannel):
async for user in message.client.iter_participants(message.to_id):
if user.bot:
user_name = user.first_name
if user.last_name is not None:
user_name += " " + user.last_name
rep += self.strings["user_link"].format(user.id, user_name)
await utils.answer(message, rep)
else:
await utils.answer(message, self.strings["unknow"])

View File

@@ -0,0 +1,42 @@
from .. import loader, utils
import logging
import datetime
import time
import asyncio
logger = logging.getLogger(__name__)
def register(cb):
cb(CONTACTMod())
@loader.tds
class CONTACTMod(loader.Module):
"""Это модуль для игры в \"контакт\""""
strings = {"name": "contact"}
def __init__(self):
self.name = self.strings["name"]
def config_complete(self):
pass
async def contactcmd(self, message):
"""Эта команда пишет 10 сообщений для контакта"""
try:
await message.delete()
x = 10
lst = str(x)
await message.respond(lst)
dd = time.time()
while time.time() - dd < x:
now = str(x - round(time.time() - dd))
if now != lst:
await message.respond(now)
lst = now
except:
await message.respond("Упс, ошибочка вышла! Напшите @gerasikoff, он вам поможет")

View File

@@ -0,0 +1,95 @@
import requests as rq
from urllib.parse import quote_plus as escape
import re
from .. import loader, utils
import asyncio
import logging
logger = logging.getLogger(__name__)
# simplified cuttly api
class CuttlyApi:
def __init__(self, token, api_url='https://cutt.ly/api/api.php'):
self.token = token
self.api_url = api_url
self.error_codes = {
1: 'Link is already shortened',
2: 'Link to short is not a link',
3: 'Short link https://cutt.ly/{name} is taken',
4: 'Invalid API key',
5: 'Link preferred alias contains invalid characters',
6: 'Link is from blocked domain'
}
self.ok_code = 7
def shorten(self, short: str, name: str=None) -> dict:
if not re.fullmatch(r'\w+://.+', short): # add scheme if needed
short = 'http://' + short # assume that it supports http
res = rq.get(self.api_url, params={
"key": self.token,
"short": escape(short, ':/%._-'),
"name": name
})
res = res.json()['url']
return res
@loader.tds
class CuttlyMod(loader.Module):
"""URL shortener module"""
# make errors translatable
strings = {
"name": "Cutt.ly",
"error_1": "<b>Link is already shortened</b>",
"error_2": "<b>It is not a link</b>",
"error_3": "<b>Short link https://cutt.ly/{name} is taken</b>",
"error_4": "<b>Invalid API key. Change it in config.</b>",
"error_5": "<b>Link preferred alias contains invalid characters</b>",
"error_6": "<b>Link is from blocked domain</b>",
"unknown_error": "<b>Unknown error {}. Check https://cutt.ly/cuttly-api for information.</b>",
"ok": "<b>Shorted!</b>\nShort link: {short}\nFull link: {full}",
"ok_nofull": "<b>Shorted!</b>\nShort link: {short}",
"no_args": "<b>At least 1 argument needed - the link you gonna to short</b>",
"many_args": "<b>At most 2 arguments - the link you gonna to short and preferred alias for it."
}
def __init__(self):
self.config = loader.ModuleConfig(
# name - default - description
"cuttly_api_url", "https://cutt.ly/api/api.php", "Cuttly API URL, took from https://cutt.ly/cuttly-api",
"api_key", None, "API key for cutt.ly. Register there and take one.",
"include_full_link", True, "Shall bot include full link into answer."
)
def config_complete(self):
self.name = self.strings['name']
self.cl = CuttlyApi(self.config['api_key'], self.config['cuttly_api_url'])
async def shortcmd(self, message):
'''usage: .short <link_to_short> [preferred_alias]'''
args = utils.get_args(message)
if len(args) < 1:
await utils.answer(message, self.strings['no_args'])
return
elif len(args) > 2:
await utils.answer(message, self.strings['many_args'])
return
if len(args) == 1:
args.append(None)
res = self.cl.shorten(*args)
logger.debug(f'Got response from cutt.ly: {res}')
if res['status'] != self.cl.ok_code:
try:
msg = self.strings[f'error_{res["status"]}']
except KeyError: # Unknown error, not in strings yet
msg = self.strings['unknown_error'].format(res['status'])
else:
if self.config['include_full_link']:
msg = self.strings['ok']
else:
msg = self.strings['ok_nofull']
await utils.answer(message, msg.format(
short = res.get('shortLink', None), # If we got an error
full = res.get('fullLink', None),
name = args[1]
))

View File

@@ -0,0 +1,131 @@
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing commands for interacting with dogbin(https://del.dog)"""
from requests import get, post, exceptions
import asyncio
import os
from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP, LOGS, TEMP_DOWNLOAD_DIRECTORY
from userbot.events import register
DOGBIN_URL = "https://dogbin.f0x1d.com/"
@register(outgoing=True, pattern=r"^.paste(?: |$)([\s\S]*)")
async def paste(pstl):
""" For .paste command, pastes the text directly to dogbin. """
dogbin_final_url = ""
match = pstl.pattern_match.group(1).strip()
reply_id = pstl.reply_to_msg_id
if not match and not reply_id:
await pstl.edit("`Elon Musk said I cannot paste void.`")
return
if match:
message = match
elif reply_id:
message = (await pstl.get_reply_message())
if message.media:
downloaded_file_name = await pstl.client.download_media(
message,
TEMP_DOWNLOAD_DIRECTORY,
)
m_list = None
with open(downloaded_file_name, "rb") as fd:
m_list = fd.readlines()
message = ""
for m in m_list:
message += m.decode("UTF-8") + "\r"
os.remove(downloaded_file_name)
else:
message = message.message
# Dogbin
await pstl.edit("`Pasting text . . .`")
resp = post(DOGBIN_URL + "documents", data=message.encode('utf-8'))
if resp.status_code == 200:
response = resp.json()
key = response['key']
dogbin_final_url = DOGBIN_URL + key
if response['isUrl']:
reply_text = ("`Pasted successfully!`\n\n"
f"`Shortened URL:` {dogbin_final_url}\n\n"
"`Original(non-shortened) URLs`\n"
f"`Dogbin URL`: {DOGBIN_URL}v/{key}\n")
else:
reply_text = ("`Pasted successfully!`\n\n"
f"`Dogbin URL`: {dogbin_final_url}")
else:
reply_text = ("`Failed to reach Dogbin`")
await pstl.edit(reply_text)
if BOTLOG:
await pstl.client.send_message(
BOTLOG_CHATID,
f"Paste query was executed successfully",
)
@register(outgoing=True, pattern="^.getpaste(?: |$)(.*)")
async def get_dogbin_content(dog_url):
""" For .getpaste command, fetches the content of a dogbin URL. """
textx = await dog_url.get_reply_message()
message = dog_url.pattern_match.group(1)
await dog_url.edit("`Getting dogbin content...`")
if textx:
message = str(textx.message)
format_normal = f'{DOGBIN_URL}'
format_view = f'{DOGBIN_URL}v/'
if message.startswith(format_view):
message = message[len(format_view):]
elif message.startswith(format_normal):
message = message[len(format_normal):]
elif message.startswith("del.dog/"):
message = message[len("del.dog/"):]
else:
await dog_url.edit("`Is that even a dogbin url?`")
return
resp = get(f'{DOGBIN_URL}raw/{message}')
try:
resp.raise_for_status()
except exceptions.HTTPError as HTTPErr:
await dog_url.edit(
"Request returned an unsuccessful status code.\n\n" + str(HTTPErr))
return
except exceptions.Timeout as TimeoutErr:
await dog_url.edit("Request timed out." + str(TimeoutErr))
return
except exceptions.TooManyRedirects as RedirectsErr:
await dog_url.edit(
"Request exceeded the configured number of maximum redirections." +
str(RedirectsErr))
return
reply_text = "`Fetched dogbin URL content successfully!`\n\n`Content:` " + resp.text
await dog_url.edit(reply_text)
if BOTLOG:
await dog_url.client.send_message(
BOTLOG_CHATID,
"Get dogbin content query was executed successfully",
)
CMD_HELP.update({
"dogbin":
".paste <text/reply>\
\nUsage: Create a paste or a shortened url using dogbin (https://dogbin.f0x1d.com/)\
\n\n.getpaste\
\nUsage: Gets the content of a paste or shortened url from dogbin (https://dogbin.f0x1d.com/)"
})

View File

@@ -0,0 +1,143 @@
import logging
import json
# import telethon
from .. import loader, utils, security
logger = logging.getLogger(__name__)
@loader.tds
class InactiveDetectorMod(loader.Module):
"""Detects inactive users"""
strings = {
"name": "Inactivity detector",
"top_header": "These {un} users wrote {mn} messages or less since joining the group:\n\n",
"top_place": "[{name}](tg://user?id={uid}) ({nmsg})", # FIXME: mentions
"top_delimiter": ", ", # TODO: move to config
"not_int": "<b>Most messages must be integer</b>",
"recount_priv": "<b>I can't recount stats in private messages!</b>",
"recount_started": "<b>Processing recount for chat {}. It may take a lot.</b>",
"recount_db_dumped": "<b>Dumped database to owners and/or saved messages</b>",
"recount_dump": "<b>Database dump for chat {cid}:<b>\n\n<pre>{dmp}</pre>",
"recount_iter_done": "<b>Iterated over {} messages in this chat</b>",
"recount_finish": "<b>Recount successful!</b>"
}
def __init__(self):
self.config = loader.ModuleConfig(
"default_chat_id", -1001457369532, "Chat ID to get top if command used in PM",
"top_delimiter", ', ', "Separates inactivity top members",
"dump_db_before_recount", False, "Dump database of chat before recounting. "
"Dump will be sent to saved or bot owners"
)
self.name = self.strings['name']
async def client_ready(self, client, db):
self.client = client
self.db = db
self.me = await self.client.get_me()
async def inactivecmd(self, message):
""".inactive <N>"""
if message.is_private:
chat_id = self.config['default_chat_id']
else:
chat_id = message.chat_id
args = utils.get_args(message)
if args:
if args[0].isdigit():
most = int(args[0])
else:
await utils.answer(message, self.strings("not_int", message))
return
else:
most = 0
users_db = self.db.get(__name__, str(chat_id), {})
users = {}
async for user in self.client.iter_participants(chat_id):
if not user.bot:
if str(user.id) not in users_db:
users_db[str(user.id)] = self.get_empty_user(user)
users[str(user.id)] = users_db[str(user.id)]
# We won't include users not CURRENTLY in chat,
# but their stats will remain in the database
self.db.set(__name__, str(chat_id), users_db)
def key(x):
return x[1]['cnt']
users = sorted(users.items(), key=key)
text = []
for uid, u in users:
if u['cnt'] <= most:
text.append(self.strings('top_place', message).format(
name=u['name'], uid=uid, nmsg=u['cnt']
))
else:
break
msg = self.strings('top_header', message).format(un=len(text), mn=most)\
+ self.config['top_delimiter'].join(text)
kw = {}
if self.me.id != message.from_id:
kw['silent'] = True
await utils.answer(message, msg, parse_mode="md", **kw)
async def recountcmd(self, message):
if message.is_private:
await utils.answer(message, self.strings('recount_priv', message))
return
chat_id = message.chat_id
await utils.answer(message, self.strings('recount_started', message).format(chat_id))
db = self.db.get(__name__, str(chat_id), {})
json_db = json.dumps(db)
msg = self.strings("recount_dump", message).format(cid=chat_id, dmp=json_db)
logging.debug('Database dump (chat %d): %s', chat_id, json_db)
owners = self.db.get(security.__name__, "owner", ["me"])
if owners:
for owner in owners:
try:
await self.client.send_message(owner, msg)
except Exception:
logger.warning("Dump of chat %d sending to %d failed",
chat_id, owner, exc_info=True)
new_db = {}
n = 0
async for msg in self.client.iter_messages(chat_id, limit=None):
if not msg.sender.bot:
n += 1
from_id = msg.from_id
# Ensure such user exists, or create him
new_db[str(from_id)] = new_db.get(str(from_id),
self.get_empty_user(msg.sender))
new_db[str(from_id)]['cnt'] += 1
await utils.answer(message, self.strings("recount_iter_done", message).format(n))
self.db.set(__name__, str(chat_id), new_db)
await utils.answer(message, self.strings("recount_finish", message))
async def watcher(self, message):
if message.is_private:
return
else:
chat_id = str(message.chat_id)
users = self.db.get(__name__, chat_id, {})
from_id = str(message.from_id)
# this creates user if not exists
if message.sender:
users[from_id] = users.get(from_id, self.get_empty_user(message.sender))
users[from_id]["cnt"] += 1
self.db.set(__name__, chat_id, users)
def get_full_name(self, user):
fn, ln = '', ''
if user.first_name:
fn = user.first_name
if user.last_name: # Can be None, then we get an exception
ln = user.last_name
return (fn + ' ' + ln).strip()
def get_empty_user(self, user):
return {"cnt": 0, "name": self.get_full_name(user)}

View File

@@ -0,0 +1,154 @@
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for purging unneeded messages(usually spam or ot). """
from asyncio import sleep
from telethon.errors import rpcbaseerrors
from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
from userbot.events import register
@register(outgoing=True, pattern="^.purge$")
async def fastpurger(purg):
""" For .purge command, purge all messages starting from the reply. """
chat = await purg.get_input_chat()
msgs = []
itermsg = purg.client.iter_messages(chat, min_id=purg.reply_to_msg_id)
count = 0
if purg.reply_to_msg_id is not None:
async for msg in itermsg:
msgs.append(msg)
count = count + 1
msgs.append(purg.reply_to_msg_id)
if len(msgs) == 100:
await purg.client.delete_messages(chat, msgs)
msgs = []
else:
await purg.edit("`I need a mesasge to start purging from.`")
return
if msgs:
await purg.client.delete_messages(chat, msgs)
done = await purg.client.send_message(
purg.chat_id, f"`Fast purge complete!`\
\nPurged {str(count)} messages")
if BOTLOG:
await purg.client.send_message(
BOTLOG_CHATID,
"Purge of " + str(count) + " messages done successfully.")
await sleep(2)
await done.delete()
@register(outgoing=True, pattern="^.purgeme")
async def purgeme(delme):
""" For .purgeme, delete x count of your latest message."""
message = delme.text
count = int(message[9:])
i = 1
async for message in delme.client.iter_messages(delme.chat_id,
from_user='me'):
if i > count + 1:
break
i = i + 1
await message.delete()
smsg = await delme.client.send_message(
delme.chat_id,
"`Purge complete!` Purged " + str(count) + " messages.",
)
if BOTLOG:
await delme.client.send_message(
BOTLOG_CHATID,
"Purge of " + str(count) + " messages done successfully.")
await sleep(2)
i = 1
await smsg.delete()
@register(outgoing=True, pattern="^.del$")
async def delete_it(delme):
""" For .del command, delete the replied message. """
msg_src = await delme.get_reply_message()
if delme.reply_to_msg_id:
try:
await msg_src.delete()
await delme.delete()
if BOTLOG:
await delme.client.send_message(
BOTLOG_CHATID, "Deletion of message was successful")
except rpcbaseerrors.BadRequestError:
if BOTLOG:
await delme.client.send_message(
BOTLOG_CHATID, "Well, I can't delete a message")
@register(outgoing=True, pattern="^.edit")
async def editer(edit):
""" For .editme command, edit your last message. """
message = edit.text
chat = await edit.get_input_chat()
self_id = await edit.client.get_peer_id('me')
string = str(message[6:])
i = 1
async for message in edit.client.iter_messages(chat, self_id):
if i == 2:
await message.edit(string)
await edit.delete()
break
i = i + 1
if BOTLOG:
await edit.client.send_message(BOTLOG_CHATID,
"Edit query was executed successfully")
@register(outgoing=True, pattern="^.sd")
async def selfdestruct(destroy):
""" For .sd command, make seflf-destructable messages. """
message = destroy.text
counter = int(message[4:6])
text = str(destroy.text[6:])
await destroy.delete()
smsg = await destroy.client.send_message(destroy.chat_id, text)
await sleep(counter)
await smsg.delete()
if BOTLOG:
await destroy.client.send_message(BOTLOG_CHATID,
"sd query done successfully")
CMD_HELP.update({
'purge':
'.purge\
\nUsage: Purges all messages starting from the reply.'
})
CMD_HELP.update({
'purgeme':
'.purgeme <x>\
\nUsage: Deletes x amount of your latest messages.'
})
CMD_HELP.update({"del": ".del\
\nUsage: Deletes the message you replied to."})
CMD_HELP.update({
'edit':
".edit <newmessage>\
\nUsage: Replace your last message with <newmessage>."
})
CMD_HELP.update({
'sd':
'.sd <x> <message>\
\nUsage: Creates a message that selfdestructs in x seconds.\
\nKeep the seconds under 100 since it puts your bot to sleep.'
})

View File

@@ -0,0 +1,298 @@
# -*- coding: future_fstrings -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import requests
import base64
import json
import telethon
from .. import loader, utils
from PIL import Image
from io import BytesIO
logger = logging.getLogger(__name__)
def register(cb):
cb(QuotesMod())
@loader.tds
class QuotesMod(loader.Module):
"""Quote a message."""
strings = {
"name": "Quotes",
"api_token_cfg_doc": "API Key/Token for Quotes.",
"api_url_cfg_doc": "API URL for Quotes.",
"colors_cfg_doc": "Username colors",
"default_username_color_cfg_doc": "Default color for the username.",
"no_reply": "<b>You didn't reply to a message.</b>",
"no_template": "<b>You didn't specify the template.</b>",
"delimiter": "</code>, <code>",
"server_error": "<b>Server error. Please report to developer.</b>",
"invalid_token": "<b>You've set an invalid token.</b>",
"unauthorized": "<b>You're unauthorized to do this.</b>",
"not_enough_permissions": "<b>Wrong template. You can use only the default one.</b>",
"templates": "<b>Available Templates:</b> <code>{}</code>",
"cannot_send_stickers": "<b>You cannot send stickers in this chat.</b>",
"admin": "admin",
"creator": "creator",
"hidden": "hidden",
"channel": "Channel",
"filename": "file.png"
}
def __init__(self):
self.config = loader.ModuleConfig("api_token", None, lambda: self.strings["api_token_cfg_doc"],
"api_url", "http://api.antiddos.systems",
lambda: self.strings["api_url_cfg_doc"],
"username_colors", ["#fb6169", "#faa357", "#b48bf2", "#85de85",
"#62d4e3", "#65bdf3", "#ff5694"],
lambda: self.strings["colors_cfg_doc"],
"default_username_color", "#b48bf2",
lambda: self.strings["default_username_color_cfg_doc"])
def config_complete(self):
self.name = self.strings["name"]
async def client_ready(self, client, db):
self.client = client
async def quotecmd(self, message): # noqa: C901
"""Quote a message.
Usage: .quote [template] [file/force_file]
Or: .quote np [template] [file/force_file]
If template is missing, possible templates are fetched.
If no args provided, default template will be used, quote sent as sticker"""
args = utils.get_args(message)
if len(args) > 0 and args[0] == 'np':
no_picture = True
del args[0]
else:
no_picture = False
reply = await message.get_reply_message()
if not reply:
return await utils.answer(message, self.strings["no_reply"])
username_color = username = admintitle = user_id = None
profile_photo_url = reply.from_id
admintitle = ""
pfp = None
if isinstance(reply.to_id, telethon.tl.types.PeerChannel) and reply.fwd_from:
user = reply.forward.chat
elif isinstance(reply.to_id, telethon.tl.types.PeerChat):
chat = await self.client(telethon.tl.functions.messages.GetFullChatRequest(reply.to_id))
participants = chat.full_chat.participants.participants
participant = next(filter(lambda x: x.user_id == reply.from_id, participants), None)
if isinstance(participant, telethon.tl.types.ChatParticipantCreator):
admintitle = self.strings["creator"]
elif isinstance(participant, telethon.tl.types.ChatParticipantAdmin):
admintitle = self.strings["admin"]
user = await reply.get_sender()
else:
user = await reply.get_sender()
username = telethon.utils.get_display_name(user)
if reply.fwd_from is not None and reply.fwd_from.post_author is not None:
username += f" ({reply.fwd_from.post_author})"
user_id = reply.from_id
if reply.fwd_from:
if reply.fwd_from.saved_from_peer:
profile_photo_url = reply.forward.chat
admintitle = self.strings["channel"]
elif reply.fwd_from.from_name:
username = reply.fwd_from.from_name
profile_photo_url = None
admintitle = ""
elif reply.forward.sender:
username = telethon.utils.get_display_name(reply.forward.sender)
profile_photo_url = reply.forward.sender.id
admintitle = ""
elif reply.forward.chat:
admintitle = self.strings["channel"]
profile_photo_url = user
else:
if isinstance(reply.to_id, telethon.tl.types.PeerUser) is False:
try:
user = await self.client(telethon.tl.functions.channels.GetParticipantRequest(message.chat_id,
user))
if isinstance(user.participant, telethon.tl.types.ChannelParticipantCreator):
admintitle = user.participant.rank or self.strings["creator"]
elif isinstance(user.participant, telethon.tl.types.ChannelParticipantAdmin):
admintitle = user.participant.rank or self.strings["admin"]
user = user.users[0]
except telethon.errors.rpcerrorlist.UserNotParticipantError:
pass
if no_picture:
profile_photo_url = ''
else:
if profile_photo_url is not None:
pfp = await self.client.download_profile_photo(profile_photo_url, bytes)
if pfp is not None:
profile_photo_url = "data:image/png;base64, " + base64.b64encode(pfp).decode()
else:
profile_photo_url = ""
if user_id is not None:
username_color = self.config["username_colors"][user_id % 7]
else:
username_color = self.config["default_username_color"]
reply_username = ""
reply_text = ""
if reply.is_reply is True:
reply_to = await reply.get_reply_message()
reply_peer = None
if reply_to.fwd_from is not None:
if reply_to.forward.chat is not None:
reply_peer = reply_to.forward.chat
elif reply_to.fwd_from.from_id is not None:
try:
user_id = reply_to.fwd_from.from_id
user = await self.client(telethon.tl.functions.users.GetFullUserRequest(user_id))
reply_peer = user.user
except ValueError:
pass
else:
reply_username = reply_to.fwd_from.from_name
elif reply_to.from_id is not None:
reply_user = await self.client(telethon.tl.functions.users.GetFullUserRequest(reply_to.from_id))
reply_peer = reply_user.user
if reply_username is None or reply_username == "":
reply_username = telethon.utils.get_display_name(reply_peer)
reply_text = reply_to.message
date = ""
if reply.fwd_from is not None:
date = reply.fwd_from.date.strftime("%H:%M")
else:
date = reply.date.strftime("%H:%M")
request = json.dumps({
"ProfilePhotoURL": profile_photo_url,
"usernameColor": username_color,
"username": username,
"adminTitle": admintitle,
"Text": reply.message,
"Markdown": get_markdown(reply),
"ReplyUsername": reply_username,
"ReplyText": reply_text,
"Date": date,
"Template": args[0] if len(args) > 0 else 'default',
"APIKey": self.config["api_token"]
})
resp = await utils.run_sync(requests.post, self.config["api_url"] + "/api/v2/quote", data=request)
resp.raise_for_status()
resp = await utils.run_sync(resp.json)
if resp["status"] == 500:
return await utils.answer(message, self.strings["server_error"])
elif resp["status"] == 401:
if resp["message"] == "ERROR_TOKEN_INVALID":
return await utils.answer(message, self.strings["invalid_token"])
else:
raise ValueError("Invalid response from server", resp)
elif resp["status"] == 403:
if resp["message"] == "ERROR_UNAUTHORIZED":
return await utils.answer(message, self.strings["unauthorized"])
else:
raise ValueError("Invalid response from server", resp)
elif resp["status"] == 404:
if resp["message"] == "ERROR_TEMPLATE_NOT_FOUND":
newreq = await utils.run_sync(requests.post, self.config["api_url"] + "/api/v1/getalltemplates", data={
"token": self.config["api_token"]
})
newreq = await utils.run_sync(newreq.json)
if newreq["status"] == "NOT_ENOUGH_PERMISSIONS":
return await utils.answer(message, self.strings["not_enough_permissions"])
elif newreq["status"] == "SUCCESS":
templates = self.strings["delimiter"].join(newreq["message"])
return await utils.answer(message, self.strings["templates"].format(templates))
elif newreq["status"] == "INVALID_TOKEN":
return await utils.answer(message, self.strings["invalid_token"])
else:
raise ValueError("Invalid response from server", newreq)
else:
raise ValueError("Invalid response from server", resp)
elif resp["status"] != 200:
raise ValueError("Invalid response from server", resp)
req = await utils.run_sync(requests.get, self.config["api_url"] + "/cdn/" + resp["message"])
req.raise_for_status()
file = BytesIO(req.content)
file.seek(0)
if len(args) == 2:
if args[1] == "file":
await utils.answer(message, file)
elif args[1] == "force_file":
file.name = self.strings["filename"]
await utils.answer(message, file, force_document=True)
else:
img = await utils.run_sync(Image.open, file)
with BytesIO() as sticker:
await utils.run_sync(img.save, sticker, "webp")
sticker.name = "sticker.webp"
sticker.seek(0)
try:
await utils.answer(message, sticker)
except telethon.errors.rpcerrorlist.ChatSendStickersForbiddenError:
await utils.answer(message, self.strings["cannot_send_stickers"])
file.close()
def get_markdown(reply):
if not reply.entities:
return []
markdown = []
for entity in reply.entities:
md_item = {
"Type": None,
"Start": entity.offset,
"End": entity.offset + entity.length - 1
}
if isinstance(entity, telethon.tl.types.MessageEntityBold):
md_item["Type"] = "bold"
elif isinstance(entity, telethon.tl.types.MessageEntityItalic):
md_item["Type"] = "italic"
elif isinstance(entity, (telethon.tl.types.MessageEntityMention, telethon.tl.types.MessageEntityTextUrl,
telethon.tl.types.MessageEntityMentionName, telethon.tl.types.MessageEntityHashtag,
telethon.tl.types.MessageEntityCashtag, telethon.tl.types.MessageEntityBotCommand,
telethon.tl.types.MessageEntityUrl)):
md_item["Type"] = "link"
elif isinstance(entity, telethon.tl.types.MessageEntityCode):
md_item["Type"] = "code"
elif isinstance(entity, telethon.tl.types.MessageEntityStrike):
md_item["Type"] = "stroke"
elif isinstance(entity, telethon.tl.types.MessageEntityUnderline):
md_item["Type"] = "underline"
else:
logger.warning("Unknown entity: " + str(entity))
markdown.append(md_item)
return markdown

View File

@@ -0,0 +1,147 @@
# encoding: utf-8
import asyncio
import time
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
def register(cb):
cb(RangeMod())
@loader.tds
class RangeMod(loader.Module):
"""Provides numbers as in Python range with delay"""
strings = {
"name": "Range",
"no_args": "<b>Not enough args (minimum {})</b>",
"delay_num": "<b>Delay must be a number</b>",
"args_int": "<b>All range args must be integers</b>",
"many_args": "<b>There must be no more than {} arguments</b>"
}
def __init__(self):
self.config = loader.ModuleConfig(
"msg_format", "{0}", "Format of each message. {0} replaces current number.",
"default_delay", 1.0, "Delay in all commands by default"
)
self.name = self.strings['name']
def config_complete(self):
self.name = self.strings['name']
async def _do_range(self, range_args, delay, message):
"""for internal usage; do range itself"""
await message.delete()
for now in range(*range_args):
before = time.time()
await message.respond(self.config['msg_format'].format(now))
delta = time.time() - before
await asyncio.sleep(max(delay - delta, 0))
async def _get_args(self, message, minn, maxn):
args = utils.get_args(message)
if len(args) < minn:
logger.warning(f'Minimum {minn} {"args" if minn != 1 else "arg"}, {len(args)} provided')
await utils.answer(message, self.strings['no_args'].format(minn))
return None
elif len(args) > maxn:
logger.warning(f'Maximum {maxn} {"args" if maxn != 1 else "arg"}, {len(args)} provided')
await utils.answer(message, self.strings['many_args'].format(maxn))
return None
return args
async def _check_range_args(self, range_args, message):
"""for internal usage; check if range args are int"""
try:
range_args = [int(x) for x in range_args]
return range_args
except ValueError:
logger.warning(f'Impossible to convert all range args to int ({range_args})')
await utils.answer(message, self.strings['args_int'])
return None
async def rangecmd(self, message):
"""Iterates over the given range and returns each number in separate message.
Usage: .range <python_range_args>"""
args = await self._get_args(message, 1, 3)
if args is None:
return # user done sth wrong
delay = self.config['default_delay']
range_args = await self._check_range_args(args, message)
if range_args is None:
return # user done sth wrong
await self._do_range(range_args, delay, message)
async def drangecmd(self, message):
"""Iterates over the given range and returns each number in separate message.
Usage: .drange <delay> <python_range_args>"""
args = await self._get_args(message, 2, 4)
if args is None:
return # user done sth wrong
try:
delay = float(args[0])
except ValueError:
logger.warning(f'Impossible to convert delay to float ({args[0]})')
await utils.answer(message, self.strings['delay_num'])
return
range_args = await self._check_range_args(args[1:], message)
if range_args is None:
return
await self._do_range(range_args, delay, message)
async def countcmd(self, message):
"""Count from 1 to N.\nUsage: .count <delay> <N> or .count <N>"""
args = await self._get_args(message, 1, 2)
if args is None:
return
if len(args) == 1:
delay = self.config['default_delay']
range_args = (1, args[0], 1)
elif len(args) == 2:
try:
delay = float(args[0])
except ValueError:
logger.warning(f'Impossible to convert delay to float ({args[0]})')
await utils.answer(message, self.strings['delay_num'])
return
range_args = (1, args[1], 1)
range_args = await self._check_range_args(range_args, message)
if range_args is None:
return
range_args[1] += 1 # so last number we print will be N itself
await self._do_range(range_args, delay, message)
async def rcountcmd(self, message):
"""Count from N to 1.\nUsage: .rcount <delay> <N> or .rcount <N>"""
args = await self._get_args(message, 1, 2)
if args is None:
return
if len(args) == 1:
delay = self.config['default_delay']
range_args = (args[0], 0, -1)
elif len(args) == 2:
try:
delay = float(args[0])
except ValueError:
logger.warning(f'Impossible to convert delay to float ({args[0]})')
await utils.answer(message, self.strings['delay_num'])
return
range_args = (args[1], 0, -1)
range_args = await self._check_range_args(range_args, message)
if range_args is None:
return
await self._do_range(range_args, delay, message)

View File

@@ -0,0 +1,66 @@
from .. import loader, utils
# from telethon import*
from telethon import functions, types
import logging
import datetime
import time
import asyncio
logger = logging.getLogger(__name__)
def register(cb):
cb(REPLMod())
@loader.tds
class REPLMod(loader.Module):
"""REPLIED for selected users"""
strings = {"name": "REPL"}
d = dict()
def __init__(self):
self.name = self.strings["name"]
def config_complete(self):
pass
async def client_ready(self, client, db):
self._db = db
self._me = await client.get_me()
async def addtxcmd(self, message):
"""Select users\nFor example: .addtx used_id \"text when reply (Default: \'.\'\""""
args = utils.get_args(message)
if not len(args):
await utils.answer(message, "Напиши .help REPL, там есть пример, как нужно делать.\nТы сделал неправильно!")
elif len(args) == 1:
self.d[int(args[0])] = '.'
else:
f = ""
for i in range(1, len(args)):
f += args[i]
if i != len(args) - 1:
f += " "
self.d[int(args[0])] = f
await utils.answer(message, "Done.\nP.S: 3 seconds later it's automatic delete")
await asyncio.sleep(3)
await message.delete()
async def clrtxcmd(self, message):
"""Unselect user\nFor example: `.clrtx used_id` for one user or `.clrtx` for all users"""
args = utils.get_args(message)
if not len(args):
self.d.clear()
else:
self.d.pop(int(args[0]))
await utils.answer(message, "Done.\nP.S: 3 seconds later it's automatic delete")
await asyncio.sleep(3)
await message.delete()
async def watcher(self, message):
if (message.from_id in self.d) and (
message.mentioned or getattr(message.to_id, "user_id", None) == self._me.id):
await message.respond(self.d[message.from_id], reply_to=message)

View File

@@ -0,0 +1,81 @@
# requires: pymongo dnspython
# Забейте
import asyncio
import pymongo
import logging
logger = logging.getLogger(__name__)
from .. import loader, utils
class Student:
def __init__(self, id: int, last_name: str, first_name: str,
patronymic: str, grade: int, region: str, academ: bool, approved: int=None):
self.last_name = last_name
self.first_name = first_name
self.patronymic = patronymic
self.grade = int(grade)
self.region = region
self.academ = bool(academ)
self.approved = approved
self.id = int(id)
def __str__(self):
p = 'Академ' if self.academ else 'Отбор'
# a = f'Уже вроде бы добавлен в чат (tg://user?id={self.approved})' if self.approved else 'Еще нет в чате'
return f'[{p}.{self.id}] {self.last_name} {self.first_name} {self.patronymic}, '\
f'{self.grade} класс, из {self.region}'
class SiriusMod(loader.Module):
"""Ищем поступивших на ИЮ2020"""
strings = {"name": "Sirius"}
def __init__(self):
self.config = loader.ModuleConfig(
# name - default - description
"db_uri", None, "Database URI, if you dont know where to take it - nevermind",
"db_db", None, "database",
"db_coll", None, "collection",
"replace_ё", True, "replace ё with е in requests, incorrect usage may return incorrect result"
)
self.name = self.strings['name']
self.db = None
def config_complete(self):
self.db = pymongo.MongoClient(self.config['db_uri'])\
.get_database(self.config['db_db']).get_collection(self.config['db_coll'])
async def findcmd(self, message):
arg = utils.get_args_raw(message).strip()
if self.config['replace_ё']:
arg = arg.replace('ё', 'е')
arg = arg.replace('Ё', 'Е')
logger.debug('Got: %s', arg)
if not arg:
await utils.answer(message, 'Только 1 аргумент - номер в списке или фамилия/имя')
if arg.isdigit():
add = f'людей с номером {arg}'
arg = int(arg)
users = list(self.db.find({"id": arg}))
elif ' ' in arg or arg.lower() == 'янао': # Костыли костыли
add = f'людей из региона {arg}'
_users = list(self.db.find())
users = []
for user in _users:
if user['region'].lower() == arg.lower():
users.append(user)
else:
add = f'людей, которых зовут {arg}'
arg = arg.capitalize()
users = list(self.db.find({'$or': [{"last_name": arg}, {"first_name": arg}, {"patronymic": arg}]}))
msg = [f'{len(users)} всего {add}', '==']
for user in users:
del user['_id']
s = Student(**user)
msg += [str(s), '==']
msg = msg[:-1]
msg = '\n'.join(msg)
await utils.answer(message, msg)

92
AlpacaGang/ftg-modules/spam.py Executable file
View File

@@ -0,0 +1,92 @@
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
import asyncio
from asyncio import wait, sleep
from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
from userbot.events import register
@register(outgoing=True, pattern="^.cspam (.*)")
async def tmeme(e):
cspam = str(e.pattern_match.group(1))
message = cspam.replace(" ", "")
await e.delete()
for letter in message:
await e.respond(letter)
if BOTLOG:
await e.client.send_message(
BOTLOG_CHATID, "#CSPAM\n"
"TSpam was executed successfully")
@register(outgoing=True, pattern="^.wspam (.*)")
async def tmeme(e):
wspam = str(e.pattern_match.group(1))
message = wspam.split()
await e.delete()
for word in message:
await e.respond(word)
if BOTLOG:
await e.client.send_message(
BOTLOG_CHATID, "#WSPAM\n"
"WSpam was executed successfully")
@register(outgoing=True, pattern="^.spam (.*)")
async def spammer(e):
counter = int(e.pattern_match.group(1).split(' ', 1)[0])
spam_message = str(e.pattern_match.group(1).split(' ', 1)[1])
await e.delete()
await asyncio.wait([e.respond(spam_message) for i in range(counter)])
if BOTLOG:
await e.client.send_message(BOTLOG_CHATID, "#SPAM\n"
"Spam was executed successfully")
@register(outgoing=True, pattern="^.picspam")
async def tiny_pic_spam(e):
message = e.text
text = message.split()
counter = int(text[1])
link = str(text[2])
await e.delete()
await asyncio.wait([e.client.send_file(e.chat_id, link) for i in range(counter)])
if BOTLOG:
await e.client.send_message(
BOTLOG_CHATID, "#PICSPAM\n"
"PicSpam was executed successfully")
@register(outgoing=True, pattern="^.delayspam (.*)")
async def spammer(e):
spamDelay = float(e.pattern_match.group(1).split(' ', 2)[0])
counter = int(e.pattern_match.group(1).split(' ', 2)[1])
spam_message = str(e.pattern_match.group(1).split(' ', 2)[2])
await e.delete()
for i in range(1, counter):
await e.respond(spam_message)
await sleep(spamDelay)
if BOTLOG:
await e.client.send_message(
BOTLOG_CHATID, "#DelaySPAM\n"
"DelaySpam was executed successfully")
CMD_HELP.update({
"spam":
".cspam <text>\
\nUsage: Spam the text letter by letter.\
\n\n.spam <count> <text>\
\nUsage: Floods text in the chat !!\
\n\n.wspam <text>\
\nUsage: Spam the text word by word.\
\n\n.picspam <count> <link to image/gif>\
\nUsage: As if text spam was not enough !!\
\n\n.delayspam <delay> <count> <text>\
\nUsage: .bigspam but with custom delay.\
\n\n\nNOTE : Spam at your own risk !!"
})

View File

@@ -0,0 +1,37 @@
# fuck python the encoding: utf-8
from .. import loader, utils
import logging
import datetime
import time
import asyncio
logger = logging.getLogger(__name__)
def register(cb):
cb(SPFMod())
@loader.tds
class SPFMod(loader.Module):
"""Этот модуль геи личку ваших друзей"""
strings = {"name": "ЖУЖАКА НАХУЙ"}
def __init__(self):
self.name = self.strings["name"]
def config_complete(self):
pass
async def spfcmd(self, message):
"""Чтобы использовать пишем так: .spf @ник_вашегоруга"""
args = utils.get_args(message)
if not args:
await utils.answer(message, "Вы не указали кому хотите писать\nЧтобы использовать напишите так: .spf @ник_вашегоруга")
return
who = args[0][1:]
conv = message.client.conversation("t.me/" + who,
timeout=5, exclusive=True)
for i in range(100):
await conv.send_message("Ты гей")

View File

@@ -0,0 +1,245 @@
from .. import loader, utils
import logging
import random
logger = logging.getLogger(__name__)
version = 4.8
sentence_min = 3
sentence_max = 10
# paragraph_min = 10
# paragraph_max = 20
print_length = False
m = ['некультурный', 'необразованный',
'гороховый', 'мудовый', 'глупенький',
'малолетний', 'ебучий', 'гнилой',
'собачий', 'ссаный', 'моржовый',
'вредный', 'прибабахнутый', 'ебаный',
'волшебный', 'сказочный', 'маленький',
'приёмный', 'сральный', 'пердёжный',
'обоссанный', 'обосранный', 'чёртов',
'грязный', 'тупой', 'нищий', 'родной', 'мусорный',
'дегенеративный',
'распроклятый', 'турецкий', 'блядский',
'ёбаный', 'хуев', 'хуёвый', 'ебанутый',
'ёбнутый', 'грязный', 'зелёный', 'сукин',
'лысый', 'пожилой', 'вонючий', 'чокнутый']
f = ['некультурная', 'необразованная',
'гороховая', 'мудовая', 'глупенькая',
'малолетняя', 'ебучая', 'гнилая',
'собачья', 'ссаная', 'моржовая',
'вредная', 'прибабахнутая', 'ебаная',
'волшебная', 'сказочная', 'маленькая',
'приёмная', 'сральная', 'пердёжная',
'обоссанная', 'обосранная', 'чёртова',
'грязная', 'тупая', 'нищая',
'родная', 'мусорная', 'дегенеративная',
'распроклятая', 'турецкая', 'блядская',
'ёбаная', 'хуева', 'хуёвая', 'ебанутая',
'ёбнутая', 'грязная', 'зелёная', 'сукина',
'лысая', 'пожилая', 'вонючая', 'чокнутая']
s = ['некультурное', 'необразованное',
'гороховое', 'мудовое', 'глупенькое',
'малолетнее', 'ебучее', 'гнилое',
'собачье', 'ссаное', 'моржовое',
'вредное', 'прибабахнутое', 'ебаное',
'волшебное', 'сказочное', 'маленькое',
'приёмное', 'сральное', 'пердёжное',
'обоссанное', 'обосранное', 'чёртово', 'грязное',
'тупое', 'нищее', 'родное', 'мусорное', 'дегенеративное',
'распроклятое', 'турецкое', 'блядское',
'ёбаное', 'хуево', 'хуёвое', 'ебанутое',
'ёбнутое', 'грязное', 'зелёное', 'сукино',
'лысое', 'пожилое', 'вонючее', 'чокнутое']
k = ['из жопы', 'в ловушке', 'в бане',
'на хуе', 'в дурке', 'из стула', 'в дурке ебаной',
'в хуипе', 'в запечатанной колоде']
n = ['негра', 'джокера', 'тупого говна', 'хуйни ебаной',
'хуя', 'феминизма', 'говна',
'от народа', 'хуйни', 'Навального',
'ловушкера', 'Путина', 'русского народа', 'вонючки', 'с функцией жопа']
o = ['пиздец', 'блять', 'попался в ловушку',
'тебя забайтили', 'ловушка джокера', 'тебе бан',
'фак ю', 'убейся', 'соси',
'ёбаный твой рот', 'срал я на тебя',
'убейся об стену', 'соси пизду', 'у тебя хуй вместо носа',
'купи мою подписку на ютубе',
'хуй соси', 'губой тряси', 'я съел деда',
'насрал в пизду',
'22 июня 1642 года Карл Первый поднял королевский штандарт (королевский флаг), что по английским традициям означало объявление войны',
'мне этот мир абсолютно понятен',
'я был на этой планете бесконечным множеством',
'но тебе этого не понять',
'иди преисполняться в гранях каких-то',
'пиздуй - бороздуй',
'бредишь', 'вот я какну и смываю, и ты так делай',
'не надо шутить с войной',
'твою дочку ебут', 'залупаешься',
'хули ты пиздишь', 'поцелуй лошадиную сраку',
'распронаёб тебя', 'ъеь', 'ьуь', 'аье',
'какого хуя они в другом порядке разложены',
'ай фак ю булщит щит',
'он за углом сидит и тебе на голову дрочит',
'армяне в нарды играют', 'жирняк гай',
'иди сюда, попробуй меня трахнуть, я тебя сам трахну',
'что ты там делаешь', 'беги за горизонт',
'попал в дурку ебаную', 'был бы ты человек', 'нахуй',
'запомни', 'хули ты сюда лезешь',
'высрана твоя морда', 'возьми салфетку',
'я бы никому не проиграл',
'иди нахуй', 'иди',
'я тебя ебал, гад, срать на нас говна',
'я тебя ебал гадить нас срать так',
'держи в курсе', 'несёшь хуйню какую-то',
'русские вперёд']
d = ['бекон', 'сыр', 'пенис', 'член',
'мудозвон', 'лицемер', 'лжец',
'хуй', 'гомогей', 'чай', 'рукоблуд',
'долбан', 'пидорас', 'сын', 'козёл',
'газ', 'фашист', 'пососатель',
'дегенерат', 'спермобак', 'долбоёб',
'клоун', 'паразит', 'письколёт',
'мудак', 'спидозник', 'пудж', 'кремлебот',
'объебос', 'дурачок', 'хуебес', 'пиздолёт',
'педик', 'педик - медведик', 'дебил', 'дифичент',
'кок сакер', 'пиздабол', 'аутист', 'гадёныш', 'выблядок',
'глиномес', 'даун', 'хер', 'булщит', 'засранец',
'инвалид', 'дурак', 'болван',
'минетчик', 'онанист', 'напёрдыш',
'чилипиздрик', 'пиздюк', 'гей', 'ловушкер',
'пендос', 'наркоман', 'алкаш', 'жиробас',
'рак', 'укурок', 'крокодил', 'ебальник',
'секс-раб', 'потомок', 'дрыщ',
'урод', 'карлик', 'дед инсайд', 'волк',
'калыван', 'либераст', 'шакал',
'педофил', 'бомж', 'пингвин', 'жираф',
'огурец', 'салат', 'лук', 'картофель',
'деградант', 'спам', 'человек', 'гуманитарий',
'язык', 'стол', 'PEP-8', 'ебалай', 'враг', 'недруг', 'супостат',
'кретин', 'козолуп', 'свинарь',
'униженец', 'опущенец', 'муравей',
'дятел', 'козёл', 'жирняк', 'говноед',
'чёрт', 'суслик', 'идиот', 'жлоб', 'мерзавец',
'негодяй', 'подлец', 'ублюдок', 'гад',
'гавкошмыг', 'чикибамбонатор', 'чикибамбог',
'джокер', 'жмых', 'жмышок', 'жмышонок',
'куколд', 'ебалай', 'ушлёпок',
'хуесос', 'членосос', 'чикибамбонёнок',
'чикибан', 'чикибомбастер', 'чайник',
'чикибамбонизатор', 'чикибамбог']
dd = ['куколда', 'хуйолда', 'мудила', 'блядина', 'гнида',
'пидрила', 'тварь', 'сука', 'сперма', 'пидорасина',
'либераха', 'срака', 'жопа', 'петушара', 'залупа',
'хуета', 'пупа', 'петька', 'блядь', 'елда', 'тряпка',
'яма', 'хуемразь', 'срань', 'мошонка', 'ссанина',
'вагина', 'пизда', 'пососательница',
'ловушка', 'паста', 'макаронина',
'жиробасина', 'радфемка', 'шлюха', 'прошмандовка',
'жируха', 'доска', 'уродина',
'плоскодонка', 'скотина', 'омега',
'черешня', 'ватрушка', 'шишка',
'ракушка', 'свинья', 'какашка',
'гнилушка', 'лягушка', 'свинушка',
'картошка', 'волчара', 'дочь', 'пешка',
'давалка', 'пососательница',
'колбаса', 'собака', 'мохнатка', 'жижа',
'какашка', 'какуля', 'душа', 'вражина',
'падла', 'болезнь', 'бумажка', 'вонючка',
'тень', 'гадина', 'чикибамбони',
'микробамбони', 'мышь', 'мразь',
'мразина', 'мразота']
ddd = ['удобрение', 'уёбище', 'ебло', 'хуйло',
'чудище', 'говно', 'яблоко', 'животное',
'дерьмо', 'блядотище', 'дитя', 'порождение',
'очко', 'растение', 'ебало', 'ведро',
'мудило', 'хуепучило']
gens = ['03', '14', '25', '8',
'06', '16', '26', '30',
'41', '52', '303', '330', '0',
'414', '441', '1', '8',
'525', '552', '2', '067',
'167', '267', '306', '416',
'526', '07', '8', '8', '8',
'17', '27', '8', '8', '8',
'307', '417', '527', '8', '8',
'3067', '4167', '5267']
array = [d, dd, ddd, m, f, s, k, n, o]
def generate(word_count: int, caps_rate: int, name: str):
res = []
priv = ''
if name:
priv += f'Привет, {name}! '
caps_rate %= 100
priv += 'Ты, '
word_count_now = 0
while word_count_now < word_count:
tempi = word_count + 1
while word_count_now + tempi > word_count:
random.seed()
y = random.choice(gens)
x = []
for j in y:
x.append(random.choice(array[int(j)]))
x = ' '.join(x)
tempi = len(x.split())
res.append(x)
word_count_now += tempi
res = ', '.join(res)
res = res.split()
count = 0
kek = random.randint(sentence_min, sentence_max)
for v in range(len(res)):
if res[v].endswith(','):
count += 1
if count % kek == 0:
count = 0
random.seed()
kek = random.randint(sentence_min, sentence_max)
res[v] = res[v][:-1] + '.'
if v < len(res) - 1:
res[v + 1] = res[v + 1][0].upper() + res[v + 1][1:]
res[0] = priv + res[0]
res = ' '.join(res).split()
for v in range(len(res)):
random.seed()
z = random.randint(0, 99)
if z < caps_rate:
res[v] = res[v].upper()
return ' '.join(res) + '.'
# КТО ПРОЧИТАЛ ТОТ ЗДОХНЕТ
def register(cb):
cb(TralkaMod())
@loader.tds
class TralkaMod(loader.Module):
"""Generates pastes"""
strings = {"name": "Tralka"}
def __init__(self):
self.config = loader.ModuleConfig()
self.name = self.strings['name']
async def tralkacmd(self, message):
""".tralka <word_count> <caps_rate (in %)> <recepient name>"""
args = utils.get_args(message)
if len(args) < 2:
await utils.answer(message, "Not enough arguments")
elif len(args) == 2:
await utils.answer(message, generate(int(args[0]), int(args[1]), None))
else:
await utils.answer(message, generate(int(args[0]), int(args[1]), args[2]))

View File

@@ -0,0 +1,94 @@
from .. import loader, utils
import logging
import datetime
import time
import asyncio
logger = logging.getLogger(__name__)
def register(cb):
cb(WAITMod())
@loader.tds
class WAITMod(loader.Module):
"""Этот модуль поможет вам удалить сообщение через n секунд/минут"""
strings = {"name": "wait"}
def __init__(self):
self.name = self.strings["name"]
def config_complete(self):
pass
async def wait5cmd(self, message):
"""Эта команда удаляет сообхение черезе 5 секунд"""
await utils.answer(message, "Через 5 секунд это сообщение удалится")
for i in range(4, -1, -1):
await asyncio.sleep(1)
await utils.answer(message, "Через " + str(i) + " секунд это сообщение удалится")
await message.delete()
async def waitcmd(self, message):
"""Эта команда удаляет сообхение через n секунд, \nписать нужно так: .wait <n>, если хотите секунды\nи так .wait <n>m, если хотите ждать в минутах\n(например .wait 5m)"""
args = utils.get_args(message)
if not args or len(args) > 1:
await utils.answer(message, "Вы не указали число секунд или указали несколько параметров")
else:
try:
g = -1
h = ""
try:
g = int(args[0][:len(args[0])])
except:
try:
g = int(args[0][:len(args[0]) - 1])
h = args[0][len(args[0]) - 1]
except:
await utils.answer(message, "Вы указали не число!")
if g > 0:
if h == 's' or h == '':
x = g
lst = "Через " + str(x) + " секунд это сообщение удалится"
await utils.answer(message, lst)
dd = time.time()
while time.time() - dd < x:
now = "Через " + str(x - round(time.time() - dd)) + " секунд это сообщение удалится"
if now != lst:
await utils.answer(message, now)
lst = now
await message.delete()
elif h == 'm':
x = g
lst = "Через " + str(x) + " минут это сообщение удалится"
await utils.answer(message, lst)
dd = time.time()
ff = x * 60
llst = x
while time.time() - dd < ff:
oo = round((ff - round(time.time() - dd)) / 60)
nw = oo
if nw == llst:
await asyncio.sleep(0.1)
continue
now = "Через " + str(nw) + " минут это сообщение удалится"
await utils.answer(message, now)
llst = nw
await message.delete()
else:
await utils.answer(message, "Вы указали не число!")
except:
await utils.answer(message, "Упс, ошибочка вышла! Напшите @gerasikoff, он вам поможет")
async def tagcmd(self, message):
"""Эта команда для троллинга друзей. \nЕй вы можете тегнуть друга, а сообщение само удалится!"""
await message.delete()

121
CakesTwix/Hikka-Modules/.gitignore vendored Normal file
View File

@@ -0,0 +1,121 @@
# For quick debug
test.py
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# PyCharm
.idea/

View File

@@ -0,0 +1,65 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/shadow_geektg
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: requests
# meta pic: https://cdn-icons-png.flaticon.com/512/1005/1005340.png
# meta developer: @shadow_geektg, @cakestwix_mods
# scope: inline
# scope: hikka_only
import requests
import random
from .. import loader, utils
from telethon.tl.types import Message
async def photofox() -> str:
"""Fox photo handler"""
return (await utils.run_sync(requests.get, "https://randomfox.ca/floof")).json()["image"]
async def photodog() -> str:
"""Dog photo handler"""
return (await utils.run_sync(requests.get, "https://random.dog/woof.json")).json()["url"]
async def randomapi():
randomapis = random.choice(["https://randomfox.ca/floof", "https://random.dog/woof.json", "http://aws.random.cat/meow"])
if randomapis == "https://randomfox.ca/floof":
return (await utils.run_sync(requests.get, "https://randomfox.ca/floof")).json()["image"]
else:
return (await utils.run_sync(requests.get, "https://random.dog/woof.json")).json()["url"]
@loader.tds
class FoxGalerryMod(loader.Module):
"""🦊 Foxes, Dogs 🐶 and cats 🐱"""
strings = {"name": "FoxGallery"}
async def foxescmd(self, message: Message) -> None:
"""🦊 Sending photos with foxes"""
await self.inline.gallery(
message,
photofox,
)
async def dogscmd(self, message: Message) -> None:
"""🐶 Sending photos with dogs"""
await self.inline.gallery(
message,
photodog,
)
async def randomcdfcmd(self, message: Message) -> None:
"""Photos of dogs 🐶 and foxes 🦊"""
await self.inline.gallery(
message,
randomapi,
)

View File

@@ -0,0 +1,540 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 1, 1) # BETA
# requires: httpx pydantic
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
# scope: inline
# scope: hikka_only
# scope: hikka_min 1.1.2
from .. import loader, utils
import httpx
import asyncio
import logging
import ast
import telethon
from aiogram.types import InputFile
from aiogram.utils.markdown import hlink
from pydantic import BaseModel, Field
from typing import Optional
logger = logging.getLogger(__name__)
def rating_string(rating_list: list) -> str:
rating_str = ["s", "q", "e"]
if sum(rating_list) == 2:
return (
"-rating:"
+ rating_str[[i for i, val in enumerate(rating_list) if not val][0]]
)
elif sum(rating_list) == 1:
return f"rating:{rating_str[[i for i, val in enumerate(rating_list) if val][0]]}"
else:
return ""
# id: int | Айди
# tag: str = Field(alias='tag_string') | Теги
# rating: str | Рейтинг
# author: str | Автор
# file_size: int | Размер без сжатия
# sample_file_size: int | Размер со средним сжатием
# file_url: str | Без сжатия
# preview_file_url: str | Сильное сжатие
# sample_url: Optional[str] = None | Среднее сжатие
# source: Optional[str] = None | Откуда арт
class BooruModel(BaseModel):
id: int
tag: str = Field(alias='tag_string_general')
rating: str
author: Optional[str] = None
file_size: int
sample_file_size: int = Field(alias='file_size')
file_url: str
preview_file_url: str = Field(alias='large_file_url')
sample_url: Optional[str] = Field(alias='large_file_url')
source: Optional[str] = None
class MoebooruModel(BaseModel):
id: int
tag: str = Field(alias='tags')
rating: str
author: Optional[str] = None
file_size: int
sample_file_size: int
file_url: str
preview_file_url: str = Field(alias='preview_url')
sample_url: Optional[str] = None
source: Optional[str] = None
class Moebooru:
domain = 'yande.re'
get_url = f'https://{domain}'
post_url = '/post.json'
async def getLast(self, params):
async with httpx.AsyncClient() as client:
get = await client.get(self.get_url + self.post_url + params)
result = get.json()
return [MoebooruModel(**item) for item in result]
class Konachan_Net(Moebooru):
domain = 'konachan.net'
get_url = f'https://{domain}'
post_url = '/post.json'
class Lolibooru(Moebooru):
domain = 'lolibooru.moe'
get_url = f'https://{domain}'
post_url = '/post.json'
# Very buggy :(
class Booru:
domain = 'danbooru.donmai.us'
get_url = f'https://{domain}'
post_url = '/posts.json'
async def getLast(self, params):
async with httpx.AsyncClient() as client:
get = await client.get(self.get_url + self.post_url + params)
result = get.json()
list_art = []
for item in result:
try:
list_art.append(BooruModel(**item))
except Exception as err:
logger.debug(str(err)) # Fck Booru
return list_art
@loader.tds
class ImageBoardSenderMod(loader.Module):
"""Auto-posting art to your channels"""
strings = {
"cfg_channel": "Сhannel variable where the content will be posted",
"cfg_tags": "Filtering art by tags",
"name": "ImageBoardSender",
"no_chennel": "Channel does not exist",
"ok": "Everything is okay",
"no_ok": "Everything not okay (maybe not admin rights)",
"channel_status": "<b>Channel Status</b>:",
"channel_username": "<b>Channel username</b>:",
"channel_tags": "<b>Channel tags</b>:",
"channel_no_tags": "no tags",
"change_channel_username": "<b>Change the channel username</b>",
"changed_successfully": "Successfully changed",
"btn_menu_change_channel": "✍️ Change username channel",
"btn_menu_change_tags": "✍️ Change tags",
"btn_menu_change_input": "✍️ Enter new configuration value for this option",
"btn_menu_update": "Update",
"btn_menu_start": "Start",
"btn_menu_stop": "Stop",
"btn_menu_Safe": "Safe",
"btn_menu_Questionable": "Questionable",
"btn_menu_Explicit": "Explicit",
"btn_menu_autostart_on": "✅ Autostart",
"btn_menu_autostart_off": "❌ Autostart",
"source": "<b>List of available sources. \nThe source used:</b> <code>{}</code>",
}
strings_ru = {
"cfg_channel": "Переменная канала, где будет размещаться контент",
"cfg_tags": "Фильтрация артов по тегам",
"name": "ImageBoardSender",
"no_chennel": "Канал не существует",
"ok": "Все хорошо",
"no_ok": "Все не окей (возможно нет прав админа)",
"channel_status": "<b>Статус канала</b>:",
"channel_username": "<b>Имя канала</b>:",
"channel_tags": "<b>Теги канала</b>:",
"channel_no_tags": "нет тегов",
"change_channel_username": "<b>Изменить имя пользователя канала</b>",
"changed_successfully": "Успешно изменено",
"btn_menu_change_channel": "✍️ Изменить имя канал",
"btn_menu_change_tags": "✍️ Изменить теги",
"btn_menu_change_input": "✍️ Введите новое значение конфигурации для этой опции",
"btn_menu_update": "Обновить",
"btn_menu_start": "Start",
"btn_menu_stop": "Stop",
"btn_menu_Safe": "Безопасно",
"btn_menu_Questionable": "Под вопросом",
"btn_menu_Explicit": "Откровенное 18+",
"btn_menu_autostart_on": "✅ Автостарт",
"btn_menu_autostart_off": "❌ Автостарт",
"source": "<b>Список доступных источников. \nИспользуемый источник:</b> <code>{}</code>",
}
rating = {"e": "Explicit 🔴", "q": "Questionable 🟡", "s": "Safe 🟢"}
url = "https://yande.re/post.json"
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_CHANNEL",
"@notset",
lambda: self.strings("cfg_channel"),
"CONFIG_TAGS",
"",
lambda: self.strings("cfg_tags"),
)
self.entity = None
self.last_id = 0
self.sources = {"Yandere": Moebooru(), "Konachan.net": Konachan_Net(), "LoliBooru": Lolibooru()}
self.source_btn = [{"text": item, "callback": self.callback__change_source, "args": (item,)} for item in self.sources]
# Check channel rights
async def check_entity(self) -> bool:
try:
if not self.entity:
self.entity = await self._client.get_entity(self.config["CONFIG_CHANNEL"])
if not isinstance(self.entity, telethon.types.Channel):
self.entity = None
return False
except ValueError:
self.entity = None
return False
if self.entity.admin_rights is None:
return False
elif self.entity.admin_rights.post_messages:
return True
async def menu_keyboard(self) -> list:
return [
[
{
"text": self.strings["btn_menu_change_channel"],
"input": self.strings["btn_menu_change_input"],
"handler": self.change_config,
"args": ("CONFIG_CHANNEL",),
},
{
"text": self.strings["btn_menu_change_tags"],
"input": self.strings["btn_menu_change_input"],
"handler": self.change_config,
"args": ("CONFIG_TAGS",),
},
],
[
{
"text": f"[ {self.strings['btn_menu_Safe']} ]"
if self._db.get(self.strings["name"], "rating")[0]
else self.strings["btn_menu_Safe"],
"callback": self.set_rating,
"args": ("s"),
},
{
"text": f"[ {self.strings['btn_menu_Questionable']} ]"
if self._db.get(self.strings["name"], "rating")[1]
else self.strings["btn_menu_Questionable"],
"callback": self.set_rating,
"args": ("q"),
},
{
"text": f"[ {self.strings['btn_menu_Explicit']} ]"
if self._db.get(self.strings["name"], "rating")[2]
else self.strings["btn_menu_Explicit"],
"callback": self.set_rating,
"args": ("e"),
},
]
if await self.check_entity()
else [],
[
{"text": self.strings["btn_menu_stop"], "callback": self.stop_posting}
if self.loop__send_arts.status
else {
"text": self.strings["btn_menu_start"],
"callback": self.start_posting,
},
{
"text": self.strings["btn_menu_autostart_on"]
if self._db.get(self.strings["name"], "autostart")
else self.strings["btn_menu_autostart_off"],
"callback": self.change_autostart,
},
]
if await self.check_entity()
else [],
[
{
"text": self.strings["btn_menu_update"],
"callback": self.update_channel_status,
}
],
]
# Just async init
async def _init(self) -> None:
await self.check_entity()
bot_info = await self.inline.bot.get_me()
if self.config["CONFIG_CHANNEL"] == "@notset":
return
self.entity = await self._client.get_entity(self.config["CONFIG_CHANNEL"])
try:
channel_bot = await self._client.edit_admin(self.config["CONFIG_CHANNEL"],
user=bot_info.username,
change_info=False,
post_messages=True,
edit_messages=True,
delete_messages=True,
ban_users=False,
invite_users=False,
pin_messages=True,
add_admins=False,)
logger.debug(f"[{self.strings['name']}] Bot added")
if self._db.get(self.strings["name"], "autostart"):
self.loop__send_arts.start()
except ValueError:
channel_bot = None
logger.warning(f"[{self.strings['name']}] Check channel username")
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
None if self._db.get(self.strings["name"], "source") else self._db.set(self.strings["name"], "source", "Yandere")
None if self._db.get(self.strings["name"], "rating") else self._db.set(self.strings["name"], "rating", [False, False, False])
None if self._db.get(self.strings["name"], "autostart") else self._db.set(self.strings["name"], "autostart", False)
await self._init()
async def on_unload(self) -> None:
try:
self.loop__send_arts.stop()
except Exception:
pass
# Caption
def string_builder(self, json):
# Thanks to Фрося <3
string = f"Tags : {'#' + str.join(' #', json.tag.split())}\n"
string += f'©️ : {json.author or "No author"}\n'
string += f'🔗 : {json.source or "No source"}\n'
string += f"Rating : {self.rating[json.rating]}\n\n"
string += ("🆔 : " + str(json.id))
return string
# Commands #
async def channelmenucmd(self, message):
"""🗒 Simple Menu and status"""
string = f"{self.strings['channel_status']} {self.strings['ok'] if await self.check_entity() else self.strings['no_ok']}\n"
string += f"{self.strings['channel_username']} {self.config['CONFIG_CHANNEL'] if self.config['CONFIG_CHANNEL'] != '@notset' else self.strings['change_channel_username']}\n"
string += f"{self.strings['channel_tags']} {self.config['CONFIG_TAGS'] if self.config['CONFIG_TAGS'] != '' else self.strings['channel_no_tags']}\n"
await self.inline.form(
text=string,
message=message,
reply_markup=await self.menu_keyboard(),
)
async def artsourcecmd(self, message):
"""🧑‍🎤 Change the source of art"""
await self.inline.form(
text=self.strings["source"].format(self._db.get(self.strings["name"], "source")),
message=message,
reply_markup=utils.chunks(self.source_btn, 2),
)
async def latestartcmd(self, message):
"""⌚️ Sending the last art for now"""
params = (
"?tags="
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(art_data[0].sample_url),
self.string_builder(art_data[0]),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": art_data[0].file_url}]
),
)
await message.delete()
async def randomartcmd(self, message):
"""🎲 Sending a random art"""
params = (
"?tags=order:random "
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(art_data[0].sample_url),
self.string_builder(art_data[0]),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": art_data[0].file_url}]
),
)
await message.delete()
# Inline callback handlers #
# From Hikka https://github.com/hikariatama/Hikka/blob/d3144fcebdbc8ecbec7f3d299cc927bb1fea00b6/hikka/modules/hikka_config.py#L51-L80
async def change_config(self, call, param, config_name) -> None:
for module in self.allmodules.modules:
if module.strings("name") == self.strings["name"]:
module.config[config_name] = param
if param:
try:
param = ast.literal_eval(param)
except (ValueError, SyntaxError):
pass
self._db.setdefault(module.__class__.__name__, {}).setdefault(
"__config__", {}
)[config_name] = param
else:
try:
del self._db.setdefault(
module.__class__.__name__, {}
).setdefault("__config__", {})[config_name]
except KeyError:
pass
self.allmodules.send_config_one(module, self._db, skip_hook=True)
self._db.save()
await call.edit(
text=self.strings["changed_successfully"],
reply_markup=[
{
"text": self.strings["btn_menu_update"],
"callback": self.update_channel_status,
}
],
)
async def update_channel_status(self, call) -> None:
string = f"{self.strings['channel_status']} {self.strings['ok'] if await self.check_entity() else self.strings['no_ok']}\n"
string += f"{self.strings['channel_username']} {self.config['CONFIG_CHANNEL'] if self.config['CONFIG_CHANNEL'] != '@notset' else self.strings['change_channel_username']}\n"
string += f"{self.strings['channel_tags']} {self.config['CONFIG_TAGS'] if self.config['CONFIG_TAGS'] != '' else self.strings['channel_no_tags']}\n"
await call.edit(
text=string,
reply_markup=await self.menu_keyboard(),
)
async def set_rating(self, call, rating) -> None:
list_rating = self._db.get(self.strings["name"], "rating")
if rating == "s":
list_rating[0] = not list_rating[0]
self._db.set(self.strings["name"], "rating", list_rating)
elif rating == "q":
list_rating[1] = not list_rating[1]
self._db.set(self.strings["name"], "rating", list_rating)
elif rating == "e":
list_rating[2] = not list_rating[2]
self._db.set(self.strings["name"], "rating", list_rating)
await self.update_channel_status(call)
async def start_posting(self, call) -> None:
if not self.loop__send_arts.status:
self.loop__send_arts.start()
await asyncio.sleep(0.5) # Otherwise the button does not update
await self.update_channel_status(call)
async def stop_posting(self, call) -> None:
if self.loop__send_arts.status:
self.loop__send_arts.stop()
await self.update_channel_status(call)
async def change_autostart(self, call) -> None:
self._db.set(
self.strings["name"],
"autostart",
not self._db.get(self.strings["name"], "autostart"),
)
await self.update_channel_status(call)
async def callback__change_source(self, call, source):
self._db.set(self.strings["name"], "source", source)
self.last_id = 0
await call.edit(text=self.strings["source"].format(self._db.get(self.strings["name"], "source")), reply_markup=utils.chunks(self.source_btn, 2))
# General loop #
@loader.loop(interval=60)
async def loop__send_arts(self):
"""Auto-Posting"""
params = (
"?tags="
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
if art_data == []:
logger.warning(f"[{self.strings['name']}] No arts, check tags")
return
if self.last_id == 0:
self.last_id = art_data[0].id
return
for item in reversed(art_data):
if item.id > self.last_id:
try:
# await self._client.send_file(
# self.entity,
# item["sample_url"],
# caption=self.string_builder(item),
# )
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(item.sample_url),
self.string_builder(item),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": item.file_url}]
),
)
# break # DEBUG
except Exception as e:
logger.error(str(e))
await asyncio.sleep(1)
self.last_id = art_data[0].id
await asyncio.sleep(5 * 60)

View File

@@ -0,0 +1,104 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: spotdl
# meta pic: https://cdn-icons-png.flaticon.com/512/2111/2111624.png
# meta developer: @cakestwix_mods
# scope: hikka_only
import os
import subprocess
import logging
import asyncio
import spotdl
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class InlineSpotifyDownloaderMod(loader.Module):
"""Module for downloading music from Spotify"""
strings = {
"name": "InlineSpotifyDownloader",
"cfg_spotdl_path": "Path to spotdl bin",
"no_args": "🎞 <b>You need to specify link</b>",
"no_track": "🎞 <b>You need to specify track link</b>",
"downloading": "🎞 <b>Downloading...</b>",
"no_spotdl": "🚫 <b>Spotdl not found... Check config or install spotdl (<code>.terminal pip install spotdl</code>)</b>",
"not_found": "🎧 <b>Music not found...</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_SPOTDL_PATH",
"~/.local/bin/spotdl",
lambda: self.strings("cfg_spotdl_path"),
)
async def spotdlcmd(self, message):
"""Download music from Spotify (Only tracks)"""
if not (args := utils.get_args_raw(message)):
return await utils.answer(message, self.strings["no_args"])
if "https://open.spotify.com/track/" not in args:
return await utils.answer(message, self.strings["no_track"])
# Try write command
await utils.answer(message, self.strings["downloading"])
proc = await asyncio.create_subprocess_shell(
self.config["CONFIG_SPOTDL_PATH"] + " " + args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# Pass one line
_ = await proc.stdout.readline()
# Get console strings
line = (await proc.stdout.readline()).decode().rstrip()
await proc.wait()
# Check "not found" error
err = await proc.stderr.readline()
if ": not found" in err.decode():
return await utils.answer(message, self.strings["no_spotdl"])
# Try get youtube video id
if "https://www.youtube.com/watch?v=" in line and len(line.split("https://www.youtube.com/watch?v=")) == 2:
photo_id = line.split("https://www.youtube.com/watch?v=")[1]
elif "as it's already downloaded" in line:
photo_id = None
else:
return await utils.answer(message, self.strings["not_found"])
# Get track name and send message
track_name = line.split('"')[1]
await self.inline.form(
text=line,
photo=f"https://img.youtube.com/vi/{photo_id}/maxresdefault.jpg" if photo_id else None,
message=message,
reply_markup=[{"text": "Upload", "callback": self.inline__upload, "args": (track_name, message.chat.id)}]
)
async def inline__upload(self, call, track_name, chat_id):
with open(track_name + ".mp3","rb",) as input_file:
content = input_file.read()
input_file.seek(0)
await self._client.send_file(
chat_id,
track_name + ".mp3"
)
os.remove(track_name + ".mp3")
await call.delete()

View File

@@ -0,0 +1,443 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 4, 5)
# requires: psutil py-cpuinfo
# meta pic: https://img.icons8.com/external-xnimrodx-lineal-color-xnimrodx/512/000000/external-pc-computer-xnimrodx-lineal-color-xnimrodx.png
# meta developer: @cakestwix_mods
# scope: inline
# scope: hikka_min 1.1.2
# For version info
import telethon
import aiogram
import git
import datetime
import logging
from typing import Union
import platform
import cpuinfo
import psutil
from aiogram.utils.markdown import quote_html
from os.path import exists
from .. import loader, utils
logger = logging.getLogger(__name__)
# https://www.adamsmith.haus/python/answers/how-to-remove-empty-lines-from-a-string-in-python
def remove_empty_lines(string_with_empty_lines):
lines = string_with_empty_lines.split("\n")
non_empty_lines = [line for line in lines if line.strip() != ""]
return "".join(line + "\n" for line in non_empty_lines)
backslash = "\n"
def get_os_release():
if not exists("/etc/os-release"):
return False
list_ = []
with open("/etc/os-release") as f:
list_.extend(item.split("=") for item in f.readlines())
return {item[0]: item[1].replace(backslash, "").replace('"', "") for item in list_}
# https://stackoverflow.com/questions/2756737/check-linux-distribution-name
def get_distro():
"""
Name of your Linux distro
"""
if not exists("/etc/issue"):
return False
with open("/etc/issue") as f:
return f.read().split()[0]
def progressbar(iteration: int, length: int) -> str:
percent = ("{0:." + str(1) + "f}").format(100 * (iteration / float(100)))
filledLength = int(length * iteration // 100)
return "" * filledLength + "" * (length - filledLength)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8K'
# >>> bytes2human(100001221)
# '95.4M'
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {s: 1 << (i + 1) * 10 for i, s in enumerate(symbols)}
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return "%.1f%s" % (value, s)
return "%sB" % n
@loader.tds
class InlineSystemInfoMod(loader.Module):
"""🖥 Get detailed information about your server"""
strings = {
"name": "🖥 InlineSystemInfo",
}
AddressFamily = {
2: "IPv4",
10: "IPv6",
28: "IPv6",
17: "Link",
18: "Link",
}
def menu_keyboard(self) -> list:
keyboard = [
[
{
"text": "😼 General",
"callback": self.change_stuff,
"args": ("General",),
}
],
]
keyboard.extend(
iter(
chunks(
[
{
"text": "🧠 CPU",
"callback": self.change_stuff,
"args": ("CPU",),
},
{
"text": "🐧 Linux",
"callback": self.change_stuff,
"args": ("Linux",),
},
{
"text": "🗄 Memory",
"callback": self.change_stuff,
"args": ("Memory",),
},
{
"text": "🌐 Network Address",
"callback": self.change_stuff,
"args": ("Network Address",),
},
{
"text": "🌐 Network Stats",
"callback": self.change_stuff,
"args": ("Network Stats",),
},
{
"text": "💽 Disk",
"callback": self.change_stuff,
"args": ("Disk",),
},
{
"text": "🌡 Sensors",
"callback": self.change_stuff,
"args": ("Sensors",),
},
{
"text": "🐍 Python",
"callback": self.change_stuff,
"args": ("Python",),
}
],
3,
)
)
)
keyboard.append([{"text": "🚫 Close", "callback": self.inline__close}])
try:
return keyboard[3].remove([])
except ValueError:
return keyboard
def general_info(self):
string = "😼 <b>System Info</b>\n"
string += f" ├──<b>CPU Name</b>: <code>{self.cpu_info.get('brand_raw', 'Undetermined.')}</code> {self.cpu_count_logic}/{self.cpu_count} ({self.cpu_info['arch_string_raw']})\n"
string += f" ├──<b>RAM</b>: {progressbar(self.virtual_memory.percent, 10)} <code>({bytes2human(self.virtual_memory.used)}/{bytes2human(self.virtual_memory.total)})</code>\n"
string += f" └──<b>Swap</b>: {progressbar(self.swap_memory.percent, 10)} <code>({bytes2human(self.swap_memory.used)}/{bytes2human(self.swap_memory.total)})</code>\n\n"
string += "🐧 <b>Linux Info</b>\n"
string += f" ├──<b>Name</b>: <code>{get_distro()}</code>\n"
string += f" └──<b>Kernel</b>: <code>{platform.release()}</code>\n\n"
if hasattr(self, "disk_partitions"):
for disk_root in psutil.disk_partitions("/"):
if disk_root.mountpoint == '/':
disk_usage = psutil.disk_usage(disk_root.mountpoint)
string += "💽 <b>Disk Info</b> <code>(/)</code>\n"
string += f" └──<b>{disk_root.device}</b>\n"
string += f" ├── <b>Mount</b> {disk_root.mountpoint}\n"
string += f" ├── <b>FS</b> {disk_root.fstype}\n"
string += f" ├── <b>Disk Usage</b> {disk_usage.percent}% ({bytes2human(disk_usage.used)}/{bytes2human(disk_usage.total)})\n"
string += f" │ └──{progressbar(disk_usage.percent, 10)}\n"
string += f" └── <b>Options</b> {disk_root.opts}\n\n"
return string
def cpu_string(self):
string = "🧠 <b>CPU Info</b>\n"
string += f"⦁ <b>Name</b>: {self.cpu_info.get('brand_raw', 'Undetermined.')} ({self.cpu_info['arch_string_raw']})\n"
string += f"⦁ <b>Count</b>: {self.cpu_count_logic} ({self.cpu_count})\n"
string += (
f"⦁ <b>Freq</b>: {self.cpu_freq[0]} (max: {self.cpu_freq[2]} / min: {self.cpu_freq[1]})\n"
if hasattr(self, "cpu_freq") and self.cpu_freq
else ""
)
string += f"⦁ <b>Flags</b>: {' '.join(self.cpu_info.get('flags', 'No flags'))}\n"
string += (
f"⦁ <b>Load avg</b>: {self.loadavg[0]} {self.loadavg[1]} {self.loadavg[2]}\n"
if hasattr(self, "loadavg")
else ""
)
return string
def disks_string(self):
if not hasattr(self, "disk_partitions"):
return None
string = "💽 <b>Disk Info</b>\n"
for disk in self.disk_partitions:
disk_usage = psutil.disk_usage(disk.mountpoint)
string += f"<b>{disk.device}</b>\n"
string += f"├── <b>Mount</b> {disk.mountpoint}\n"
string += f"├── <b>FS</b> {disk.fstype}\n"
string += f"├── <b>Disk Usage</b> {disk_usage.percent}% ({bytes2human(disk_usage.used)}/{bytes2human(disk_usage.total)})\n"
string += f"│ └──{progressbar(disk_usage.percent, 10)}\n"
string += f"└── <b>Options</b> {disk.opts}\n\n"
return string
def network_addr_string(self):
if not hasattr(self, "net_if_addrs"):
return None
string = "🌐 <b>Network Info</b>\n"
string += "<b>Address</b>:\n"
for interf in self.net_if_addrs:
interface = self.net_if_addrs[interf]
string += f"<b>{interf}</b>\n"
for addr in interface:
attr = [
a
for a in dir(psutil.net_if_addrs()[interf][0])
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(psutil.net_if_addrs()[interf][0], a))
]
string += f"{self.AddressFamily[getattr(addr, 'family')]}\n"
for item in attr[:-1]:
string += f"├── {item}: {getattr(addr, item)}\n"
string += f"└── {attr[-1]}: {getattr(addr, attr[-1])}\n"
string += "\n"
return string
def memory_string(self):
string = "🗄 <b>Memory Info</b>\n"
string += f"<b>RAM</b>: {progressbar(self.virtual_memory.percent, 10)} <code>({bytes2human(self.virtual_memory.used)}/{bytes2human(self.virtual_memory.total)})</code>\n"
string += f"<b>Swap</b>: {progressbar(self.swap_memory.percent, 10)} <code>({bytes2human(self.swap_memory.used)}/{bytes2human(self.swap_memory.total)})</code>\n"
return string
def sensors_string(self):
string = None
if hasattr(self, "sensors_temperatures"):
string = "🌡 <b>Sensors Info</b>\n" + "<b>Temperature</b>:\n"
for sensor_name in self.sensors_temperatures:
sensor = self.sensors_temperatures[sensor_name]
string += f"<b>{sensor_name}</b>\n"
for sensor_info in sensor:
attr = [
a
for a in dir(sensor_info)
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(sensor_info, a))
]
for item in attr[:-1]:
string += f"├── {item}: {getattr(sensor_info, item)}\n"
string += f"└── {attr[-1]}: {getattr(sensor_info, attr[-1])}\n"
string += "\n"
if hasattr(self, "sensors_fans"):
string += "<b>Fans</b>:"
for sensor_name in self.sensors_fans:
sensor = self.sensors_fans[sensor_name]
string += f"<b>{sensor_name}</b>\n"
for sensor_info in sensor:
attr = [
a
for a in dir(sensor_info)
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(sensor_info, a))
]
for item in attr[:-1]:
string += f"├── {item}: {getattr(sensor_info, item)}\n"
string += f"└── {attr[-1]}: {getattr(sensor_info, attr[-1])}\n"
return string
def network_stats_string(self):
if not hasattr(self, "net_if_stats"):
return None
string = "🌐 <b>Network Info</b>\n" + "<b>Stats</b>:\n"
for interf in self.net_if_stats:
interface = self.net_if_stats[interf]
string += f"<b>{interf}</b>\n"
string += f"└── {quote_html(interface)}\n\n"
return string
def linux_string(self):
os_release = get_os_release()
string = f"""🐧 <b>Linux Info</b>
Name: {get_distro()}
Kernel: {platform.release()}
Hostname: {platform.node()}
{f'glibc ver: {platform.glibc()[1]}' if hasattr(platform, 'glibc') else ''}
Boot time: {self.boot_time if hasattr(self, "boot_time") else "Termux moment"}
"""
if os_release:
string += f"""<b>\n /etc/os-releases Info:</b>
Pretty Name: {os_release["PRETTY_NAME"]}
Name: {os_release["NAME"]}
Version: {os_release.get("VERSION", "Not available")}
Documentation: {os_release.get("DOCUMENTATION_URL", "Not available")}
Support: {os_release.get("SUPPORT_URL", "Not available")}
Bug Report: {os_release["BUG_REPORT_URL"]}
"""
return remove_empty_lines(string)
def python_string(self):
string = "🐍 <b>Python Info</b>\n"
string += f" ├──<b>Version</b>: <code>{platform.python_version()}</code>\n"
string += f" ├──<b>Version (More details)</b>: <code>{cpuinfo.get_cpu_info()['python_version']}</code>\n"
string += f" └──<b>Python Packages version</b>\n"
string += f" ├──<b>Telethon</b>: <code>{telethon.__version__}</code>\n"
string += f" ├──<b>AIOgram</b>: <code>{aiogram.__version__}</code>\n"
string += f" ├──<b>Cpuinfo</b>: <code>{cpuinfo.get_cpu_info()['cpuinfo_version_string']}</code>\n"
string += f" ├──<b>psutil</b>: <code>{psutil.__version__}</code>\n"
string += f" └──<b>git</b>: <code>{git.__version__}</code>\n"
return string
def __init__(self):
# CPU stuff
self.cpu_count_logic = psutil.cpu_count()
self.cpu_count = psutil.cpu_count(logical=False)
try:
self.cpu_freq = psutil.cpu_freq()
except FileNotFoundError:
pass
self.cpu_info = cpuinfo.get_cpu_info()
# Network
try:
self.net_if_addrs = psutil.net_if_addrs()
self.net_if_stats = psutil.net_if_stats()
except PermissionError:
pass
def update_data(self):
# Memory
self.virtual_memory = psutil.virtual_memory()
self.swap_memory = psutil.swap_memory()
# Sensors
if hasattr(psutil, "sensors_temperatures"):
self.sensors_temperatures = psutil.sensors_temperatures()
if hasattr(psutil, "sensors_fans"):
self.sensors_fans = psutil.sensors_fans()
# self.sensors_battery = psutil.sensors_battery()
# CPU stuff
self.cpu_percent = psutil.cpu_percent(interval=None)
# Linux stuff
self.loadavg = psutil.getloadavg()
# Disks
try:
self.disk_partitions = psutil.disk_partitions()
except PermissionError:
pass
# Other
self.boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(
"%Y-%m-%d %H:%M:%S"
)
# Generate string
self.info_string = {
"General": self.general_info(),
"CPU": self.cpu_string(),
"Disk": self.disks_string(),
"Network Address": self.network_addr_string(),
"Network Stats": self.network_stats_string(),
"Memory": self.memory_string(),
"Sensors": self.sensors_string(),
"Linux": self.linux_string(),
"Python": self.python_string(),
}
async def client_ready(self, client, db) -> None:
if utils.get_platform_name() == '🕶 Termux':
raise loader.LoadError("No Termux support. Change your host")
async def systeminfocmd(self, message):
"""Get information about your server"""
await utils.run_sync(self.update_data)
await self.inline.form(
text=self.general_info(),
message=message,
reply_markup=self.menu_keyboard(),
)
# Inline callback
async def change_stuff(self, call, stuff):
if self.info_string[stuff] != None:
await call.edit(text=self.info_string[stuff], reply_markup=self.menu_keyboard())
else:
await call.answer("No data :(")
async def inline__close(self, call) -> None:
await call.delete()

View File

@@ -0,0 +1,337 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 0)
# requires: aiohttp timeago
# meta pic: https://b.thumbs.redditmedia.com/-cDkj6PuQHqdLEhPh1JYsYplTArOOUuBnKs5FC8sgKs.png
# meta developer: @cakestwix_mods
# scope: inline
import logging
import uuid
from datetime import datetime
from typing import Union
import aiohttp
import timeago
from .. import loader, utils # noqa
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
@loader.tds
class InlineWynnCraftInfoMod(loader.Module):
"""A module for displaying player information on the WynnCraft rpg server"""
strings = {
"name": "InlineWynnCraft",
"error_message": "🚫 This entity does not exist or you entered it incorrectly",
"about_user": "<b>Available player information</b> <code>{}</code> {}\n",
"rank_user": "<b>Rank</b>: ",
"last_join_user": "\n<b>Last Seen</b>: ",
"first_join_user": "\n<b>First Join</b>: ",
"professions_user": "\n<b>Professions</b>: ",
"guild_user": "\n<b>Guild</b>: {} ({})",
"general_info_user": "\n\n👉 <b>General Information</b>",
"chestsFound": "\n 🔍 <b>Chests Found</b>: ",
"blocksWalked": "\n 🚶‍♀️ <b>Walked blocks</b>: ",
"mobsKilled": "\n 🐗 <b>Mobs Killed</b>: ",
"itemsIdentified": "\n 🧰 <b>Items analyzed</b>: ",
"logins": "\n 🎟 <b>Logins</b>: ",
"discoveries": "\n 🔎 <b>Discoveries</b>: ",
"dungeons": "\n 🪨 <b>Dungeons</b>: ",
"raids": "\n ⚔️ <b>Raids</b>: ",
"quests": "\n 📕 <b>Quests</b>: ",
"eventsWon": "\n 🎊 <b>Events Won</b>: ",
"pvp_user": "\n\n🗡 <b>PVP</b>: ",
"deaths": "\n ☠️ <b>Deaths</b>: ",
"kills": "\n ⚔️ <b>Kills</b>: ",
"completed": "\n✅ <b>Completed</b>",
"skills": "\n\n🔧 <b>Skills</b>",
"strength": "\n 💪 <b>Strength</b>: ",
"dexterity": "\n 💨 <b>Dexterity</b>: ",
"intelligence": "\n 🧐 <b>Intelligence</b>: ",
"defense": "\n 🧱 <b>Defence</b>: ",
"defence": "\n 🛡 <b>Defence</b>: ",
"agility": "\n 🤸‍♂️ <b>Agility</b>: ",
"professions": "\n\n👷‍♀️ <b>Professions</b>: ",
"alchemism": "\n 💧 <b>Alchemism</b>: ",
"armouring": "\n 🛡 <b>Armouring</b>: ",
"combat": "\n ⚔️ <b>Combat</b>: ",
"cooking": "\n 🍽 <b>Cooking</b>: ",
"farming": "\n 🌾️ <b>Farming</b>: ",
"fishing": "\n 🎣 <b>Fishing</b>: ",
"jeweling": "\n 💎 <b>Jeweling</b>: ",
"mining": "\n ⛏ <b>Mining</b>: ",
"scribing": "\n 🖋 <b>Scribing</b>: ",
"tailoring": "\n 🪡 <b>Tailoring</b>: ",
"weaponsmithing": "\n 🗡️ <b>Weaponsmithing</b>: ",
"woodcutting": "\n 🪓 <b>Woodcutting</b>: ",
"woodworking": "\n 🌳️ <b>Woodworking</b>: ",
"btn_back": "Back",
"btn_close": "Close",
"top_list": "<b>Top list:</b>",
}
strings_ru = {
"error_message": "🚫 Этот объект не существует или вы ввели его неправильно",
"about_user": "<b>Доступная информация об игроке</b> <code>{}</code> {}\n",
"rank_user": "<b>Ранг</b>: ",
"last_join_user": "\n<b>Последнее посещение</b>: ",
"first_join_user": "\n<b>Первое присоединение</b>: ",
"professions_user": "\n<b>Профессии</b>: ",
"guild_user": "\n<b>Гильдия</b>: {} ({})",
"general_info_user": "\n\n👉 <b>Главная Информация</b>",
"chestsFound": "\n 🔍 <b>Найдено сундуков</b>: ",
"blocksWalked": "\n 🚶‍♀️ <b>Пройдено блоков</b>: ",
"mobsKilled": "\n 🐗 <b>Мобов убито</b>: ",
"itemsIdentified": "\n 🧰 <b>Проанализировано предметов</b>: ",
"logins": "\n 🎟 <b>Заходил на сервер</b>: ",
"discoveries": "\n 🔎 <b>Открытий</b>: ",
"dungeons": "\n 🪨 <b>Подземелья</b>: ",
"raids": "\n ⚔️ <b>Рейды</b>: ",
"quests": "\n 📕 <b>Квесты</b>: ",
"eventsWon": "\n 🎊 <b>Выигранные события</b>: ",
"pvp_user": "\n\n🗡 <b>PVP</b>: ",
"deaths": "\n ☠️ <b>Смертей</b>: ",
"kills": "\n ⚔️ <b>Убийств</b>: ",
"completed": "\n✅ <b>Завершено</b>",
"skills": "\n\n🔧 <b>Навыки</b>",
"strength": "\n 💪 <b>Прочность</b>: ",
"dexterity": "\n 💨 <b>Ловкость</b>: ",
"intelligence": "\n 🧐 <b>Интеллект</b>: ",
"defense": "\n 🧱 <b>Оборона</b>: ",
"defence": "\n 🛡 <b>Защита</b>: ",
"agility": "\n 🤸‍♂️ <b>Ловкость</b>: ",
"professions": "\n\n👷‍♀️ <b>Профессии</b>: ",
"alchemism": "\n 💧 <b>Алхимизм</b>: ",
"armouring": "\n 🛡 <b>Бронирование</b>: ",
"combat": "\n ⚔️ <b>Бой</b>: ",
"cooking": "\n 🍽 <b>Готовка</b>: ",
"farming": "\n 🌾️ <b>Сельское хозяйство</b>: ",
"fishing": "\n 🎣 <b>Рыбалка</b>: ",
"jeweling": "\n 💎 <b>Ювелирное дело</b>: ",
"mining": "\n ⛏ <b>Добыча</b>: ",
"scribing": "\n 🖋 <b>Скрайбирование</b>: ",
"tailoring": "\n 🪡 <b>Портняжное дело</b>: ",
"weaponsmithing": "\n 🗡️ <b>Оружейное дело</b>: ",
"woodcutting": "\n 🪓 <b>Резьба по дереву</b>: ",
"woodworking": "\n 🌳️ <b>Деревообработка</b>: ",
"btn_back": "Назад",
"btn_close": "Закрыть",
"top_list": "<b>Топ:</b>",
}
base_url = "https://mc-heads.net/minecraft/profile/"
wynncraft_api = "https://api.wynncraft.com/v2/"
def general_info_builder(self, user) -> str:
text = self.strings["about_user"].format(
f'🟢 ({user["meta"]["location"]["server"]})'
if user["meta"]["location"]["online"]
else "🔴",
user["username"],
)
text += (
self.strings["rank_user"]
+ user["rank"]
+ (
f' ({user["meta"]["tag"]["value"]})'
if user["meta"]["tag"]["value"]
else ""
)
)
# Guild
text += (
self.strings["guild_user"].format(
user["guild"]["name"], user["guild"]["rank"]
)
if user["guild"]["name"]
else ""
)
text += self.strings["last_join_user"] + timeago.format(
datetime.strptime(user["meta"]["lastJoin"][:-5], "%Y-%m-%dT%H:%M:%S"),
datetime.now(),
)
text += self.strings["first_join_user"] + timeago.format(
datetime.strptime(user["meta"]["firstJoin"][:-5], "%Y-%m-%dT%H:%M:%S"),
datetime.now(),
)
# Global stuff
text += self.strings["general_info_user"]
for general_stuff in user["global"]:
if general_stuff in ["pvp", "totalLevel"]:
continue
text += (
self.strings[general_stuff]
+ f"<code>{user['global'][general_stuff]}</code>"
)
# PvP
text += self.strings["pvp_user"]
text += self.strings["kills"] + f"<code>{user['global']['pvp']['kills']}</code>"
text += (
self.strings["deaths"] + f"<code>{user['global']['pvp']['deaths']}</code>"
)
return text
def class_info_builder(self, class_) -> str:
text = self.strings["about_user"].format(
"".join([i for i in class_["name"].title() if not i.isdigit()]),
f"[{class_['level']}]",
)
# Completed stuff
text += self.strings["completed"]
for some_item in class_:
if some_item not in ["dungeons", "raids", "quests"]:
continue
text += (
self.strings[some_item]
+ f"<code>{class_[some_item]['completed']}</code>"
)
# Some stuff
text += self.strings["general_info_user"]
for some_item in class_:
if some_item in [
"itemsIdentified",
"mobsKilled",
"chestsFound",
"blocksWalked",
"logins",
"discoveries",
"eventsWon",
]:
text += self.strings[some_item] + f"<code>{class_[some_item]}</code>"
# PvP
text += self.strings["pvp_user"]
text += self.strings["kills"] + f"<code>{class_['pvp']['kills']}</code>"
text += self.strings["deaths"] + f"<code>{class_['pvp']['deaths']}</code>"
# Skills stuff
text += self.strings["skills"]
for skill in class_["skills"]:
text += self.strings[skill] + f"<code>{class_['skills'][skill]}</code>"
# Professions stuff
text += self.strings["professions"]
for skill in class_["professions"]:
text += self.strings[skill] + f"<code>{class_['professions'][skill]['level']} ({class_['professions'][skill]['xp']})</code>"
return text
def keyboard_class_builder(self, user):
return [
{
"text": f'[{class_["level"]}] {"".join([i for i in class_["name"].title() if not i.isdigit()])}',
"callback": self.inline__get_class,
"args": [class_, user],
}
for class_ in user["classes"]
]
async def wucheckcmd(self, message):
"""Check user by username"""
if not (args := utils.get_args_raw(message)):
return
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}{args}") as get:
if get.status != 200:
return await utils.answer(message, self.strings["error_message"])
uuid_str = (await get.json())["id"]
# Get info about user
async with session.get(
self.wynncraft_api + "player/{}/stats".format(uuid.UUID(hex=uuid_str))
) as get:
logger.debug(str(await get.json()))
if (await get.json())["code"] != 200:
return await utils.answer(message, self.strings["error_message"])
user = (await get.json())["data"][0]
await self.inline.form(
text=self.general_info_builder(user),
message=message,
reply_markup=chunks(self.keyboard_class_builder(user), 3),
photo=f"https://wynndata.tk/gen/stats/{args}.png",
force_me=False, # optional: Allow other users to access form (all)
)
async def wplayertopcmd(self, message):
"""Top players"""
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.wynncraft_api}leaderboards/player/overall/all") as get:
if get.status != 200:
return await utils.answer(message, self.strings["error_message"])
top_list = list(reversed(chunks((await get.json())["data"],10))) # oh no, cringe code
string = f"{self.strings['top_list']}\n\n"
for player in reversed(top_list[0]):
string += f"╭ <b>{player['name']} 🎮\n"
string += f"╰─ </b> LvL: <code>{player['level']}</code> / XP: <code>{player['xp']}</code> / Time: <code>{player['minPlayed']}</code>\n"
await self.inline.form(text=string, message=message, reply_markup=chunks([{"text": str(i + 1), "callback": self.inline__toplayer, "args": (top_list, i),} for i in range(10)], 5), force_me=False)
async def inline__toplayer(self, call, top_list: list, num: int):
string = f"{self.strings['top_list']}\n\n"
for player in reversed(top_list[num]):
string += f"╭ <b>{player['name']} 🎮\n"
string += f"╰─ </b> LvL: <code>{player['level']}</code> / XP: <code>{player['xp']}</code> / Time: <code>{player['minPlayed']}</code>\n"
await call.edit(text=string, reply_markup=chunks([{"text": str(i + 1), "callback": self.inline__toplayer, "args": (top_list, i),} for i in range(10)], 5), force_me=False)
async def inline__get_class(self, call, class_, player):
await call.edit(
text=self.class_info_builder(class_),
reply_markup=[
{
"text": self.strings["btn_back"],
"callback": self.inline__back,
"args": [player],
}
],
)
async def inline__back(self, call, player):
await call.edit(
text=self.general_info_builder(player),
reply_markup=chunks(self.keyboard_class_builder(player), 3),
)

View File

@@ -0,0 +1,211 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 3)
# meta pic: https://img.icons8.com/bubbles/512/000000/youtube-play.png
# meta developer: @cakestwix_mods
# requires: yt_dlp aiohttp
# scope: hikka_min 1.1.11
# scope: hikka_only
import asyncio
import logging
import aiohttp
import os
from yt_dlp.utils import DownloadError
import yt_dlp
from telethon.tl.types import Message
from telethon import functions, types
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
def bytes2human(num, suffix="B"):
if not num:
return 0
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
def progressbar(iteration: int, length: int) -> str:
percent = ("{0:." + str(1) + "f}").format(100 * (iteration / float(100)))
filledLength = int(length * iteration // 100)
return "" * filledLength + "" * (length - filledLength)
@loader.tds
class YouTubeMod(loader.Module):
"""Download YouTube videos with video and audio quality selection"""
strings = {
"name": "InlineYouTube",
"args": "🎞 <b>You need to specify link</b>",
"downloading": "🎞 <b>Downloading...</b>",
"not_found": "🎞 <b>Video not found...</b>",
"no_qualt":"No quality",
"format": "<b>Format</b>:",
"ext": "<b>Ext</b>:",
"video_codec": "<b>Video codec</b>:",
"audio": "Audio",
"file_size": "<b>File size</b>:",
"uploading": "🎞 <b>Uploading File...</b>",
"getting_info": " <b>Getting information about the video...</b>",
}
strings_ru = {
"name": "InlineYouTube",
"args": "🎞 <b>Вам необходимо указать ссылку</b>",
"downloading": "🎞 <b>Скачиваю...</b>",
"not_found": "🎞 <b>Видео не найдено...</b>",
"no_qualt":"Нету такого качества",
"format": "<b>Формат</b>:",
"ext": "<b>Расширение</b>:",
"video_codec": "<b>Видео кодек</b>:",
"audio": "Аудио",
"file_size": "<b>Размер</b>:",
"uploading": "🎞 <b>Загружаю...</b>",
"getting_info": " <bПолучаю информацию про видео...</b>",
}
async def client_ready(self, client, db):
self._db = db
self._client = client
@loader.unrestricted
async def ytcmd(self, message: Message):
"""[quality(144p/720p/etc)] <link> - Download video from youtube"""
args = utils.get_args(message)
await utils.answer(message, self.strings("getting_info"))
if not args:
return await utils.answer(message, self.strings("args"))
with yt_dlp.YoutubeDL() as ydl:
try:
info_dict = ydl.extract_info(
args[1] if len(args) >= 2 else args[0], download=False
)
except DownloadError as e:
return await utils.answer(message, e.msg)
formats_list = [{"text": f"{item['format_note']} ({item['video_ext']})", "callback": self.format_change, "args": (item, info_dict, message.chat.id, item["format_id"],),} for item in info_dict["formats"] if item["ext"] in ["mp4", "webm"] and item["vcodec"] != "none" and (len(args) >= 2 and args[0] == item["format_note"] or len(args) < 2)]
caption = f"<b>{info_dict['title']}</b>\n\n"
# caption += info_dict["description"]
await self.inline.form(text=caption if formats_list else self.strings["no_qualt"], photo=f"https://img.youtube.com/vi/{info_dict['id']}/0.jpg", message=message, reply_markup=utils.chunks(formats_list, 2))
async def format_change(
self,
call: InlineCall,
quality: dict,
info_dict: dict,
chat_id: int,
format_id: int):
string = f"{self.strings['format']} {quality['format']}\n"
string += f"{self.strings['ext']} {quality['ext']}\n"
string += f"{self.strings['video_codec']} {quality['vcodec']}\n"
string += f"{self.strings['file_size']} {bytes2human(quality['filesize'])}\n"
audio_keyboard = [{"text": f"{self.strings['audio']} ({audio['format_note']})", "callback": self.download, "args": (info_dict["id"], quality["ext"], quality["format_id"], audio["format_id"], chat_id,),} for audio in info_dict["formats"] if audio["ext"] == "m4a"]
audio_keyboard.append(
{
"text": "Back",
"callback": self.back,
"args": (
info_dict,
chat_id,
),
},
)
await call.edit(
text=string,
reply_markup=audio_keyboard,
)
async def back(self, call: InlineCall, info_dict: dict, chat_id: int):
formats_list = [{"text": f"{item['format_note']} ({item['video_ext']})", "callback": self.format_change, "args": (item, info_dict, chat_id, item["format_id"]),} for item in info_dict["formats"] if item["ext"] in ["mp4", "webm"] and item["vcodec"] != "none"]
caption = f"<b>{info_dict['title']}</b>\n\n"
# caption += info_dict["description"]
await call.edit(text=caption, reply_markup=utils.chunks(formats_list, 2))
async def download(
self,
call: InlineCall,
video_id: str,
ext: str,
video_format: int,
audio_format: int,
chat_id: int,
):
meta = {}
def download():
nonlocal meta
with yt_dlp.YoutubeDL(
{
"format": "{}+{}".format(str(video_format), str(audio_format)),
"outtmpl": "%(resolution)s.%(id)s.%(ext)s",
}
) as yd:
meta = yd.extract_info(
"https://www.youtube.com/watch?v=" + video_id, download=False
)
yd.download("https://www.youtube.com/watch?v=" + video_id)
await call.edit(
text=f"{self.strings['downloading']}",
)
await utils.run_sync(download)
await call.edit(
text=f"{self.strings['uploading']}",
)
# Download thumb for video
async with aiohttp.ClientSession() as session:
async with session.get(f"https://img.youtube.com/vi/{meta['id']}/0.jpg") as resp:
with open(meta['id'] + ".jpg", 'wb') as fd:
async for chunk in resp.content.iter_chunked(512):
fd.write(chunk)
await self._client.send_file(
chat_id,
"{0}x{1}.{2}.{3}".format(
(meta["width"]),
(meta["height"]),
(meta["id"]),
(meta["ext"].replace("webm", "mkv")),
),
supports_streaming=True,
thumb=meta["id"] + ".jpg"
)
os.remove(
"{0}x{1}.{2}.{3}".format(
(meta["width"]),
(meta["height"]),
(meta["id"]),
(meta["ext"].replace("webm", "mkv")),
)
)
os.remove(meta["id"] + ".jpg")
await call.delete()

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Friendly UserBot Modules
Copyright (C) 2021 CakesTwix
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) 2021 CakesTwix
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,5 @@
# Friendly Telegram / GeekTG Modules
Channel - https://t.me/cakestwix_mods
Author - @CakesTwix

View File

@@ -0,0 +1,71 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: aiohttp
# meta pic: https://www.pngall.com/wp-content/uploads/12/Avatar-Transparent.png
# meta developer: @cakestwix_mods
import logging
from .. import loader, utils
import aiohttp
logger = logging.getLogger(__name__)
@loader.tds
class RandomPeopleMod(loader.Module):
"""Create your new identity"""
strings = {
"name": "RandomPeople",
"id":"Id",
"uuid":"UUID",
"firstname":"Firstname",
"lastname":"Lastname",
"username":"Username",
"password":"Password",
"email":"Email",
"ip":"IP",
"macAddress":"MAC-address",
"website":"Website",
"image":"Image",
}
strings_ru = {
"name": "RandomPeople",
"id":"Id",
"uuid":"UUID",
"firstname":"Имя",
"lastname":"Фамилия",
"username":"Юзернейм",
"password":"Пароль",
"email":"Почта",
"ip":"IP",
"macAddress":"MAC-адрес",
"website":"Сайт",
"image":"Фото",
}
async def prandomcmd(self, message):
"""Get random people"""
async with aiohttp.ClientSession() as session:
async with session.get("https://fakerapi.it/api/v1/users?_quantity=1") as get:
b = (await get.json())["data"][0]
await session.close()
string = "".join(f"<b>{self.strings[key]}</b>: <code>{val}</code>\n" for val, key in zip(b.values(), b.keys()))
await utils.answer(message, string)

View File

@@ -0,0 +1,119 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 1)
# requires: torch
# meta pic: https://cdn.pixabay.com/photo/2017/07/09/20/48/speaker-2488096_1280.png
# meta developer: @cakestwix_mods
# scope: hikka_only
import os
import re
import torch
import logging
from .. import loader, utils
import aiohttp
logger = logging.getLogger(__name__)
device = torch.device("cpu")
torch.set_num_threads(4)
@loader.tds
class SileroMod(loader.Module):
"""Silero Models: pre-trained speech-to-text, text-to-speech and text-enhancement models made embarrassingly simple"""
strings = {
"name": "Silero",
"cfg_as_audio_note": "Send audio as a voice message",
"cfg_rate": "Sound frequency",
"no_avx2": "Your server does not support AVX2 instructions.",
}
strings_ru = {
"name": "Silero",
"cfg_as_audio_note": "Отправлять аудио как голосовые сообщения",
"cfg_rate": "Частота звука",
"no_avx2": "Твой сервер не поддерживает AVX2 инструкции",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_AS_AUDIO_NOTE",
True,
lambda: self.strings("cfg_as_audio_note"),
"CONFIG_RATE",
48000,
lambda: self.strings("cfg_rate"),
)
async def client_ready(self, client, db) -> None:
with open("/proc/cpuinfo") as f:
if 'avx2' not in f.read():
raise loader.LoadError(self.strings["no_avx2"])
if not os.path.isfile(os.path.abspath(os.getcwd()) + "/assets/model.pt"):
torch.hub.download_url_to_file(
"https://models.silero.ai/models/tts/ru/ru_v3.pt", "assets/model.pt"
)
self.model = torch.package.PackageImporter("assets/model.pt").load_pickle(
"tts_models", "model"
)
self.model.to(device)
async def send_audio(self, text: str, speaker: str, message):
audio_paths = self.model.save_wav(
text=text, speaker=speaker, sample_rate=self.config["CONFIG_RATE"]
)
with open(audio_paths, "rb") as audio_file:
content = audio_file.read()
audio_file.seek(0)
await self._client.send_file(
message.chat.id,
audio_file,
voice_note=self.config["CONFIG_AS_AUDIO_NOTE"],
reply_to=await message.get_reply_message()
)
async def sxeniacmd(self, message):
"""From text to sound (xenia)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "xenia", message)
async def saidarcmd(self, message):
"""From text to sound (aidar)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "aidar", message)
async def sbayacmd(self, message):
"""From text to sound (baya)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "baya", message)
async def skseniyacmd(self, message):
"""From text to sound (kseniya)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "kseniya", message)
async def srandomcmd(self, message):
"""From text to sound (random)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "random", message)

View File

@@ -0,0 +1,106 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# meta developer: @cakestwix_mods
# meta pic: https://img.icons8.com/officel/16/000000/broken-link.png
from .. import loader
import re
import logging
from telethon.tl.patched import Message
logger = logging.getLogger(__name__)
class NoLinksMod(loader.Module):
"""A simple link cleaner from your chats"""
strings = {"name": "SimpleNoLinks", "settings": "Setting for this chat", "add": "Add", "remove": "Remove"}
strings_ru = {"name": "SimpleNoLinks", "settings": "Настройка для данного чата", "add": "Добавить", "remove": "Убрать"}
async def linkcmd(self, message):
"""Configuration for chat"""
await self.inline.form(
message=message,
text=self.strings["settings"],
reply_markup=[
{
"text": self.strings["add"],
"callback": self.chat__callback,
"args": (
True,
message.chat.id,
),
}
]
if message.chat.id not in self.chats
else [
{
"text": self.strings["remove"],
"callback": self.chat__callback,
"args": (
False,
message.chat.id,
),
}
],
)
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
None if self._db.get(self.strings["name"], "chats") else self._db.set(
self.strings["name"], "chats", []
)
self.chats = self._db.get(self.strings["name"], "chats")
async def chat__callback(self, call, type_, id_):
if type_:
self.chats.append(id_)
else:
self.chats.remove(id_)
self._db.set(self.strings["name"], "chats", self.chats)
await call.edit(
text=self.strings["settings"],
reply_markup=[
{
"text": self.strings["add"],
"callback": self.chat__callback,
"args": (
True,
id_,
),
}
]
if id_ not in self.chats
else [
{
"text": self.strings["remove"],
"callback": self.chat__callback,
"args": (
False,
id_,
),
}
],
)
async def watcher(self, message):
if getattr(message, "sender_id", None) != self._client._tg_id and bool(
re.findall(
r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""",
message.text,
)
and message.chat.id in self.chats
):
await message.delete()

View File

@@ -0,0 +1,336 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: aiohttp
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://image.winudf.com/v2/image/cnUucmFkaWF0aW9ueC5hbmlsaWJyaWEuYXBwX2ljb25fMTUyODYyNzQ2NV8wMjY/icon.png?w=&fakeurl=1
# meta developer: @cakestwix_mods
from .. import loader, main
from ..inline import GeekInlineQuery, rand
from aiogram.types import InlineQueryResultPhoto, CallbackQuery
import aiohttp
import logging
from requests import post
import datetime
logger = logging.getLogger(__name__)
@loader.tds
class AniLibriaMod(loader.Module):
"""A non-profit project for the dubbing and adaptation of foreign TV series, cartoons and anime"""
strings = {
"name": "AniLibria",
"cfg_mail": "Your mail from anilibria.tv",
"cfg_pass": "Your password from anilibria.tv",
"announce": "<b>Анонс</b> :",
"status": "<b>Статус</b> :",
"type": "<b>Тип</b> :",
"genres": "<b>Жанры</b> :",
"favorite": "<b>Избранное &lt;3</b> :", # &lt; == <
"season": "<b>Сезон</b> :",
"inline": "Взаимодействие с аниме {}",
}
link = "https://anilibria.tv"
api = "https://api.anilibria.tv/v2/"
getFavorites_api = (
"https://api.anilibria.tv/v2/getFavorites?session={}&limit=999&filter=id"
)
weekdays = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ", "ВС"]
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_MAIL",
None,
lambda m: self.strings("cfg_mail", m),
"CONFIG_PASS",
None,
lambda m: self.strings("cfg_pass", m),
)
# Try login and get cookies for some methods
self.logined = False
if (
self.config["CONFIG_MAIL"] is not None
and self.config["CONFIG_PASS"] is not None
):
self.login = post(
f"{self.link}/public/login.php",
data={
"mail": self.config["CONFIG_MAIL"],
"passwd": self.config["CONFIG_PASS"],
},
)
if self.login.cookies.values() != []:
self.logined = True
self.cookies = self.login.cookies.values()[0]
async def client_ready(self, client, db) -> None:
self._client = client
@loader.unrestricted
@loader.ratelimit
async def arandomcmd(self, message) -> None:
"""Возвращает случайный тайтл из базы"""
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getRandomTitle") as get:
anime_title = await get.json()
await session.close()
text = f"{anime_title['names']['ru']} | {anime_title['names']['en']} \n"
text += f"{self.strings['status']} {anime_title['status']['string']}\n\n"
text += f"{self.strings['type']} {anime_title['type']['full_string']}\n"
text += f"{self.strings['season']} {anime_title['season']['string']} {anime_title['season']['year']}\n"
text += f"{self.strings['genres']} {' '.join(anime_title['genres'])}\n\n"
# text += f"<code>{anime_title['description']}</code>\n\n"
text += f"{self.strings['favorite']} {anime_title['in_favorites']}"
kb = [
[
{
"text": "Ссылка",
"url": f"https://anilibria.tv/release/{anime_title['code']}.html",
}
]
]
if self.logined:
async with aiohttp.ClientSession() as session:
async with session.get(
self.getFavorites_api.format(self.cookies)
) as get:
favorite_list = await get.json()
await session.close()
ids_favorite = [_id["id"] for _id in favorite_list]
if anime_title["id"] in ids_favorite:
kb.append(
[
{
"text": "Убрать из избранного",
"callback": self.inline__favorite,
"args": [anime_title["id"], "delFavorite"],
}
]
)
else:
kb.append(
[
{
"text": "Добавить в избранное",
"callback": self.inline__favorite,
"args": [anime_title["id"], "addFavorite"],
}
]
)
kb.extend(
[
{
"text": f"{torrent['quality']['string']}",
"url": f"https://anilibria.tv/{torrent['url']}",
}
]
for torrent in anime_title["torrents"]["list"]
)
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await message.client.send_file(
message.chat_id,
self.link + anime_title["posters"]["original"]["url"],
caption=text,
)
await self.inline.form(
self.strings["inline"].format(anime_title["names"]["ru"]),
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def aschedulecmd(self, message) -> None:
"""
Получить список последних обновлений тайтлов
"""
selected_weekday = datetime.datetime.weekday(datetime.datetime.now())
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getSchedule") as get:
schedule_list = await get.json()
await session.close()
kb = [[]]
for day in schedule_list:
kb[0].append(
{
"text": f"[{self.weekdays[day['day']]}]"
if day["day"] == selected_weekday
else self.weekdays[day["day"]], # With [] if current weekday
"callback": self.inline__update_schedule,
"args": [day["day"]], # Number of the day
}
)
if day["day"] == selected_weekday:
text = "".join(
f"<b>{new_anime['names']['ru']}</b>\n" for new_anime in day["list"]
)
await self.inline.form(
"Актуальное расписание Либрии\n" + text,
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def asearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Возвращает список найденных по названию тайтлов
"""
text = query.args
if not text:
return
async with aiohttp.ClientSession() as session:
async with session.get(
self.api + f"searchTitles?search={text}&limit=10"
) as get:
search_list = await get.json()
await session.close()
inline_query = []
for anime in search_list:
text = f"{anime['names']['ru']} | {anime['names']['en']} \n"
text += f"{self.strings['status']} {anime['status']['string']}\n\n"
text += f"{self.strings['type']} {anime['type']['full_string']}\n"
text += f"{self.strings['season']} {anime['season']['string']} {anime['season']['year']}\n"
text += f"{self.strings['genres']} {' '.join(anime['genres'])}\n\n"
# text += f"<code>{anime['description']}</code>\n\n"
text += f"{self.strings['favorite']} {anime['in_favorites']}"
inline_query.append(
InlineQueryResultPhoto(
id=rand(20),
title=anime["names"]["ru"],
description=anime["type"]["full_string"],
caption=text,
thumb_url=f"{self.link}{anime['posters']['small']['url']}", # noqa
photo_url=f"{self.link}{anime['posters']['original']['url']}",
parse_mode="html",
)
)
await query.answer(
inline_query,
cache_time=0,
)
async def inline__close(self, call: CallbackQuery) -> None:
await call.delete()
async def inline__favorite(
self, call: CallbackQuery, _id: int, method: str
) -> None:
_id = str(_id)
async with aiohttp.ClientSession() as session:
# get anime by id for update buttons
async with session.get(f"{self.api}getTitle?id={_id}") as get:
anime_title = await get.json()
kb = [
[
{
"text": "Ссылка",
"url": f"https://anilibria.tv/release/{anime_title['code']}.html",
}
]
]
if method == "addFavorite":
async with session.put(
(self.api + f"{method}?session={self.cookies}&title_id={_id}")
) as get:
kb.append(
[
{
"text": "Убрать из избранного",
"callback": self.inline__favorite,
"args": [anime_title["id"], "delFavorite"],
}
]
)
else: # delFavorite
async with session.delete(
(self.api + f"{method}?session={self.cookies}&title_id={_id}")
) as get:
kb.append(
[
{
"text": "Добавить в избранное",
"callback": self.inline__favorite,
"args": [anime_title["id"], "addFavorite"],
}
]
)
kb.extend(
[
{
"text": f"{torrent['quality']['string']}",
"url": f"https://anilibria.tv/{torrent['url']}",
}
]
for torrent in anime_title["torrents"]["list"]
)
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await session.close()
await call.edit(
text="Взаимодействие с аниме " + anime_title["names"]["ru"],
reply_markup=kb,
)
async def inline__update_schedule(
self, call: CallbackQuery, day_inline: int
) -> None:
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getSchedule") as get:
schedule_list = await get.json()
await session.close()
kb = [[]]
for day in schedule_list:
kb[0].append(
{
"text": f"[{self.weekdays[day['day']]}]"
if day["day"] == day_inline
else self.weekdays[day["day"]], # With [] if current weekday
"callback": self.inline__update_schedule,
"args": [day["day"]], # Number of the day
}
)
if day["day"] == day_inline:
text = "".join(
f"<b>{new_anime['names']['ru']}</b>\n" for new_anime in day["list"]
)
await call.edit(
text="Актуальное расписание Либрии\n" + text,
reply_markup=kb,
)

View File

@@ -0,0 +1,81 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# meta pic: https://www.freeiconspng.com/uploads/facebook-circle-heart-love-png-4.png
# meta developer: @cakestwix_mods
import logging
import asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class CompliMod(loader.Module):
"""Send a compliment to a person"""
strings = {
"name": "Compliments",
"cfg_emoji":"Emoji at the end of the message",
"compliments_women":"умная хорошая милая добрая лучшая заботливая",
"compliments_man":"умный хороший милый добрый лучший заботливый",
}
strings_ru = {
"cfg_emoji":"Эмодзи в конце сообщения",
"compliments_women":"умная хорошая милая добрая лучшая заботливая",
"compliments_man":"умный хороший милый добрый лучший заботливый"
}
def __init__(self):
self.name = self.strings["name"]
self.config = loader.ModuleConfig(
"emoji",
"",
lambda: self.strings("cfg_emoji"),
)
self.gender = "women"
self.better = "Самая"
self.delay = 2
@loader.unrestricted
@loader.ratelimit
async def complicmd(self, message):
"""
Send a person compliments
.compli [delay] [man/women]
"""
if args := len(utils.get_args(message)) == 2 and utils.get_args(message):
try:
self.delay = int(args[0])
except:
pass
if "man" in args[1]:
self.gender = args[1]
self.better = "Самый"
elif args := utils.get_args(message):
try:
self.delay = int(args[0])
except:
if "man" in args[0]:
self.gender = args[0]
self.better = "Самый"
for compl in self.strings["compliments_" + self.gender].split():
message = await utils.answer(message, f"{self.better} {compl} {self.config['emoji']}")
await asyncio.sleep(self.delay)

View File

@@ -0,0 +1,266 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 0)
# requires: requests bs4 lxml
# meta pic: https://styles.redditmedia.com/t5_3htpk/styles/communityIcon_vlbulj1gn8l11.png
# meta developer: @cakestwix_mods
import logging
from requests import get
from .. import loader, utils
import asyncio
import aiohttp
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class CustomRomsMod(loader.Module):
"""Miscellaneous stuff for custom ROMs"""
strings = {
"name": "ROMs",
"download": "⬇️ <b>Download</b> :",
"no_device": "🚫 <b>No device.<b>",
"no_codename": "🚫 <b>Pls codename((<b>",
"general_error": "🚫 <b>Oh no, cringe, error<b>",
}
strings_ru = {
"download": "⬇️ <b>Скачать</b> :",
"no_device": "🚫 <b>Нет устройства.<b>",
"no_codename": "🚫 <b>Пжл коднейм((<b>",
"general_error": "🚫 <b>❗️Ашибка❗️<b>",
}
twrp_api = "https://dl.twrp.me/"
# ROMs
@loader.unrestricted
@loader.ratelimit
async def sakuracmd(self, message):
"""Project Sakura"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
"https://raw.githubusercontent.com/ProjectSakura/OTA/11/devices.json"
) as get:
data = await get.json()
await session.close()
for item in data:
if item["codename"] == device:
releases = f"Latest Project Sakura for {item['name']} ({item['codename']}) \n"
releases += f"👤 by {item['maintainer_name']} \n"
releases += f"{self.strings['download']} (https://projectsakura.xyz/download/#/{item['codename']}) \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def dotoscmd(self, message):
"""DotOS"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.droidontime.com/api/ota/{}".format(device)
) as get:
if get.ok:
data = await get.json()
else:
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
await session.close()
releases = f"<b>Latest DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
releases += f"👤 : {data['maintainerInfo']['name']} \n"
releases += f"🆚 : {data['latestVersion']} \n"
releases += f"{self.strings['download']} "
releases += f"<a href={data['releases'][0]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
releases += f" / <a href={data['releases'][1]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
await utils.answer(message, releases)
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def aexcmd(self, message):
"""AOSP Extended"""
args = utils.get_args(message)
if args:
device_codename = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get("https://api.aospextended.com/devices/") as get:
devices_json = await get.json()
for device in devices_json:
if device["codename"] == device_codename:
releases = f"Latest AOSP Extended for {device['brand']} {device['name']} ({device['codename']}) \n"
# releases += f"👤 by {device['maintainer_name']} \n"
releases += f"{self.strings['download']}"
for version in device["supported_versions"]:
async with session.get(
"https://api.aospextended.com/builds/{}/{}".format(
device_codename, version["version_code"]
)
) as get:
version_json = await get.json()
if "error" not in version_json:
releases += f" <a href={version_json[0]['download_link']}>{version['version_name']}</a> |"
await session.close()
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
# Recovery
@loader.unrestricted
@loader.ratelimit
async def twrpcmd(self, message):
"""TWRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
url = get(f"{self.twrp_api}{device}/")
if url.status_code == 404:
reply = f"`Couldn't find twrp downloads for {device}!`\n"
await utils.answer(message, reply)
await asyncio.sleep(5)
await message.delete()
return
page = BeautifulSoup(url.content, "lxml")
download = page.find("table").find_all("tr")
reply = f"『 Team Win Recovery Project for {device}: 』\n"
for item in download:
dl_link = f"{self.twrp_api}{item.find('a')['href']}"
dl_file = item.find("td").text
size = item.find("span", {"class": "filesize"}).text
reply += f"⦁ <a href={dl_link}>{dl_file}</a> - <tt>{size}</tt>\n"
await utils.answer(message, reply)
@loader.unrestricted
@loader.ratelimit
async def shrpcmd(self, message):
"""SHRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/SHRP-Devices/device_data/master/deviceData.json"
).json()
for item in data[:-1]:
if item["codeName"] == device:
releases = f"『 SkyHawk Recovery Project for {item['model']} ({device}): 』\n"
releases += f"👤 <b>by<b> {item['maintainer']} \n"
releases += f" <b>Version<b> : {item['currentVersion']} \n"
releases += f"{self.strings['download']} : <a href={item['latestBuild']}>SourceForge</a> \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def pbrpcmd(self, message):
"""PBRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://pitchblackrecovery.com/{device}/"
) as get:
pbrp_page = await get.text()
await session.close()
page = BeautifulSoup(pbrp_page, "lxml")
status_error = page.find("h1", class_="error-code")
if status_error is not None:
return # No device
main_info = page.find_all(
"h3", class_="elementor-heading-title elementor-size-default"
)
download_info = page.find(
"section",
class_="has_eae_slider elementor-section elementor-inner-section elementor-element elementor-element-714ebe14 elementor-section-boxed elementor-section-height-default elementor-section-height-default",
)
version = main_info[0].text
date = main_info[2].text
status = main_info[4].text
maintainer = main_info[6].text
file_size = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[1].text[10:]
md5 = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[2].text[4:]
sourceforge = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[0]["href"]
github = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[1]["href"]
releases = f"『 Pitch Black Recovery Project for ({device}): 』\n"
releases += f"👤 <b>by</b> {maintainer} \n"
releases += f" <b>Status</b> : {status} \n"
releases += f" <b>Version</b> : {version} \n"
releases += f" <b>Date</b> : {date} \n"
releases += f" <b>MD5</b> : {md5} \n"
releases += f" <b>Size</b> : {file_size} \n"
releases += f"{self.strings['download']} : <a href={sourceforge}>SourceForge</a> | <a href={github}>GitHub</a>\n"
await utils.answer(message, releases)
# Other
@loader.unrestricted
@loader.ratelimit
async def magiskcmd(self, message):
"""Magisk by topjohnwu"""
magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/"
magisk_dict = {
"𝗦𝘁𝗮𝗯𝗹𝗲": magisk_repo + "master/stable.json",
"𝗕𝗲𝘁𝗮": magisk_repo + "master/beta.json",
"𝗖𝗮𝗻𝗮𝗿𝘆": magisk_repo + "master/canary.json",
}
releases = "<code><i>𝗟𝗮𝘁𝗲𝘀𝘁 𝗠𝗮𝗴𝗶𝘀𝗸 𝗥𝗲𝗹𝗲𝗮𝘀𝗲:</i></code>\n\n"
for name, release_url in magisk_dict.items():
data = get(release_url).json()
releases += f'{name}: <a href={data["magisk"]["link"]}>APK v{data["magisk"]["version"]}</a> | <a href={data["magisk"]["note"]}>Changelog</a>\n'
await utils.answer(message, releases)

View File

@@ -0,0 +1,591 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 4, 1)
# requires: requests bs4 lxml
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://styles.redditmedia.com/t5_3htpk/styles/communityIcon_vlbulj1gn8l11.png
# meta developer: @cakestwix_mods
import asyncio
import logging
import aiohttp
from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InputTextMessageContent,
)
from aiogram.utils.markdown import hlink
from bs4 import BeautifulSoup
from requests import get
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class CustomRomsMod(loader.Module):
"""Miscellaneous stuff for custom ROMs"""
strings = {
"name": "InlineROMs",
"download": "⬇️ <b>Download</b> :",
"no_device": "<b>No device.</b>",
"no_device_info": " Please check the correct codename or availability of the site",
"no_codename": "<b>Pls codename((</b>",
"write_codename": "Write the code name of your device",
"latest_releases": " Latest {} releases",
"latest_releases_no_format": " Latest ROM releases",
"latest_releases_device": " Latest {} {} releases for {}",
"gapps_version": "GApps version",
"vanilla_version": "Vanilla version",
"general_info": "General info about {} builds",
"general_info_description": " Maintainer, latest version, etc",
"not_updating": "❌ : There will be no updates at this time",
"updated": "✅ : Updated",
"magisk_latest": "𝗟𝗮𝘁𝗲𝘀𝘁 𝗠𝗮𝗴𝗶𝘀𝗸 𝗥𝗲𝗹𝗲𝗮𝘀𝗲𝘀:",
"app_by": "👤 by {}",
"Stable": "𝗦𝘁𝗮𝗯𝗹𝗲",
"Beta": "𝗕𝗲𝘁𝗮",
"Canary": "𝗖𝗮𝗻𝗮𝗿𝘆",
"md5": "<b>MD5: </b>",
"count": "<b>Downloads count: </b>",
"customAvbSupported": "<b>Custom Avb Supported:</b> ",
}
strings_ru = {
"download": "⬇️ <b>Скачать</b> :",
"no_device": "<b>Нет устройства.</b>",
"no_device_info": " Пожалуйста, проверьте правильное кодовое имя или доступность сайта",
"no_codename": "<b>Пжл коднейм((</b>",
"write_codename": "Напишите кодовое имя вашего устройства",
"latest_releases": " Последние {} релизы",
"latest_releases_no_format": " Последние релизы ПЗУ",
"latest_releases_device": " Последние релизы {} {} для {}",
"gapps_version": "GApps version",
"vanilla_version": "Ванила",
"general_info": "Общая информация о сборках {}",
"general_info_description": " Сопровождающий, последняя версия и т. д.",
"not_updating": "❌ : На данный момент обновлений не будет",
"updated": "✅ : Обновлено",
"magisk_latest": "<b>Последние релизы Magisk</b>:",
"app_by": "👤 от {}",
"Stable": "⦁ <b>Cтабильный</b>",
"Beta": "⦁ <b>Бета</b>",
"Canary": "⦁ <b>Канарейка</b>",
"md5": "<b>MD5: </b>",
"count": "<b>Количество загрузок: </b>",
"customAvbSupported": "<b>Поддерживается пользовательский Avb:</b> ",
}
magisk_dict = {
"topjohnwu": [
{
"Stable": "master/stable.json",
"Beta": "master/stable.json",
"Canary": "master/stable.json",
},
"https://raw.githubusercontent.com/topjohnwu/magisk-files/",
],
"vvb2060": [
{"Stable": "master/lite.json", "Canary": "alpha/alpha.json"},
"https://raw.githubusercontent.com/vvb2060/magisk_files/",
],
"TheHitMan7": [
{"Stable": "stable.json", "Beta": "beta.json", "Canary": "canary.json"},
"https://raw.githubusercontent.com/TheHitMan7/Magisk-Files/master/configs/",
],
}
twrp_api = "https://dl.twrp.me/"
no_codename = [
InlineQueryResultArticle(
id=rand(20),
title=strings["write_codename"],
description=strings["latest_releases_no_format"],
input_message_content=InputTextMessageContent(
strings["no_codename"], "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/android/128/26e07f/android.png",
thumb_width=128,
thumb_height=128,
)
]
# ROMs
@loader.unrestricted
@loader.ratelimit
async def sakuracmd(self, message):
"""Project Sakura"""
if args := utils.get_args(message):
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/ProjectSakura/OTA/11/devices.json"
).json()
for item in data:
if item["codename"] == device:
releases = f"Latest Project Sakura for {item['name']} ({item['codename']}) \n"
releases += f"👤 by {item['maintainer_name']} \n"
releases += f"{self.strings['download']} (https://projectsakura.xyz/download/#/{item['codename']}) \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def dotoscmd(self, message):
"""DotOS"""
if args := utils.get_args(message):
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://api.droidontime.com/api/ota/{device}"
) as get:
if get.ok:
data = await get.json()
else:
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
await session.close()
releases = f"<b>Latest DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
releases += f"👤 : {data['maintainerInfo']['name']} \n"
releases += f"🆚 : {data['latestVersion']} \n"
releases += f"{self.strings['download']} "
releases += f"<a href={data['releases'][0]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
releases += f" / <a href={data['releases'][1]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
await utils.answer(message, releases)
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
# Recovery
@loader.unrestricted
@loader.ratelimit
async def twrpcmd(self, message):
"""TWRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
url = get(f"{self.twrp_api}{device}/")
if url.status_code == 404:
reply = f"`Couldn't find twrp downloads for {device}!`\n"
await utils.answer(message, reply)
await asyncio.sleep(5)
await message.delete()
return
page = BeautifulSoup(url.content, "lxml")
download = page.find("table").find_all("tr")
reply = f"『 Team Win Recovery Project for {device}: 』\n"
for item in download:
dl_link = f"{self.twrp_api}{item.find('a')['href']}"
dl_file = item.find("td").text
size = item.find("span", {"class": "filesize"}).text
reply += f"⦁ <a href={dl_link}>{dl_file}</a> - <tt>{size}</tt>\n"
await utils.answer(message, reply)
@loader.unrestricted
@loader.ratelimit
async def shrpcmd(self, message):
"""SHRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/SHRP-Devices/device_data/master/deviceData.json"
).json()
for item in data[:-1]:
if item["codeName"] == device:
releases = f"『 SkyHawk Recovery Project for {item['model']} ({device}): 』\n"
releases += f"👤 <b>by<b> {item['maintainer']} \n"
releases += f" <b>Version<b> : {item['currentVersion']} \n"
releases += f"{self.strings['download']} : <a href={item['latestBuild']}>SourceForge</a> \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def pbrpcmd(self, message):
"""PBRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://pitchblackrecovery.com/{device}/"
) as get:
pbrp_page = await get.text()
await session.close()
page = BeautifulSoup(pbrp_page, "lxml")
status_error = page.find("h1", class_="error-code")
if status_error is not None:
return # No device
main_info = page.find_all(
"h3", class_="elementor-heading-title elementor-size-default"
)
download_info = page.find(
"section",
class_="has_eae_slider elementor-section elementor-inner-section elementor-element elementor-element-714ebe14 elementor-section-boxed elementor-section-height-default elementor-section-height-default",
)
version = main_info[0].text
date = main_info[2].text
status = main_info[4].text
maintainer = main_info[6].text
file_size = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[1].text[10:]
md5 = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[2].text[4:]
sourceforge = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[0]["href"]
github = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[1]["href"]
releases = f"『 Pitch Black Recovery Project for ({device}): 』\n"
releases += f"👤 <b>by</b> {maintainer} \n"
releases += f" <b>Status</b> : {status} \n"
releases += f" <b>Version</b> : {version} \n"
releases += f" <b>Date</b> : {date} \n"
releases += f" <b>MD5</b> : {md5} \n"
releases += f" <b>Size</b> : {file_size} \n"
releases += f"{self.strings['download']} : <a href={sourceforge}>SourceForge</a> | <a href={github}>GitHub</a>\n"
await utils.answer(message, releases)
# Other
@loader.unrestricted
@loader.ratelimit
async def magiskcmd(self, message):
"""Magisk by topjohnwu"""
magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/"
magisk_dict = {
"𝗦𝘁𝗮𝗯𝗹𝗲": magisk_repo + "master/stable.json",
"𝗕𝗲𝘁𝗮": magisk_repo + "master/beta.json",
"𝗖𝗮𝗻𝗮𝗿𝘆": magisk_repo + "master/canary.json",
}
releases = f"<code><i>{self.strings['magisk_latest']}</i></code>\n\n"
for name, release_url in magisk_dict.items():
data = get(release_url).json()
releases += f'{name}: <a href={data["magisk"]["link"]}>APK v{data["magisk"]["version"]}</a> | <a href={data["magisk"]["note"]}>Changelog</a>\n'
await utils.answer(message, releases)
# Inline commands
async def opengapps_inline_handler(self, query: GeekInlineQuery) -> None:
"""
OpenGApps (Inline)
@allow: all
"""
text = query.args
async with aiohttp.ClientSession() as session:
async with session.get("https://api.opengapps.org/list") as get:
opengapps_list = await get.json()
await session.close()
arch_dict = {}
version_text = "<b>Avilable versions</b> :\n"
for arch in opengapps_list["archs"]:
apis_list = [str(apis) for apis in opengapps_list["archs"][arch]["apis"]]
arch_dict[arch] = apis_list
version_text += f"<b>{arch}</b> : {', '.join(apis_list)}\n"
if not text:
await query.answer(
[
InlineQueryResultArticle(
id=rand(20),
title="Select android version for your device",
description=" For example : 10.0. Click for more versions",
input_message_content=InputTextMessageContent(
version_text, "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/android/128/26e07f/android.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
if len(text.split()) == 1:
archs_inline = []
archs_photo = {
"arm": "https://img.icons8.com/android/128/26e07f/32bit.png",
"arm64": "https://img.icons8.com/android/128/26e07f/64bit.png",
"x86": "https://img.icons8.com/android/128/26e07f/x86.png",
"x86_64": "https://img.icons8.com/android/128/26e07f/x64.png",
}
for arch in opengapps_list["archs"]: # arm arm64 x86 etc
if text in arch_dict[arch]:
markup = InlineKeyboardMarkup(row_width=3)
for variant in opengapps_list["archs"][arch]["apis"][text][
"variants"
]: # pico nano etc
markup.insert(
InlineKeyboardButton(variant["name"], url=variant["zip"])
)
archs_inline.append(
InlineQueryResultArticle(
id=rand(20),
title=arch,
description=" Select arch for your device",
input_message_content=InputTextMessageContent(
f"OpenGApps for Android {text} {arch}",
"HTML",
disable_web_page_preview=True,
),
thumb_url=archs_photo[arch],
thumb_width=128,
thumb_height=128,
reply_markup=markup,
)
)
markup = None
await query.answer(archs_inline, cache_time=0)
# https://img.icons8.com/fluency/48/26e07f/android-os.png
async def aex_inline_handler(self, query: GeekInlineQuery) -> None:
"""
AOSP Extended (Inline)
@allow: all
"""
device_codename = query.args
if not device_codename:
await query.answer(self.no_codename, cache_time=0)
return
async with aiohttp.ClientSession() as session:
async with session.get("https://api.aospextended.com/devices/") as get:
devices_json = await get.json()
for device in devices_json:
if device["codename"] == device_codename:
inline_query = []
for version in device["supported_versions"]:
releases = f"Latest AOSP Extended for {device['brand']} {device['name']} ({device['codename']}) \n"
async with session.get(
f"https://api.aospextended.com/builds/{device_codename}/{version['version_code']}"
) as get:
version_json = await get.json()
if "error" not in version_json:
releases += f"{self.strings['app_by'].format(version['maintainer_name'])} \n"
releases += f"💬 {hlink('Telegram Chat', version['tg_link'])} | {hlink('XDA', version['xda_thread'])} | {hlink('XDA Maintainer', version['maintainer_url'])} \n"
releases += f"{self.strings['download']} {hlink(version_json[0]['file_name'], version_json[0]['download_link'])} \n\n"
releases += (
f"{self.strings['md5']}{version_json[0]['md5']} \n"
)
releases += f"{self.strings['count']}{version_json[0]['downloads_count']} \n"
releases += f"{self.strings['customAvbSupported']} {'Yes' if version_json[0]['isCustomAvbSupported'] else 'No'}"
inline_query.append(
InlineQueryResultArticle(
id=rand(50),
title=version["version_name"],
description=self.strings["app_by"].format(
version["maintainer_name"]
),
input_message_content=InputTextMessageContent(
releases,
"HTML",
disable_web_page_preview=True,
),
)
)
await session.close()
await query.answer(inline_query, cache_time=0)
async def dotos_inline_handler(self, query: GeekInlineQuery) -> None:
"""
DotOS (Inline)
@allow: all
"""
text = query.args
if not text:
await query.answer(self.no_codename, cache_time=0)
return
if len(text.split()) == 1:
device = text
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://api.droidontime.com/api/ota/{device}"
) as get:
if get.ok:
data = await get.json()
else:
await query.answer(
[
InlineQueryResultArticle(
id=rand(20),
title=self.strings["no_device"],
description=self.strings["no_device_info"],
input_message_content=InputTextMessageContent(
self.strings["no_device_info"],
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/fa314a/cancel-2.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
await session.close()
return
await session.close()
vanilla_markup = InlineKeyboardMarkup(row_width=3)
gapps_markup = InlineKeyboardMarkup(row_width=3)
for releases in data["releases"]:
if releases["type"] == "vanilla":
vanilla_markup.insert(
InlineKeyboardButton(releases["version"], url=releases["url"])
)
else:
gapps_markup.insert(
InlineKeyboardButton(releases["version"], url=releases["url"])
)
about_info = f"<b>DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
about_info += f"👤 : {hlink(data['maintainerInfo']['name'], data['maintainerInfo']['profileURL'])} \n"
about_info += f"🆚 : {data['latestVersion']} \n"
about_info += (
self.strings["not_updating"]
if data["discontinued"]
else self.strings["updated"]
)
about_info += f"\n🔗 : {hlink('XDA',data['links']['xda'])} / {hlink('Telegram',data['links']['telegram'])} \n"
await query.answer( # About, Vanilla, Gapps
[
InlineQueryResultArticle(
id=rand(20),
title=self.strings["general_info"].format("DotOS"),
description=self.strings["general_info_description"],
input_message_content=InputTextMessageContent(
about_info,
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/info.png",
thumb_width=128,
thumb_height=128,
),
InlineQueryResultArticle(
id=rand(20),
title=self.strings["vanilla_version"],
description=self.strings["latest_releases"].format("DotOS"),
input_message_content=InputTextMessageContent(
self.strings["latest_releases_device"].format(
"DotOS", "Vanilla", device
),
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/forward.png",
thumb_width=128,
thumb_height=128,
reply_markup=vanilla_markup,
),
InlineQueryResultArticle(
id=rand(20),
title=self.strings["gapps_version"],
description=self.strings["latest_releases"].format("DotOS"),
input_message_content=InputTextMessageContent(
self.strings["latest_releases_device"].format(
"DotOS", "GApps", device
),
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/forward.png",
thumb_width=128,
thumb_height=128,
reply_markup=gapps_markup,
),
],
cache_time=0,
)
async def magisk_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Magisk (Inline)
@allow: all
"""
inline_query = []
latest_releases = f"<code><i>{self.strings['magisk_latest']}</i></code>\n\n"
for magisk_author in self.magisk_dict: # topjohnwu vvb2060
text_type = ""
for magisk_type in self.magisk_dict[magisk_author][
0
]: # List(Stable, Beta, etc) by author
base_url = self.magisk_dict[magisk_author][1]
async with aiohttp.ClientSession() as session:
async with session.get(
base_url + self.magisk_dict[magisk_author][0][magisk_type]
) as get:
data = await get.json(content_type=None)
text_type += f'{self.strings[magisk_type]}: {hlink("APK v" + data["magisk"]["version"], data["magisk"]["link"])} | {hlink("Changelog", data["magisk"]["note"])} \n'
text_type += f'\n{self.strings["app_by"].format(magisk_author)}'
inline_query.append(
InlineQueryResultArticle(
id=rand(20),
title=self.strings["magisk_latest"],
description=self.strings["app_by"].format(magisk_author),
input_message_content=InputTextMessageContent(
latest_releases + text_type,
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://upload.wikimedia.org/wikipedia/commons/b/b8/Magisk_Logo.png",
thumb_width=128,
thumb_height=128,
)
)
await query.answer(inline_query, cache_time=0)

View File

@@ -0,0 +1,138 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://forum.f-droid.org/uploads/default/original/2X/c/cfb2c14973c28415b0e5b5f7adef9c8288cd8609.png
# meta developer: @cakestwix_mods
# scope: hikka_only
# requires: httpx bs4
import logging
import httpx
from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InputTextMessageContent,
)
from aiogram.utils.markdown import hlink
from bs4 import BeautifulSoup
from .. import loader, utils
from ..inline.types import InlineQuery
logger = logging.getLogger(__name__)
async def fdroid_search(search_app = "") -> dict:
fdroid_main = "https://apt.izzysoft.de/fdroid/index.php?repo=main" # FDroid
async with httpx.AsyncClient() as client:
html = (await client.post(fdroid_main, data={"limit": 50, "searchterm": search_app, "doFilter": "Go%21"})).content
soup = BeautifulSoup(html, "html.parser")
apps = []
html_apps = soup.find_all("div", class_="approw")
for app in html_apps:
buff = {"Name": app.find("span", class_="boldname").get_text()}
buff["Desc"] = app.find_all("div", class_="appdetailcell")[-2].get_text()
buff["Icon"] = app.find("img")["src"] if app.find("img")["src"] != "/shared/images/spacer.gif" else "https://f-droid.org/repo/com.termux.tasker/en-US/icon.png"
buff["Minor-Details"] = app.find_all("span", class_="minor-details")
buff["Links"] = app.find_all("a", class_="paddedlink")[1:]
apps.append(buff)
return apps
def StringBuilder(app):
return f"<code>{app['Name']}</code> {app['Minor-Details'][0].get_text()} ({app['Minor-Details'][1].get_text()})\n\n{app['Desc']}"
class FDroidMod(loader.Module):
"""Search for android apps from FDroid"""
strings = {
"name": "FDroid",
"no_apps": "🚫 Unfortunately, I couldn't find any applications",
}
strings_ru = {
"name": "FDroid",
"no_apps": "🚫 К сожалению, не нашел приложений",
}
async def fdroidcmd(self, message):
"""Find the app in the FDroid catalog"""
args = utils.get_args_raw(message)
if apps := await fdroid_search(args):
markup = [[{"text": app.get_text(), "url": app["href"]} for app in apps[0]["Links"]]]
if len(apps) != 1:
markup.append([{"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, 0, "+")}])
await self.inline.form(
text=StringBuilder(apps[0]),
message=message,
# photo=apps[0]["Icon"],
reply_markup=markup,
)
else:
await utils.answer(message, self.strings["no_apps"])
@loader.inline_everyone
async def fdroid_inline_handler(self, query: InlineQuery) -> None:
"""Find the app in the FDroid catalog (Inline)"""
query_args = query.args
if apps := await fdroid_search(query_args):
InlineQueryResult = []
for app in apps:
# Generate button
markup = InlineKeyboardMarkup()
for link in app["Links"]:
markup.insert(InlineKeyboardButton(link.get_text(), link["href"]))
# Add InlineQueryResultArticle
InlineQueryResult.append(
InlineQueryResultArticle(
id=utils.rand(64),
title=f'{app["Name"]} ({app["Minor-Details"][1].get_text()})',
description=app["Desc"],
input_message_content=InputTextMessageContent(
StringBuilder(app),
"HTML",
disable_web_page_preview=True,
),
reply_markup=markup,
# thumb_url=app["Icon"],
)
)
await query.answer(InlineQueryResult, cache_time=0)
else:
await query.e404()
# Just callbacks
async def fdroid_pagination__callback(self, call, apps, index, type_button):
markup = [[{"text": app.get_text(), "url": app["href"]} for app in apps[index]["Links"]],[]]
if type_button == "+":
index += 1
markup[1].append({"text":"⬅️","callback": self.fdroid_pagination__callback, "args": (apps, index, "-")})
if index != len(apps) - 1:
markup[1].append({"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, index, "+")})
else:
index -= 1
if index != 0:
markup[1].append({"text":"⬅️","callback": self.fdroid_pagination__callback, "args": (apps, index, "-")})
markup[1].append({"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, index, "+")})
await call.edit(text=StringBuilder(apps[index]), reply_markup=markup)

View File

@@ -0,0 +1,169 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# meta pic: https://allvpn.ru/assets/upload/t-200x200-7439447981535195421.png
# meta developer: @cakestwix_mods
# requires: httpx bs4
# scope: inline
import logging
import xml.etree.ElementTree as ET
from typing import Union
import httpx
from aiogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
InlineQueryResultArticle, InputTextMessageContent)
from bs4 import BeautifulSoup
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
async def search_book(query=None):
books_list = []
async with httpx.AsyncClient() as client:
if query:
xml_ = (await client.get(f"http://flibusta.is/opds/opensearch?searchTerm={query}&searchType=books&pageNumber=1"))
else:
xml_ = await client.get("http://flibusta.is/opds/opensearch?searchType=books&pageNumber=1")
myroot = ET.fromstring(xml_.text)
for book in myroot.findall('.//{http://www.w3.org/2005/Atom}entry'):
books_dict = {"Books": {}, "Name": book.find('./{http://www.w3.org/2005/Atom}title').text, "Author": ""}
for item in book.findall('./{http://www.w3.org/2005/Atom}author'):
books_dict["Author"] += item.find('./{http://www.w3.org/2005/Atom}name').text + " "
# Links and Formats
for item in book.findall('./{http://www.w3.org/2005/Atom}link'):
if "application/" in item.attrib["type"] and "related" not in item.attrib["rel"]:
books_dict["Books"][item.attrib["type"].split("/")[1].replace("+zip", "").replace("x-mobipocket-ebook", "mobi")] = item.attrib["href"]
# Read
if "title" in item.attrib:
books_dict["Read"] = [item.attrib["title"], item.attrib["href"]]
if books_dict["Books"] != {}:
books_list.append(books_dict)
return books_list
@loader.tds
class FlibustaMod(loader.Module):
"""Get books from flibusta"""
strings = {
"name": "Flibusta",
"no_args": "🎞 <b>You need to specify book name</b>",
"no_book": "🎞 <b>No books by your query :(</b>",
}
# Just commands
async def bookcmd(self, message):
"""🔎 Sending the form with the books. Send message with args if you want to find a book by title"""
# Get args from message
if args:= utils.get_args_raw(message):
books = await search_book(args)
else:
books = await search_book()
# No books ((
if books == []:
return await utils.answer(message, self.strings["no_book"])
string = f'📙 <b>{books[0]["Name"]}</b>'
string += f"\n<b>Author:</b> {books[0]['Author']}"
# epub pdf fb2 mobi / Read
reply_keyboard = [[{"text": file_, "url": f"http://flibusta.is{books[0]['Books'][file_]}"} for file_ in books[0]["Books"]], [{"text": "Read", "url": f"http://flibusta.is{books[0]['Read'][1]}"}]]
btn_buff = [{"text": str(i), "callback": self.change_book__callback, "args": (book, args or None)} for i, book in enumerate(books, start=1)]
reply_keyboard.extend(iter(chunks(btn_buff, 5)))
try:
reply_keyboard.remove([])
except ValueError:
pass
await self.inline.form(
text=string,
message=message,
reply_markup=reply_keyboard,
)
# Just callbacks
async def change_book__callback(self, call, book, search=None):
books = await search_book(search)
string = f'📙 <b>{book["Name"]}</b>'
string += f"\n<b>Author:</b> {book['Author']}"
# epub pdf fb2 mobi / Read
reply_keyboard = [[{"text": file_, "url": f"http://flibusta.is{book['Books'][file_]}"} for file_ in book["Books"]], [{"text": "Read", "url": f"http://flibusta.is{book['Read'][1]}"}]]
btn_buff = [{"text": str(i), "callback": self.change_book__callback, "args": (book, search or None)} for i, book in enumerate(books, start=1)]
reply_keyboard.extend(iter(chunks(btn_buff, 5)))
try:
reply_keyboard.remove([])
except ValueError:
pass
await call.edit(text=string, reply_markup=reply_keyboard)
# Just Inline
async def book_inline_handler(self, query: GeekInlineQuery) -> None:
"""
🔎 Sending the form with the books. Send message with args if you want to find a book by title (Inline)
"""
if text := query.args:
books = await search_book(text)
else:
books = await search_book()
# No books ((
if books == []:
return await query.e404()
InlineQueryResult = []
for book in books:
markup = InlineKeyboardMarkup(row_width=3)
for file_ in book["Books"]:
markup.insert(InlineKeyboardButton(file_, f"http://flibusta.is{book['Books'][file_]}"))
InlineQueryResult.append(
InlineQueryResultArticle(
id=utils.rand(50),
title=book["Name"],
description=book["Author"],
input_message_content=InputTextMessageContent(
f'📙 <b>{book["Name"]}</b>\n<b>Author:</b> {book["Author"]}',
"HTML",
disable_web_page_preview=True,
),
reply_markup=markup,
)
)
await query.answer(InlineQueryResult, cache_time=0)

View File

@@ -0,0 +1,23 @@
anilibria
compli
customroms_geek
customroms
FoxAndDogsGallery
ImageBoardSender
linux_packages
minecraft
qrcode
random_tools
tikcock
toloka_geek
translate
transmission
wynncraft_geek
yandere_geek
yandere
InlineSystemInfo
InlineYouTube
RandomPeople
InlineSpotifyDownloader
flibusta
SimpleNoLink

View File

@@ -0,0 +1,125 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 1)
# meta pic: https://seeklogo.com/images/H/hentai-haven-logo-B9D8C4B3B8-seeklogo.com.png
# meta developer: @cakestwix_mods
# requires: NHentai-API
import logging
from typing import Union
from NHentai import NHentaiAsync, CloudFlareSettings
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
from aiogram.utils.markdown import hlink
import asyncio
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/commit/03f7c71557acd6e14e816df4de932dd55668fd97#diff-b020ffc1f4d0e66f2cfd8724370d8ee28197d945f9d0f2cf7e4358717e71e27cR439-R441
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
def StringBuilder(Hentai):
tags = "".join(f"{hlink(tag.name, tag.url)} " for tag in Hentai.tags)
langs = "".join(f"{hlink(lang.name, lang.url)} " for lang in Hentai.languages)
text = f"{hlink(Hentai.title.english, Hentai.url)} [{Hentai.id}]\n\n"
text += f"{tags} \n\n"
text += f"Language: {langs} \n"
text += f"❤️ {Hentai.total_favorites} | 📄 {Hentai.total_pages}"
return text
@loader.tds
class NHentaiMod(loader.Module):
"""🍓 Hentai doujin module 18+"""
strings = {
"name": "NHentai",
"no_tags": "🎞 <b>No hentai by your query :(</b>",
"no_digit": "1⃣ <b>Please give me a number.</b>",
}
strings_ru = {
"name": "🍓 NHentai",
"no_tags": "🎞 <b>Не нашел хентая по твоему запросу :(</b>",
"no_digit": "1⃣ <b>Пожалуйста, дайте мне число.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_CSRFTOKEN",
"",
lambda: self.strings("cfg_csrftoken"),
"CONFIG_CF_CLEARANCE",
"",
lambda: self.strings("cfg_cf_clearance"),
)
async def client_ready(self, client, db) -> None:
self.nhentai_async = NHentaiAsync(request_settings=CloudFlareSettings(csrftoken=self.config["CONFIG_CSRFTOKEN"],
cf_clearance=self.config["CONFIG_CF_CLEARANCE"]))
async def nhrandomcmd(self, message):
"""🎲 Random hentai doujin"""
hentai = await self.nhentai_async.get_random()
await message.delete()
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhlastcmd(self, message):
"""⌚️ Latest hentai doujin"""
hentai = await self.nhentai_async.get_doujin((await self.nhentai_async.get_page(page=1)).doujins[0].id)
await message.delete()
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhidcmd(self, message):
"""1⃣ Hentai doujin by id"""
if args:= utils.get_args_raw(message):
if not args.isdigit():
return await message.answer(message, self.strings["no_digit"])
hentai = await self.nhentai_async.get_doujin(args)
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhsearchcmd(self, message):
"""🔎 Search hentai doujin"""
if args:= utils.get_args_raw(message):
hentai = await self.nhentai_async.search(args)
markup = [[{"text":"Link", "url":hentai.doujins[0].url}]]
if len(hentai.doujins) != 1:
markup.append([{"text":"➡️","callback": self.hentai_pagination__callback, "args": (hentai.doujins, 0, "+")}])
await self.inline.form(
text=StringBuilder(hentai.doujins[0]),
message=message,
photo=hentai.doujins[0].cover.src,
reply_markup=markup,
)
# Just callbacks
async def hentai_pagination__callback(self, call, list_doujins, index, type_button):
markup = [[{"text":"Link", "url": list_doujins[index].url}],[]]
if type_button == "+":
index += 1
markup[1].append({"text":"⬅️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "-")})
if index != len(list_doujins) - 1:
markup[1].append({"text":"➡️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "+")})
else:
index -= 1
if index != 0:
markup[1].append({"text":"⬅️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "-")})
markup[1].append({"text":"➡️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "+")})
await call.edit(text=StringBuilder(list_doujins[index]), reply_markup=markup, photo=list_doujins[index].cover.src)

View File

@@ -0,0 +1,108 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
# Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: requests hentai
# meta pic: https://seeklogo.com/images/H/hentai-haven-logo-B9D8C4B3B8-seeklogo.com.png
# meta developer: @cakestwix_mods
import asyncio
import logging
from hentai import Hentai, Utils
from requests.exceptions import HTTPError
from .. import loader, utils
logger = logging.getLogger(__name__)
# Utils
def StringBuilder(Hentai):
id_nh = Hentai.id
eng_name = Hentai.title()
link = Hentai.url
total_pages = Hentai.num_pages
total_favorites = Hentai.num_favorites
tags = "".join(f"{tag.name} " for tag in Hentai.tag)
text = f"<a href={link}>{eng_name}</a> [{id_nh}]\n\n"
text += f"{tags} \n"
text += f"❤️ {total_favorites} | 📄 {total_pages}"
return text
def ListHentaiBuilder(Hentais):
text = ""
for i, Hentai in enumerate(Hentais, start=1):
id_nh = Hentai.id
eng_name = Hentai.title()
link = Hentai.url
total_pages = Hentai.num_pages
total_favorites = Hentai.num_favorites
text += f"{i}: <a href={link}>{eng_name}</a> [{id_nh}] / "
text += f"❤️ {total_favorites} | 📄 {total_pages} \n"
return text
@loader.unrestricted
@loader.ratelimit
@loader.tds
class NHentaiMod(loader.Module):
"""Hentai module 18+ Legacy"""
strings = {
"name": "NHentai",
}
@loader.unrestricted
@loader.ratelimit
async def nhrandomcmd(self, message):
"""Random hentai manga"""
await message.delete()
hentai_info = Utils.get_random_hentai()
text = StringBuilder(hentai_info)
await message.client.send_file(message.chat_id, hentai_info.cover, caption=text)
@loader.unrestricted
@loader.ratelimit
async def nhtagcmd(self, message):
"""Search hentai manga by tag"""
if args := utils.get_args(message):
hentai_info = Utils.search_by_query(args)
text = ListHentaiBuilder(hentai_info)
await utils.answer(message, text)
else:
await utils.answer(message, "Pls tags")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def nhidcmd(self, message):
"""Search hentai manga by id"""
args = utils.get_args(message)
if args[0].isdigit():
try:
hentai_info = Hentai(args[0])
text = StringBuilder(hentai_info)
await message.client.send_file(
message.chat_id, hentai_info.cover, caption=text
)
except HTTPError as e:
await utils.answer(message, str(e))
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, "Pls id")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,292 @@
"""
█▄▀ █ █░█░█ █ █▄░█ █ █▀▀ █▀▀ █▀█
█░█ █ ▀▄▀▄▀ █ █░▀█ █ █▄▄ ██▄ █▀▄
Copyleft 2022 t.me/KiwiNicer
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# requires: aiohttp
# meta pic: https://img.icons8.com/clouds/512/000000/linux-client.png
# meta developer: @KiwiNicer
import aiohttp
import logging
import asyncio
from aiogram.types import CallbackQuery
from typing import Union
from .. import loader, utils
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
@loader.tds
class LinuxPackagesMod(loader.Module):
"""Search package for Linux by name"""
strings = {
"name": "Packages",
"no_name": "Pls give me name",
"general_error": "<b>Unknown error</b> .-.",
"string_list": "<b>List of packages in the {}</b>\n\n",
"info_about": "<b>Info about</b> <code>{}</code>\n\n",
"ver": "<b>Version:</b> {}\n",
"description": "<b>Description:</b> {}\n",
"maintainer": "<b>Maintainer:</b> {}\n",
"no_packages": "<b>No packages</b>...",
}
strings_ru = {
"no_name": "Пожалуйста, дайте мне имя пакета",
"general_error": "<b>Неизвестная ошибка</b> .-.",
"string_list": "<b>Список пакетов в {}</b>\n\n",
"info_about": "<b>Информация о</b> <code>{}</code>\n\n",
"ver": "<b>Версия:</b> {}\n",
"description": "<b>Описание:</b> {}\n",
"maintainer": "<b>Сопровождающий:</b> {}\n",
"no_packages": "<b>Нет пакетов</b>...",
}
async def aurcmd(self, message):
"""Arch User Repository"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["no_name"])
return await asyncio.sleep(5)
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=search&arg={args}"
) as get:
if get.ok:
packages = await get.json()
if packages["resultcount"] == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("AUR")
for package in packages["results"]:
string += f"{i}. {package['Name']}(v{package['Version']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["Name"], "AUR", args],
}
)
if i >= 10:
break
i = i + 1
await self.inline.form(
text=string,
message=message,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
async def inline__get_package(
self, call: CallbackQuery, Name: str, _type: str, search_arg: str
) -> None:
if _type == "AUR":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=info&arg[]={Name}"
) as get:
if get.ok:
package = await get.json()
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
string = self.strings["info_about"].format(Name)
string += self.strings["ver"].format(package["results"][0]["Version"])
string += self.strings["description"].format(
package["results"][0]["Description"]
)
string += self.strings["maintainer"].format(
package["results"][0]["Maintainer"]
)
btn = [
[
{
"text": "AUR",
"url": f"https://aur.archlinux.org/packages/{Name}",
},
{
"text": "Download snapshot",
"url": "https://aur.archlinux.org"
+ package["results"][0]["URLPath"],
},
],
[
{
"text": "Back",
"callback": self.inline__back,
"args": [search_arg, "AUR"],
}
],
]
elif _type == "pacman":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={Name}"
) as get:
if get.ok:
package = await get.json()
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
string = self.strings["info_about"].format(Name)
string += self.strings["ver"].format(package["results"][0]["pkgver"])
string += self.strings["description"].format(
package["results"][0]["pkgdesc"]
)
string += self.strings["maintainer"].format(
package["results"][0]["maintainers"][0]
)
btn = [
[
{
"text": "Pacman",
"url": f"https://archlinux.org/packages/{package['results'][0]['repo']}/{package['results'][0]['arch']}/{package['results'][0]['pkgname']}",
},
],
[
{
"text": "Back",
"callback": self.inline__back,
"args": [search_arg, "pacman"],
}
],
]
await call.edit(
text=string,
reply_markup=btn, # optional: Change buttons in message. If not specified, buttons will be removed
force_me=False, # optional: Change button privacy mode
)
async def inline__back(self, call: CallbackQuery, Name: str, _type: str) -> None:
if _type == "AUR":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=search&arg={Name}"
) as get:
if get.ok:
packages = await get.json()
i = 1
reply_markup = []
string = self.strings["string_list"].format("AUR")
for package in packages["results"]:
string += f"{i}. {package['Name']}(v{package['Version']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["Name"], "AUR", Name],
}
)
if i >= 10:
break
i = i + 1
await call.edit(
text=string,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
elif _type == "pacman":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={Name}"
) as get:
if get.ok:
packages = await get.json()
if len(packages["results"]) == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("pacman")
for package in packages["results"]:
string += f"{i}. {package['pkgname']}(v{package['pkgver']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["pkgname"], "pacman", Name],
}
)
if i >= 10:
break
i = i + 1
await call.edit(
text=string,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
async def pacmancmd(self, message):
"""Pacman"""
if not (args := utils.get_args_raw(message)):
return
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={args}"
) as get:
if get.ok:
packages = await get.json()
if len(packages["results"]) == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("pacman")
for package in packages["results"]:
string += f"{i}. {package['pkgname']}(v{package['pkgver']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["pkgname"], "pacman", args],
}
)
if i >= 10:
break
i = i + 1
await self.inline.form(
text=string,
message=message,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)

View File

@@ -0,0 +1,97 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# requires: aiohttp
# meta pic: https://icons.iconarchive.com/icons/blackvariant/button-ui-requests-2/1024/Minecraft-2-icon.png
# meta developer: @cakestwix_mods
import logging
import aiohttp
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class InlineMinecraftInfoMod(loader.Module):
"""Information about players and server status"""
strings = {
"name": "MinecraftInfo",
"error_message": "🚫 This entity does not exist or you entered it incorrectly",
"about_user": "<b>Available player information</b> <code>{}</code>:'\n",
"about_server": "<b>Available server information</b> <code>{}</code>:'\n",
"username": "<b>Username:</b> <code>{}</code>\n",
"id": "<b>Id:</b> <code>{}</code>\n",
"description": "<b>Description</b>: {}\n",
"latency": "<b>Latency</b>: {}\n",
"players": "<b>Players</b>: {} in {}\n",
"versions": "<b>Versions</b>: {}\n",
}
strings_ru = {
"error_message": "🚫 Этот объект не существует или вы ввели его неправильно",
"about_user": "<b>Доступная информация об игроке</b> <code>{}</code>:'\n",
"about_server": "<b>Доступная информация о сервере</b> <code>{}</code>:'\n",
"username": "<b>Имя игрока:</b> <code>{}</code>\n",
"id": "<b>Id:</b> <code>{}</code>\n",
"description": "<b>Описание</b>: {}\n",
"latency": "<b>Задержка</b>: {}\n",
"players": "<b>Игроки</b>: {} in {}\n",
"versions": "<b>Версии</b>: {}\n",
}
base_url = "https://api.minetools.eu"
async def mucheckcmd(self, message):
"""Check user by username"""
if args := utils.get_args_raw(message):
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}/uuid/{args}") as get:
data = await get.json()
if data["status"] == "ERR":
return await utils.answer(
message, self.strings["error_message"]
)
async with session.get(f"{self.base_url}/profile/{data['id']}") as get:
user = await get.json()
text = self.strings["about_user"].format(user["decoded"]["profileName"])
text += self.strings["id"].format(user["decoded"]["profileId"])
text += self.strings["username"].format(user["decoded"]["profileName"])
for texture in user["decoded"]["textures"]:
text += f"<b>{texture}</b>: <a href={user['decoded']['textures'][texture]['url']}>URL</a>\n"
await utils.answer(message, text)
async def mpingcmd(self, message):
"""Ping minecraft server"""
if args := utils.get_args_raw(message):
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}/ping/{args}") as get:
data = await get.json()
if "error" in data:
return await utils.answer(
message, self.strings["error_message"]
)
text = self.strings["about_user"].format(args)
text += self.strings["description"].format(data["description"])
text += self.strings["latency"].format(data["latency"])
text += self.strings["players"].format(
data["players"]["online"], data["players"]["max"]
)
text += self.strings["versions"].format(data["version"]["name"])
await utils.answer(message, text)

View File

@@ -0,0 +1,61 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: qrcode
# meta pic: https://cdn1.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/qr-code-circle-blue-512.png
# meta developer: @cakestwix_mods
import asyncio
import io
import logging
import qrcode
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class QrCodeMod(loader.Module):
"""Module for creating Qr codes"""
strings = {
"name": "QrCode",
}
@loader.unrestricted
@loader.ratelimit
async def qrcmd(self, message):
"""Create QrCode"""
reply = await message.get_reply_message()
if len(message.text) > 3:
text = message.text[4:] # .qr_
elif reply and reply.text != "":
text = reply.text
else:
text = None
if text != None:
img = qrcode.make(text)
with io.BytesIO() as output:
img.save(output)
contents = output.getvalue()
await message.delete()
await message.client.send_file(message.chat_id, contents, caption=text)
else:
await utils.answer(message, "Pls text")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,116 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://i0.wp.com/alliancestake.org/wp-content/uploads/2017/09/icon-circle-tools-blue-1.png?fit=300%2C300&ssl=1
# meta developer: @cakestwix_mods
import logging
import aiohttp
import asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class RToolsMod(loader.Module):
"""Random tools"""
strings = {
"name": "Tools",
"no_found": "No found",
"no_args": "Not found args, pls check help",
"general_error": "Oh no, cringe, error",
}
strings_ru = {
"no_found": "Не найдено",
"no_args": "Аргументы не найдены, пожалуйста, проверьте справку",
"general_error": "❗️Ашибка❗️ ",
}
@loader.unrestricted
@loader.ratelimit
async def mac2vendorcmd(self, message):
"""Get vendor name by mac"""
if args := utils.get_args(message):
mac = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(f"http://api.macvendors.com/{mac}") as get:
if get.ok:
await utils.answer(message, await get.text())
else:
await utils.answer(message, self.strings["no_found"])
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def oneptcmd(self, message):
"""A simple URL shortener (1pt.co)"""
if args := utils.get_args(message):
mac = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.1pt.co/addURL?long={mac}") as get:
if get.ok:
answer_json = await get.json()
await utils.answer(message, "1pt.co/" + answer_json["short"])
else:
await utils.answer(message, self.strings["general_error"])
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def npcmd(self, message):
"""Нова Пошта"""
if args := utils.get_args(message):
document_number = args[0].lower()
data = {
"apiKey": "abe3a74549c55e4b703ed042c5169406",
"modelName": "TrackingDocument",
"calledMethod": "getStatusDocuments",
"methodProperties": {
"Documents": [{"DocumentNumber": document_number, "Phone": ""}]
},
}
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.novaposhta.ua/v2.0/json/", json=data
) as get:
answer = await get.json()
await session.close()
item = answer["data"][0]
caption = f"Экспресс-накладная: {item['Number']}"
caption += f"\nСтатус: {item['Status']}"
if "DateCreated" in item:
caption += f"\nБыло создано: {item['DateCreated']}"
caption += f"\nОжид. дата доставки: {item['ScheduledDeliveryDate']}"
caption += f"\n{item['CitySender']} -> {item['CityRecipient']}"
if item.get("DocumentCost") is not None:
caption += f"\nЦена доставки: {item['DocumentCost']} грн."
await utils.answer(message, caption)

View File

@@ -0,0 +1,110 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://img.icons8.com/external-flaticons-lineal-color-flat-icons/512/000000/external-anime-addiction-flaticons-lineal-color-flat-icons.png
# meta developer: @cakestwix_mods
# requires: saucenao_api
# scope: inline
# scope: hikka_only
# scope: hikka_min 1.2.7
import logging
import os
from .. import loader, utils
from saucenao_api import AIOSauceNao
from saucenao_api.errors import ShortLimitReachedError, LongLimitReachedError
from saucenao_api.containers import BasicSauce
logger = logging.getLogger(__name__)
def string_builder(sauce_item):
string = "Unsupported type, sorry("
if isinstance(sauce_item, BasicSauce):
string = f"<b>Similarity</b>: <code>{sauce_item.similarity}</code>\n\n"
string += f"<b>Title</b>: <code>{sauce_item.title}</code>\n"
string += f"<b>Author</b>: <code>{sauce_item.author}</code>\n"
string += f"<b>Urls</b>: {' '.join(sauce_item.urls)}\n"
return string
@loader.tds
class SauceNaoMod(loader.Module):
"""🔎 SauceNao - image source locator"""
strings = {
"name": "SauceNao",
"cfg_api_key": "https://saucenao.com/user.php?page=search-api",
"no_args_reply": "🚫 Not found args or reply, pls check help",
"wrong_url": "🚫 <b>Wrong Url</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_API_KEY",
None,
lambda: self.strings("cfg_api_key"),
)
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
# Just commands
async def saucecmd(self, message):
"""🔗 Search for the source by link/photo"""
if not self.config["CONFIG_API_KEY"]:
return await utils.answer(message, "🚫 <b>No API Key</b>")
results = None
# If message has reply
if reply := await message.get_reply_message():
if reply.photo:
async with AIOSauceNao(self.config["CONFIG_API_KEY"]) as aio:
try:
file_ = await self._client.download_media(reply.photo)
with open(file_, 'rb') as img:
results = await aio.from_file(img)
os.remove(file_)
except ShortLimitReachedError:
return await utils.answer(message, "🚫 <b>ShortLimitReachedError</b>")
except LongLimitReachedError:
return await utils.answer(message, "🚫 <b>LongLimitReachedError</b>")
# If message not have reply, then get args from message
if url := utils.get_args_raw(message):
if utils.check_url(utils.get_args_raw(message)):
async with AIOSauceNao(self.config["CONFIG_API_KEY"]) as aio:
try:
results = await aio.from_url(url)
except ShortLimitReachedError:
return await utils.answer(message, "🚫 <b>ShortLimitReachedError</b>")
except LongLimitReachedError:
return await utils.answer(message, "🚫 <b>LongLimitReachedError</b>")
else:
await utils.answer(message, self.strings["wrong_url"])
if not results:
return await utils.answer(message, self.strings["no_args_reply"])
await self.inline.gallery(
message,
[url_photo.thumbnail for url_photo in results],
[
f"<b>Request limits (per 30 seconds limit)</b>: <code>{results.short_remaining}</code>\n<b>Request limits (per day limit)</b>: <code>{results.long_remaining}</code>\n"
+ string_builder(item)
for item in results
],
)

View File

@@ -0,0 +1,73 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 1)
# meta pic: http://assets.stickpng.com/images/5cb78671a7c7755bf004c14b.png
# meta developer: @cakestwix_mods
# scope: hikka_only
# requires: httpx
import logging
import re
import httpx
from aiogram.utils.markdown import hlink
from telethon.errors.rpcerrorlist import BotResponseTimeoutError
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class TikTokMod(loader.Module):
"""Yet Another TikTok Downloader"""
strings = {
"name": "YATikTok-DL",
"no_args": "🚫 Not found args, pls check help",
"no_item": "Couldn't find it("
}
strings_ru = {
"name": "YATikTok-DL",
"no_args": "🚫 Аргументы не найдены, пожалуйста, проверьте справку",
"no_item": "Не нашел(("
}
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
async def ttdlcmd(self, message):
"""Download video/music from tiktok"""
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, self.strings["no_args"])
elif "www.tiktok.com" in args or "vm.tiktok.com" in args:
async with httpx.AsyncClient() as client:
if tik_info := re.findall(r'\/.*\/([\d]*)?', (await client.head(args)).headers["Location"] if "vm.tiktok.com" in args else args):
tik_get = (await client.get("http://api.tiktokv.com/aweme/v1/multi/aweme/detail/?aweme_ids=[" + tik_info[0])).json()
logger.debug(tik_get)
await self.inline.form(
message=message,
text=hlink(tik_get["aweme_details"][0]["share_info"]["share_title"], tik_get["aweme_details"][0]["share_info"]["share_url"]),
reply_markup=[[{"text":"Without watermark", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["video"]["play_addr"]["url_list"][0], message.to_id)}, {"text":"With watermark", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["video"]["download_addr"]["url_list"][0], message.to_id)}], [{"text":"Audio", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["music"]["play_url"]["url_list"][0], message.to_id)}]],
photo=tik_get["aweme_details"][0]["video"]["origin_cover"]["url_list"][0]
)
else:
await utils.answer(message, "")
async def download__callback(self, call, url, id_):
await self._client.send_file(id_, url)
await call.delete()

View File

@@ -0,0 +1,145 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://img.icons8.com/external-others-iconmarket/512/000000/external-national-flags-others-iconmarket-5.png
# meta developer: @cakestwix_mods
import asyncio
import aiohttp
import logging
from aiogram.utils.markdown import hlink
from aiogram.types import (
InlineQueryResultArticle,
InputTextMessageContent,
)
from ..inline import GeekInlineQuery, rand
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class HurtomMod(loader.Module):
"""Український торрент трекер"""
strings = {
"name": "InlineHurtom",
"no_args": "🚫 <b>Будь ласка, введіть ключові слова, за якими я знайду Вам тему</b>",
"no_args_inline": "Будь ласка, введіть ключові слова, за якими я знайду Вам тему",
"no_args_inline_description": " Наприклад : Кот",
"no_torrent": "🚫 Не було знайдено жодного торрента",
"forum_name": "<b>Назва Розділу</b> : ",
"comments": "<b>Коментарі</b> : ",
"size": "<b>Розмір</b> : ",
"size_inline": "Розмір: ",
"seeders": "<b>Роздають</b> : ",
"leechers": "<b>Завантажують</b> : ",
}
def stringBuilder(self, json):
text = "<b>{}</b>\n".format(hlink(json["title"], json["link"]))
text += (
self.strings["forum_name"]
+ json["forum_name"]
+ " | "
+ json["forum_parent"]
+ "\n"
)
text += self.strings["comments"] + json["comments"] + "\n"
text += self.strings["size"] + json["size"] + "\n"
text += self.strings["seeders"] + json["seeders"] + "\n"
text += self.strings["leechers"] + json["leechers"] + "\n"
return text
@loader.unrestricted
@loader.ratelimit
async def hsearchcmd(self, message):
"""Пошук по трекеру toloka.to (повертає перший елемент)"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
return
async with aiohttp.ClientSession() as session:
async with session.get(f"https://toloka.to/api.php?search={args}") as get:
if not get.ok:
return
data = await get.json()
if data == []:
await utils.answer(message, self.strings["no_torrent"])
return
await session.close()
await utils.answer(message, self.stringBuilder(data[0]))
# Inline
async def hsearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Пошук по трекеру toloka.to (Inline)
@allow: all
"""
text = query.args
if not text:
await query.answer(
[
InlineQueryResultArticle(
id=1,
title=self.strings["no_args_inline"],
description=self.strings["no_args_inline_description"],
input_message_content=InputTextMessageContent(
self.strings["no_args"],
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/ball-point-pen.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
async with aiohttp.ClientSession() as session:
async with session.get(f"https://toloka.to/api.php?search={text}") as get:
if not get.ok:
return
data = await get.json()
if data == []:
return
await session.close()
inline_query = [
InlineQueryResultArticle(
id=rand(50),
title=torrent["title"],
description=self.strings["size_inline"] + torrent["size"],
input_message_content=InputTextMessageContent(
self.stringBuilder(torrent), "HTML", disable_web_page_preview=True
),
)
for torrent in data
]
await query.answer(inline_query, cache_time=0)

View File

@@ -0,0 +1,137 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 0)
# meta pic: https://img.icons8.com/color/512/40C057/translate-text.png
# meta developer: @cakestwix_mods
# requires: translators
import logging
import aiohttp, asyncio
from .. import loader, utils
import translators as trl
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class TranslatorMod(loader.Module):
"""
🔡 Module for text translation
➡️ .tr en ru | Hello World
➡️ .tr ru | Hello World
➡️ .tr ru + reply to message
"""
strings = {
"name": "🔡 Translator",
"cfg_lingva_url": "Alternative front-end for Google Translate",
"error": "Error!\n .gtr [en] ru | text or check help",
}
strings_ru = {
"cfg_lingva_url": "Альтернативный интерфейс для Google Translate",
"error": "Ошибка!\n .gtr [en] ru | текст или проверьте хелп",
}
def __init__(self):
self.config = loader.ModuleConfig(
"lingva_url",
"https://lingva.ml/api/v1/{source}/{target}/{query}",
lambda m: self.strings("cfg_lingva_url", m),
)
self.name = self.strings["name"]
async def tr(self, message, translator):
if args:= utils.get_args_raw(message):
lang_args = args.split("|")[0].split() # Lang
if reply := await message.get_reply_message():
if reply.message == '':
return await utils.answer(message, self.strings["error"])
if len(lang_args) == 2:
translated_text = translator(reply.message, from_language=lang_args[0], to_language=lang_args[1])
return await utils.answer(message, translated_text)
elif len(lang_args) == 1:
translated_text = translator(reply.message, to_language=lang_args[0])
return await utils.answer(message, translated_text)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
text_args = args.split("|")[1] # Text
if len(lang_args) == 2 and text_args:
translated_text = translator(text_args, from_language=lang_args[0], to_language=lang_args[1])
elif len(lang_args) == 1 and text_args:
translated_text = translator(text_args, to_language=lang_args[0])
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
await utils.answer(message, translated_text)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
async def atrcmd(self, message):
"""
Based on Argos (LibreTranslate)
"""
await self.tr(message, trl.argos)
async def itrcmd(self, message):
"""
Based on Iciba
"""
await self.tr(message, trl.iciba)
async def gtrcmd(self, message):
"""
Based on Google Translate
"""
await self.tr(message, trl.google)
async def ltrcmd(self, message):
"""
Based on lingva.ml (Google Translate)
"""
if args:= utils.get_args_raw(message):
lang_args = args.split("|")[0].split() # Lang
text_args = args.split("|")[1] # Text
if len(lang_args) == 2 and text_args:
url = self.config["lingva_url"].format(
source=lang_args[0], target=lang_args[1], query=text_args
)
elif len(lang_args) == 1 and text_args:
url = self.config["lingva_url"].format(
source="auto", target=lang_args[0], query=text_args
)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
async with aiohttp.ClientSession() as session:
async with session.get(url) as get:
translated_text = await get.json()
await session.close()
await utils.answer(message, translated_text["translation"])
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,512 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: transmission-rpc
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://img.icons8.com/ios-filled/512/40C057/torrent.png
# meta developer: @cakestwix_mods
import logging
from .. import loader, utils
import asyncio
from telethon.tl.functions.channels import CreateChannelRequest
from ..inline import GeekInlineQuery, rand
from aiogram.types import (
InlineQueryResultArticle,
InputTextMessageContent,
InlineKeyboardMarkup,
InlineKeyboardButton,
CallbackQuery,
)
from aiogram.utils.exceptions import MessageNotModified
from transmission_rpc import Client
from transmission_rpc.utils import format_size
from transmission_rpc.error import TransmissionConnectError
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class TransmissionMod(loader.Module):
"""Simple torrent client for Transmission"""
strings = {
"name": "Transmission",
"cfg_username": "Username",
"cfg_password": "Password",
"cfg_port": "Post (9091)",
"cfg_host": "Host (localhost)",
"cfg_protocol": "Protocol (http)",
"cfg_rpc": "RPC url (/transmission/)",
"not_ready": "Pls check config",
"torrent_name": "<b>Name:</b> ",
"torrent_status": "<b>Status:</b> ",
"torrent_hash": "<b>Hash:</b> ",
"torrent_dir": "<b>Directory:</b> ",
"torrent_size": "<b>Size:</b> ",
"kb_update": "🔄 Update",
"kb_close": "🚫 Close",
"torrent_eta": "ETA: ",
"torrent_error": "<b>Torrent not found in result</b>",
"kb_start": "▶️",
"kb_stop": "",
"kb_delete": "❌ Delete torrent ❌",
"kb_delete_data": "❌ Delete torrent with data ❌",
"answer_start": "Torrent starting",
"answer_stop": "Torrent stopped",
"answer_delete": "Torrent removed",
"inline_title": "Torrent Manager",
"inline_desc": " Click to view the parameters",
"inline_answer": " No changes",
}
strings_ru = {
"cfg_username": "Юзернейм",
"cfg_password": "Пароль",
"cfg_port": "Сообщение (9091)",
"cfg_host": "Хост (localhost)",
"cfg_protocol": "Протокол (http)",
"cfg_rpc": "URL-адрес RPC (/transmission/)",
"not_ready": "Пожалуйста, проверьте конфиг",
"torrent_name": "<b>Имя:</b> ",
"torrent_status": "<b>Статус:</b> ",
"torrent_hash": "<b>Хэш:</b> ",
"torrent_dir": "<b>Директория:</b> ",
"torrent_size": "<b>Размер:</b> ",
"kb_update": "🔄 Обновить",
"kb_close": "🚫 Закрыть",
"torrent_eta": "ETA: ",
"torrent_error": "<b>Torrent not found in result</b>",
"kb_delete": "❌ Удалить торрент ❌",
"kb_delete_data": "❌ Удалить торрент с данными ❌",
"answer_start": "Запуск торрента",
"answer_stop": "Торрент остановлен",
"answer_delete": "Торрент удален",
"inline_title": "Торрент-менеджер",
"inline_desc": " Нажмите, чтобы просмотреть параметры",
"inline_answer": " Без изменений",
}
def stringTorrent(self, torrent):
torrent_text = f"{self.strings['torrent_name']}{torrent.name} \n"
torrent_text += f"{self.strings['torrent_status']}{torrent.status} \n"
torrent_text += f"{self.strings['torrent_eta']}{torrent.format_eta()} \n"
torrent_text += f"{self.strings['torrent_hash']}{torrent.hashString} \n"
torrent_text += f"{self.strings['torrent_size']}{format_size(torrent.total_size)[0]} {format_size(torrent.total_size)[1]} \n"
torrent_text += f"{self.strings['torrent_dir']}{torrent.download_dir} \n"
return torrent_text
def __init__(self):
self.config = loader.ModuleConfig(
"username",
None,
lambda m: self.strings("cfg_username", m),
"password",
None,
lambda m: self.strings("cfg_password", m),
"port",
9091,
lambda m: self.strings("cfg_port", m),
"host",
"127.0.0.1",
lambda m: self.strings("cfg_host", m),
"protocol",
"http",
lambda m: self.strings("cfg_protocol", m),
"rpc",
"/transmission/",
lambda m: self.strings("cfg_rpc", m),
)
self.name = self.strings["name"]
# Check Transmission Server
self.is_ready = False
try:
self.TransmissionClientUserBot = Client(
host=self.config["host"],
port=self.config["port"],
username=self.config["username"],
password=self.config["password"],
path=self.config["rpc"],
protocol=self.config["protocol"],
)
self.is_ready = True
except TransmissionConnectError:
pass
async def client_ready(self, client, db):
self._client = client
self._me = await client.get_me(True)
@loader.unrestricted
@loader.ratelimit
async def tinfocmd(self, message):
"""Useful information about transmission server"""
if self.is_ready:
session_stats = self.TransmissionClientUserBot.session_stats()
timeout = self.TransmissionClientUserBot.timeout
rpc_version = self.TransmissionClientUserBot.rpc_version
is_port_open = self.TransmissionClientUserBot.port_test()
port = session_stats.peer_port
download_dir = session_stats.download_dir
free_space = self.TransmissionClientUserBot.free_space(download_dir)
string = "Info about your Transmission Server\n\n"
string += f"RPC version : {rpc_version}\n"
string += f"Current timeout for HTTP queries : {timeout}\n"
string += f"Port is open : {is_port_open}\n"
string += f"Port : {port}\n"
string += f"Download path : {download_dir}\n"
string += f"Free space : {format_size(free_space)[0]} {format_size(free_space)[1]}\n"
await utils.answer(message, string)
else:
await utils.answer(message, self.strings["not_ready"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def tdownloadcmd(self, message):
"""Download Torrent file"""
reply, args = await message.get_reply_message(), utils.get_args_raw(message)
if reply and reply.media.document.mime_type == "application/x-bittorrent":
path = await self._client.download_media(reply.media, "scam.torrent")
torrent = self.TransmissionClientUserBot.add_torrent(
"file://scam.torrent", download_dir=args or None
)
kb = [
[
{
"text": self.strings["kb_update"],
"callback": self.inline_update_torrent,
"args": [torrent.id],
}
],
[
{
"text": self.strings["kb_start"],
"callback": self.inline__start,
"args": [torrent.id],
},
{
"text": self.strings["kb_stop"],
"callback": self.inline__stop,
"args": [torrent.id],
},
],
[
{
"text": self.strings["kb_delete_data"],
"callback": self.inline__delete,
"args": [torrent.id, True],
},
{
"text": self.strings["kb_delete"],
"callback": self.inline__delete,
"args": [torrent.id, False],
},
],
[{"text": self.strings["kb_close"], "callback": self.inline__close}],
]
await self.inline.form(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent.id)
),
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def transmission_inline_handler(self, query: GeekInlineQuery) -> None:
"""
General info (Inline)
"""
args = query.args
param = {"list": "List of 10 torrents", "search": "Search torrents by name"}
param_text = "<b>Available parameters: </b>\n"
for item in param:
param_text += f"{item} - {param[item]}\n"
if not args:
await query.answer(
[
InlineQueryResultArticle(
id=1,
title=self.strings["inline_title"],
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
param_text, "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/ios-filled/128/26e07f/torrent.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
if "list" in args:
kb_torrent_list = []
for torrent in self.TransmissionClientUserBot.get_torrents():
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_delete" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(torrent.id),
),
)
kb_torrent_list.append(
InlineQueryResultArticle(
id=rand(10),
title=torrent.name,
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent.id)
),
"HTML",
disable_web_page_preview=True,
),
reply_markup=torrent_markup,
)
)
if len(kb_torrent_list) == 10:
break
await query.answer(kb_torrent_list[:10], cache_time=0)
return
if "search" in args:
search_arg = " ".join(args.split()[1:]) # transmission search BlaBlaBla
kb_torrent_list = []
for torrent in self.TransmissionClientUserBot.get_torrents():
if search_arg in torrent.name:
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_delete" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(torrent.id),
),
)
kb_torrent_list.append(
InlineQueryResultArticle(
id=rand(20),
title=torrent.name,
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(
torrent.id
)
),
"HTML",
disable_web_page_preview=True,
),
reply_markup=torrent_markup,
)
)
return await query.answer(kb_torrent_list[:10], cache_time=0)
# Inline button handler
async def inline__close(self, call) -> None:
await call.delete()
async def inline_update_torrent(self, call, torrent_id) -> None:
kb = [
[
{
"text": self.strings["kb_update"],
"callback": self.inline_update_torrent,
"args": [torrent_id],
}
],
[
{
"text": self.strings["kb_start"],
"callback": self.inline__start,
"args": [torrent_id],
},
{
"text": self.strings["kb_stop"],
"callback": self.inline__stop,
"args": [torrent_id],
},
],
[
{
"text": self.strings["kb_delete_data"],
"callback": self.inline__delete,
"args": [torrent_id, True],
},
{
"text": self.strings["kb_delete"],
"callback": self.inline__delete,
"args": [torrent_id, False],
},
],
[{"text": self.strings["kb_close"], "callback": self.inline__close}],
]
try:
await call.edit(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent_id)
),
reply_markup=kb,
)
except KeyError:
await call.edit(self.strings["torrent_error"])
async def inline__start(self, call, torrent_id) -> None:
self.TransmissionClientUserBot.get_torrent(torrent_id).start()
await call.answer(self.strings["answer_start"])
async def inline__stop(self, call, torrent_id) -> None:
self.TransmissionClientUserBot.get_torrent(torrent_id).stop()
await call.answer(self.strings["answer_stop"])
async def inline__delete(self, call, torrent_id, delete_data) -> None:
self.TransmissionClientUserBot.remove_torrent(torrent_id, delete_data)
await call.answer(self.strings["answer_delete"])
# Callback buttons (for Inline search)
async def button_callback_handler(self, call: CallbackQuery) -> None:
"""
Process button presses
"""
# await call.answer(call.data, show_alert=True) # Debug
# Update
if call.data[:11] == "cake_update":
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(call.data[11:]),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(call.data[10:]),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(call.data[9:]),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_detete" + str(call.data[11:]),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(call.data[11:]),
),
)
try:
torrent = self.TransmissionClientUserBot.get_torrent(
int(call.data[11:])
)
await self.inline.bot.edit_message_text(
self.stringTorrent(torrent),
reply_markup=torrent_markup,
inline_message_id=call.inline_message_id,
parse_mode="HTML",
)
except KeyError:
await self.inline.bot.edit_message_text(
self.strings["torrent_error"],
inline_message_id=call.inline_message_id,
parse_mode="HTML",
)
except MessageNotModified:
await call.answer(self.strings["inline_answer"])
# Start
if call.data[:10] == "cake_start":
self.TransmissionClientUserBot.get_torrent(int(call.data[11:])).start()
return await call.answer(self.strings["answer_start"])
# Stop
if call.data[:9] == "cake_stop":
self.TransmissionClientUserBot.get_torrent(int(call.data[11:])).stop()
return await call.answer(self.strings["answer_stop"])
# Delete torrent with data
if call.data[:11] == "cake_delete":
self.TransmissionClientUserBot.remove_torrent(int(call.data[11:]), True)
return await call.answer(self.strings["answer_delete"])
# Just delete torrent
if call.data[:11] == "cake_remove":
self.TransmissionClientUserBot.remove_torrent(int(call.data[11:]), False)
return await call.answer(self.strings["answer_delete"])

View File

@@ -0,0 +1,144 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: aiohttp
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
import logging
import aiohttp, asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class MoebooruMod(loader.Module):
"""Module for obtaining art from the ImageBoard yande.re"""
strings = {
"name": "Yandere",
"url": "https://yande.re/post.json",
"vote_url": "https://yande.re/post/vote.json?login={login}&password_hash={password_hash}",
"vote_ok": "OK!",
"vote_login": "Login or password incorrect.",
"vote_error": "ERROR, .logs 40 or .logs error",
"cfg_yandere_login": "Login from yande.re",
"cfg_yandere_password_hash": "SHA1 hashed password",
}
strings_ru = {
"vote_login": "Неверный логин или пароль.",
"vote_error": "ОШИБКА, .logs 40 или .logs error",
"cfg_yandere_login": "Войти через yande.re",
"cfg_yandere_password_hash": "Хэшированный пароль SHA1",
}
def __init__(self):
self.config = loader.ModuleConfig(
"yandere_login",
"None",
lambda m: self.strings("cfg_yandere_login", m),
"yandere_password_hash",
"None",
lambda m: self.strings("cfg_yandere_password_hash", m),
)
self.name = self.strings["name"]
def string_builder(self, json):
string = f"Tags : {json['tags']}\n"
string += f"©️ : {json['author'] or 'No author'}\n"
string += f"🔗 : {json['source'] or 'No source'}\n\n"
string += (
f"🆔 : <a href=https://yande.re/post/show/{json['id']}>{json['id']}</a>"
)
return string
@loader.unrestricted
@loader.ratelimit
async def ylastcmd(self, message):
"""The last posted art"""
args = utils.get_args(message)
await message.delete()
params = f"?login={self.config['yandere_login']}&password_hash={self.config['yandere_password_hash']}&tags="
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yrandomcmd(self, message):
"""Random posted art"""
args = utils.get_args(message)
await message.delete()
params = f"?login={self.config['yandere_login']}&password_hash={self.config['yandere_password_hash']}&tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yvotecmd(self, message):
"""
Vote for art
Bad = -1, None = 0, Good = 1, Great = 2, Favorite = 3
"""
reply = await message.get_reply_message()
args = utils.get_args(message)
if reply and args:
yandere_id = reply.raw_text.split("🆔")[1][2:]
params = {"id": yandere_id, "score": args[0]}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
if result_code == 200:
await utils.answer(message, self.strings("vote_ok"))
elif result_code == 403:
await utils.answer(message, self.strings("vote_login"))
else:
await utils.answer(message, self.strings("vote_error"))
await asyncio.sleep(5)
await message.delete()
return
await utils.answer(message, "Pls code! Check help Yandere")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,311 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 1)
# requires: aiohttp
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
import logging
import aiohttp
import asyncio
from .. import loader, main, utils
from ..inline import GeekInlineQuery, rand
from aiogram.types import InlineQueryResultPhoto
from aiogram.utils.markdown import quote_html
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class InlineMoebooruMod(loader.Module):
"""Module for obtaining art from the ImageBoard yande.re"""
strings = {
"name": "InlineYandere",
"url": "https://yande.re/post.json",
"vote_url": "https://yande.re/post/vote.json?login={login}&password_hash={password_hash}",
"vote_text": "Vote for this art. The buttons are only available to me",
"vote_ok": "OK!",
"vote_login": "Login or password incorrect.",
"vote_error": "ERROR, .logs 40 or .logs error",
"cfg_yandere_login": "Login from yande.re",
"cfg_yandere_password_hash": "SHA1 hashed password",
}
strings_ru = {
"vote_text": "Голосуйте за этот арт. Кнопки доступны только мне",
"vote_login": "Неверный логин или пароль.",
"vote_error": "ОШИБКА, .logs 40 или .logs error",
"cfg_yandere_login": "Войти через yande.re",
"cfg_yandere_password_hash": "Хэшированный пароль SHA1",
}
def __init__(self):
self.config = loader.ModuleConfig(
"yandere_login",
"None",
lambda m: self.strings("cfg_yandere_login", m),
"yandere_password_hash",
"None",
lambda m: self.strings("cfg_yandere_password_hash", m),
)
self.name = self.strings["name"]
async def client_ready(self, client, db) -> None:
self.db = db
self.client = client
def string_builder(self, json):
string = f"Tags : {quote_html(json['tags'])}\n"
string += (
f"©️ : {quote_html(json['author']) if json['author'] else 'No author'}\n"
)
string += (
f"🔗 : {quote_html(json['source']) if json['source'] else 'No source'}\n\n"
)
string += f"🆔 : https://yande.re/post/show/{json['id']}"
return string
@loader.unrestricted
@loader.ratelimit
async def ylastcmd(self, message):
"""The last posted art"""
await message.delete()
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"]) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yrandomcmd(self, message):
"""The random posted art"""
await message.delete()
params = "?tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yvotecmd(self, message) -> None:
"""
Vote for art
Bad = -1, None = 0, Good = 1, Great = 2, Favorite = 3
"""
reply = await message.get_reply_message()
args = utils.get_args(message)
if reply and args:
yandere_id = reply.raw_text.split("🆔")[1].split("/")[5]
params = {"id": yandere_id, "score": args[0]}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
if result_code == 200:
await utils.answer(message, self.strings("vote_ok"))
elif result_code == 403:
await utils.answer(message, self.strings("vote_login"))
else:
await utils.answer(message, self.strings("vote_error"))
await asyncio.sleep(5)
await message.delete()
return
elif reply:
yandere_id = reply.raw_text.split("🆔")[1][2:]
kb = [
[
{
"text": "Bad",
"callback": self.inline__vote,
"args": [-1, yandere_id],
}
],
[
{
"text": "Good",
"callback": self.inline__vote,
"args": [1, yandere_id],
}
],
[
{
"text": "Great",
"callback": self.inline__vote,
"args": [2, yandere_id],
}
],
[
{
"text": "Favorite",
"callback": self.inline__vote,
"args": [3, yandere_id],
}
],
]
await self.inline.form(
self.strings["vote_text"],
message=message,
reply_markup=kb,
always_allow=self.client.dispatcher.security._owner,
)
return
await utils.answer(message, "Pls code! Check help Yandere")
await asyncio.sleep(5)
await message.delete()
# Inline commands
async def ylast_inline_handler(self, query: GeekInlineQuery) -> None:
"""
The last posted art (Inline)
@allow: all
"""
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"]) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
async def yrandom_inline_handler(self, query: GeekInlineQuery) -> None:
"""
The random posted art (Inline)
@allow: all
"""
params = "?tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
async def ysearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Search art by tags. (https://yande.re/help)
@allow: all
"""
text = query.args
if not text:
return
params = "?tags=order:random " + text
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
# Inline button handler
async def inline__close(self, call: "aiogram.types.CallbackQuery") -> None:
await call.delete()
async def inline__vote(self, call, score, _id) -> None:
params = {"id": _id, "score": score}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
kb = [[{"text": "🚫 Close", "callback": self.inline__close}]]
if result_code == 200:
await call.edit(self.strings("vote_ok"), reply_markup=kb)
elif result_code == 403:
await call.edit(self.strings("vote_login"), reply_markup=kb)
else:
await call.edit(self.strings("vote_error"), reply_markup=kb)

62
D4n13l3k00/FTG-Modules/.gitignore vendored Normal file
View File

@@ -0,0 +1,62 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
.env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
stuf

View File

@@ -0,0 +1,4 @@
{
"python.pythonPath": "C:\\Users\\D4n13l3k00\\AppData\\Local\\Programs\\Python\\Python39\\python.exe",
"python.analysis.typeCheckingMode": "off"
}

View File

@@ -0,0 +1,346 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: pydub numpy requests
import io
import math
import re
import aiohttp
import numpy as np
from pydub import AudioSegment, effects
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class AudioEditorMod(loader.Module):
"""Module for working with sound"""
strings = {
"name": "AudioEditor",
"downloading": "<b>[{}]</b> Downloading...",
"working": "<b>[{}]</b> Working...",
"exporting": "<b>[{}]</b> Exporting...",
"set_value": "<b>[{}]</b> Specify the level from {} to {}...",
"reply": "<b>[{}]</b> reply to audio...",
"set_fmt": "<b>[{}]</b> Specify the format of output audio...",
"set_time": "<b>[{}]</b> Specify the time in the format start(ms):end(ms)",
}
@loader.owner
async def basscmd(self, m):
""".bass [level bass'а 2-100 (Default 2)] <reply to audio>
BassBoost"""
args = utils.get_args_raw(m)
if not args:
lvl = 2.0
elif re.match(r"^\d+(\.\d+)?$", args) and (1.0 < float(args) < 100.1):
lvl = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("BassBoost", 2.0, 100.0)
)
audio = await self.get_audio(m, "BassBoost")
if not audio:
return
sample_track = list(audio.audio.get_array_of_samples())
out = (audio.audio - 0).overlay(
audio.audio.low_pass_filter(
int(
round(
(
3 * np.std(sample_track) / (math.sqrt(2))
- np.mean(sample_track)
)
* 0.005
)
)
)
+ lvl
)
await self.send_audio(m, audio, out, audio.pref, f"{audio.pref} {lvl}lvl")
@loader.owner
async def fvcmd(self, m):
""".fv [level 2-100 (Default 25)] <reply to audio>
Distort"""
args = utils.get_args_raw(m)
if not args:
lvl = 25.0
elif re.match(r"^\d+(\.\d+)?$", args) and (1.0 < float(args) < 100.1):
lvl = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Distort", 2.0, 100.0)
)
audio = await self.get_audio(m, "Distort")
if not audio:
return
out = audio.audio + lvl
await self.send_audio(m, audio, out, audio.pref, f"{audio.pref} {lvl}lvl")
@loader.owner
async def echoscmd(self, m):
""".echos <reply to audio>
Echo effect"""
audio = await self.get_audio(m, "Echo")
if not audio:
return
out = AudioSegment.empty()
n = 200
none = io.BytesIO()
out += audio.audio + AudioSegment.from_file(none)
for _ in range(5):
audio.audio - 10
out = out.overlay(audio.audio, n)
n += 200
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def volupcmd(self, m):
""".volup <reply to audio>
VolUp 10dB"""
audio = await self.get_audio(m, "+10dB")
if not audio:
return
out = audio.audio + 10
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def voldwcmd(self, m):
""".voldw <reply to audio>
VolDw 10dB"""
audio = await self.get_audio(m, "-10dB")
if not audio:
return
out = audio.audio - 10
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def revscmd(self, m):
""".revs <reply to audio>
Reverse audio"""
audio = await self.get_audio(m, "Reverse")
if not audio:
return
out = audio.audio.reverse()
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def repscmd(self, m):
""".reps <reply to audio>
Repeat audio 2 times"""
audio = await self.get_audio(m, "Repeat")
if not audio:
return
out = audio.audio * 2
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def slowscmd(self, m):
""".slows <reply to audio>
SlowDown 0.5x"""
audio = await self.get_audio(m, "SlowDown")
if not audio:
return
s2 = audio.audio._spawn(
audio.audio.raw_data,
overrides={"frame_rate": int(audio.audio.frame_rate * 0.5)},
)
out = s2.set_frame_rate(audio.audio.frame_rate)
await self.send_audio(
audio.message, audio, out, audio.pref, audio.pref, audio.duration * 2
)
@loader.owner
async def fastscmd(self, m):
""".fasts <reply to audio>
SpeedUp 1.5x"""
audio = await self.get_audio(m, "SpeedUp")
if not audio:
return
s2 = audio.audio._spawn(
audio.audio.raw_data,
overrides={"frame_rate": int(audio.audio.frame_rate * 1.5)},
)
out = s2.set_frame_rate(audio.audio.frame_rate)
await self.send_audio(
audio.message,
audio,
out,
audio.pref,
audio.pref,
round(audio.duration / 2),
)
@loader.owner
async def rightscmd(self, m):
""".rights <reply to audio>
Push sound to right channel"""
audio = await self.get_audio(m, "Right channel")
if not audio:
return
out = effects.pan(audio.audio, +1.0)
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def leftscmd(self, m):
""".lefts <reply to audio>
Push sound to left channel"""
audio = await self.get_audio(m, "Left channel")
if not audio:
return
out = effects.pan(audio.audio, -1.0)
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def normscmd(self, m):
""".norms <reply to audio>
Normalize sound (from quiet to normal)"""
audio = await self.get_audio(m, "Normalization")
if not audio:
return
out = effects.normalize(audio.audio)
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def tovscmd(self, m):
""".tovs <reply to audio>
Convert to voice message"""
audio = await self.get_audio(m, "Voice")
if not audio:
return
audio.voice = True
await self.send_audio(audio.message, audio, audio.audio, audio.pref, audio.pref)
@loader.owner
async def convscmd(self, m):
""".convs <reply to audio> [audio_format (ex. `mp3`)]
Convert audio to some format"""
f = utils.get_args(m)
if not f:
return await utils.answer(m, self.strings("set_fmt", m).format("Converter"))
audio = await self.get_audio(m, "Converter")
if not audio:
return
await self.send_audio(
audio.message,
audio,
audio.audio,
audio.pref,
f"Converted to {f[0].lower()}",
fmt=f[0].lower(),
)
@loader.owner
async def byrobertscmd(self, m):
'''.byroberts <reply to audio>
Add at the end "Directed by Robert B Weide"'''
audio = await self.get_audio(m, "Directed by...")
if not audio:
return
async with aiohttp.ClientSession() as s, s.get(
"https://raw.githubusercontent.com/D4n13l3k00/files-for-modules/master/directed.mp3"
) as r:
out = audio.audio + AudioSegment.from_file(
io.BytesIO(await r.read())
).apply_gain(+8)
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
@loader.owner
async def cutscmd(self, m):
""".cuts <start(ms):end(ms)> <reply to audio>
Cut audio"""
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("set_time", m).format("Cut"))
r = re.compile(r"^(?P<start>\d+){0,1}:(?P<end>\d+){0,1}$")
ee = r.match(args)
if not ee:
return await utils.answer(m, self.strings("set_time", m).format("Cut"))
start = int(ee["start"]) if ee["start"] else 0
end = int(ee["end"]) if ee["end"] else 0
audio = await self.get_audio(m, "Cut")
if not audio:
return
out = audio.audio[start : end or len(audio.audio) - 1]
await self.send_audio(audio.message, audio, out, audio.pref, audio.pref)
class AudioEditorClass:
audio = None
message = None
duration = None
voice = None
pref = None
reply = None
async def get_audio(self, m, pref):
r = await m.get_reply_message()
if r and r.file and r.file.mime_type.split("/")[0] in ["audio", "video"]:
ae = self.AudioEditorClass()
ae.pref = pref
ae.reply = r
ae.voice = (
r.document.attributes[0].voice
if r.file.mime_type.split("/")[0] == "audio"
else False
)
ae.duration = r.document.attributes[0].duration
ae.message = await utils.answer(
m, self.strings("downloading", m).format(pref)
)
ae.audio = AudioSegment.from_file(io.BytesIO(await r.download_media(bytes)))
ae.message = await utils.answer(
ae.message, self.strings("working", m).format(pref)
)
return ae
await utils.answer(m, self.strings("reply", m).format(pref))
return None
async def send_audio(self, message, audio, out, pref, title, fs=None, fmt="mp3"):
out_file = io.BytesIO()
out_file.name = "audio." + ("ogg" if audio.voice else "mp3")
if audio.voice:
out.split_to_mono()
message = await utils.answer(message, self.strings("exporting").format(pref))
out.export(
out_file,
format="ogg" if audio.voice else fmt,
bitrate="64k" if audio.voice else None,
codec="libopus" if audio.voice else None,
)
out_file.seek(0)
await utils.answer(
message,
out_file,
reply_to=audio.reply.id,
voice_note=audio.voice,
attributes=None
if audio.voice
else [
types.DocumentAttributeAudio(
duration=fs or audio.duration,
title=title,
performer="AudioEditor",
)
],
)

View File

@@ -0,0 +1,80 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import os
from telethon import functions, types
from .. import loader, utils # type: ignore
@loader.tds
class AvaMod(loader.Module):
"""Установка/удаление аватарок через команды"""
strings = {
"name": "AvatarMod",
"need_pic": "<b>[Avatar]</b> Нужно фото",
"downloading": "<b>[Avatar]</b> Скачиваю",
"installing": "<b>[Avatar]</b> Устанавливаю",
"deleting": "<b>[Avatar]</b> Удаляю",
"ok": "<b>[Avatar]</b> Готово",
"no_avatar": "<b>[Avatar]</b> Нету аватарки/ок",
}
async def avacmd(self, m: types.Message):
".ava <reply_to_photo> - Установить аватар"
client = m.client
reply = await m.get_reply_message()
if not reply and not reply.photo:
return await utils.answer(m, self.strings("need_pic"))
m = await utils.answer(m, self.strings("downloading"))
photo = await client.download_media(message=reply.photo)
up = await client.upload_file(photo)
m = await utils.answer(m, self.strings("installing"))
await client(functions.photos.UploadProfilePhotoRequest(up))
await utils.answer(m, self.strings("ok"))
os.remove(photo)
async def delavacmd(self, m: types.Message):
"Удалить текущую аватарку"
client = m.client
ava = await client.get_profile_photos("me", limit=1)
if len(ava) > 0:
m = await utils.answer(m, self.strings("deleting"))
await client(functions.photos.DeletePhotosRequest(ava))
await utils.answer(m, self.strings("ok"))
else:
await utils.answer(m, self.strings("no_avatar"))
async def delavascmd(self, m: types.Message):
"Удалить все аватарки"
client = m.client
ava = await client.get_profile_photos("me")
if len(ava) > 0:
m = await utils.answer(m, self.strings("deleting"))
await client(
functions.photos.DeletePhotosRequest(
await m.client.get_profile_photos("me")
)
)
await utils.answer(m, self.strings("ok"))
else:
await utils.answer(m, self.strings("no_avatar"))

View File

@@ -0,0 +1,118 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import ast
import io
from .. import loader, utils # type: ignore
@loader.tds
class BackupManMod(loader.Module):
"""BackupMan"""
strings = {"name": "BackupMan"}
async def client_ready(self, _, db):
self._db = db
@loader.owner
async def restmcmd(self, m):
"Установить все модули из *.bkm файла"
reply = await m.get_reply_message()
if not reply or not reply.file or reply.file.name.split(".")[-1] != "bkm":
return await m.edit("<b>[BackupMan]</b> Reply to <code>*.bkm</code> file")
modules = self._db.get("friendly-telegram.modules.loader", "loaded_modules", [])
txt = io.BytesIO(await reply.download_media(bytes))
valid, already_loaded = 0, 0
for i in txt.read().decode("utf-8").split("\n"):
if i not in modules:
valid += 1
modules.append(i)
else:
already_loaded += 1
self._db.set("friendly-telegram.modules.loader", "loaded_modules", modules)
await m.edit(
"<b>[BackupMan]</b>\n\n"
"<i>Загружено модулей:</i> <code>{valid}</code>\n"
"<i>Загружены ранее:</i> <code>{already_loaded}</code>\n\n"
+ (
"<b>> Юзербот автоматически перезагрузится</b>"
if valid != 0
else "<b>> Ничего не загружено</b>"
)
)
if valid != 0:
await self.allmodules.commands["restart"](await m.respond("_"))
@loader.owner
async def backmcmd(self, m):
"Сделать бэкап модулей в *.bkm файл"
modules = self._db.get("friendly-telegram.modules.loader", "loaded_modules", [])
txt = io.BytesIO("\n".join(modules).encode("utf-8"))
txt.name = f"BackupMan-{(await m.client.get_me()).id}.bkm"
await m.client.send_file(
m.to_id,
txt,
caption="<b>[BackupMan]</b> <i>Бэкап модулей</i>\n"
f"<i>Модулей:</i> <code>{len(modules)}</code>\n"
"<i>Для загрузки бэкапа используй модуль:</i>\n"
"<code>.dlmod https://d4n13l3k00.ru/modules/BackupMan.py</code>",
)
await m.delete()
@loader.owner
async def restncmd(self, m):
"Установить все заметки из *.bkn файла\n<f> - Заменять уже существующие заметки"
args: list or None = utils.get_args_raw(m)
force = "f" in args.lower()
reply = await m.get_reply_message()
if not reply or not reply.file or reply.file.name.split(".")[-1] != "bkn":
return await m.edit("<b>[BackupMan]</b> Reply to <code>*.bkn</code> file")
notes = self._db.get("friendly-telegram.modules.notes", "notes", {})
txt = io.BytesIO(await reply.download_media(bytes))
valid, already_loaded = 0, 0
for k, v in ast.literal_eval(txt.read().decode("utf-8")).items():
if k not in notes or force:
notes[k] = v
valid += 1
else:
already_loaded += 1
self._db.set("friendly-telegram.modules.notes", "notes", notes)
await m.edit(
"<b>[BackupMan]</b>\n\n"
f"<i>Загружено/заменено заметок:</i> <code>{valid}</code>\n"
f"<i>Загружены ранее:</i> <code>{already_loaded}</code>"
)
@loader.owner
async def backncmd(self, m):
"Сделать бэкап заметок в *.bkn файл"
modules = self._db.get("friendly-telegram.modules.notes", "notes", {})
txt = io.BytesIO(str(modules).encode("utf-8"))
txt.name = f"BackupMan-{(await m.client.get_me()).id}.bkn"
await m.client.send_file(
m.to_id,
txt,
caption=f"<b>[BackupMan]</b> <i>Бэкап заметок</i>\n"
f"<i>Заметок:</i> <code>{len(modules)}</code>\n"
"<i>Для загрузки бэкапа используй модуль:</i>\n"
"<code>.dlmod https://d4n13l3k00.ru/modules/BackupMan.py</code>",
)
await m.delete()

View File

@@ -0,0 +1,151 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import asyncio
import io
import logging
from typing import List
import aiohttp
import pydantic
import telethon
from telethon import types
from telethon.events import ChatAction
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights
from .. import loader, utils # type: ignore
@loader.tds
class CaptchaMod(loader.Module):
"Captcha for chats"
strings = {
"name": "Captcha",
"pls_pass_captcha": '<a href="tg://user?id={}">Хэй</a>, пройди капчу! У тебя одна попытка\n'
"Иначе получишь бан навсегда!",
"captcha_status": "<b>[Captcha]</b> {}",
}
class CUserModel(pydantic.BaseModel):
chat: int
user: int
message: int
answer: str
async def client_ready(self, _, db):
self.db = db
self.log = logging.getLogger(__name__)
self._db = "CaptchaMod"
self.locked_users: List[self.CUserModel] = []
async def watcher(self, m):
"Watcher"
client: telethon.TelegramClient = m.client
if isinstance(m, ChatAction.Event):
if m.chat_id not in self.db.get(self._db, "chats", []):
return
if m.user_added or m.user_joined:
users = [i.id for i in m.users]
for u in users:
_u = await client.get_entity(u)
if _u.bot:
continue
async with aiohttp.ClientSession() as s, s.get(
"https://api.d4n13l3k00.ru/captcha/generate"
) as r:
answer = r.headers["Captcha-Code"]
im = io.BytesIO(await r.read())
im.name = "@DekFTGModules_captcha.png"
m = await client.send_file(
m.chat,
im,
caption=self.strings("pls_pass_captcha").format(u),
)
self.locked_users.append(
self.CUserModel(
chat=m.chat_id, user=u, message=m.id, answer=answer
)
)
await asyncio.sleep(60)
l: List[self.CUserModel] = list(
filter(
lambda x: x.chat == m.chat_id and x.user in users,
self.locked_users,
)
)
if l:
for u in l:
self.locked_users.remove(u)
await (
await client.get_messages(u.chat, ids=u.message)
).delete()
await client(
EditBannedRequest(
u.chat,
u.user,
ChatBannedRights(until_date=None, view_messages=True),
)
)
elif m.user_kicked or m.user_left:
users = [i.id for i in m.users]
for u in users:
l: List[self.CUserModel] = list(
filter(
lambda x: x.chat == m.chat_id and x.user == u,
self.locked_users,
)
)
if l:
ntt = l[0]
self.locked_users.remove(ntt)
return
if isinstance(m, types.Message):
client: telethon.TelegramClient = m.client
l: List[self.CUserModel] = list(
filter(
lambda x: x.chat == m.chat_id and x.user == m.sender_id,
self.locked_users,
)
)
if l:
ntt = l[0]
self.locked_users.remove(ntt)
await (await client.get_messages(ntt.chat, ids=ntt.message)).delete()
await m.delete()
if ntt.answer.lower() != m.raw_text.lower():
await client(
EditBannedRequest(
ntt.chat,
ntt.user,
ChatBannedRights(until_date=None, view_messages=True),
)
)
async def swcaptchacmd(self, m: types.Message):
"Turn on/off captcha in chat"
l: list = self.db.get(self._db, "chats", [])
if m.chat_id in l:
l.remove(m.chat_id)
self.db.set(self._db, "chats", l)
return await utils.answer(m, self.strings("captcha_status").format("OFF"))
l.append(m.chat_id)
self.db.set(self._db, "chats", l)
await utils.answer(m, self.strings("captcha_status").format("ON"))

View File

@@ -0,0 +1,129 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from telethon.tl.types import (
InputMessagesFilterPhotos,
InputMessagesFilterVideo,
InputMessagesFilterVoice,
InputMessagesFilterMusic,
InputMessagesFilterDocument,
InputMessagesFilterContacts,
InputMessagesFilterGeo,
InputMessagesFilterRoundVideo,
InputMessagesFilterUrl,
InputMessagesFilterGif,
)
from .. import loader # type: ignore
@loader.tds
class ChatStatisticMod(loader.Module):
"Статистика чата"
strings = {"name": "ChatStatistic"}
@loader.owner
async def statacmd(self, m):
await m.edit("<b>Считаем...</b>")
al = str((await m.client.get_messages(m.to_id, limit=0)).total)
ph = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterPhotos()
)
).total
)
vi = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterVideo()
)
).total
)
mu = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterMusic()
)
).total
)
vo = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterVoice()
)
).total
)
vv = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterRoundVideo()
)
).total
)
do = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterDocument()
)
).total
)
urls = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterUrl()
)
).total
)
gifs = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterGif()
)
).total
)
geos = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterGeo()
)
).total
)
cont = str(
(
await m.client.get_messages(
m.to_id, limit=0, filter=InputMessagesFilterContacts()
)
).total
)
await m.edit(
(
"<b>Всего сoообщений</b> {}\n"
+ "<b>Фоток:</b> {}\n"
+ "<b>Видосов:</b> {}\n"
+ "<b>Попсы:</b> {}\n"
+ "<b>Голосовых:</b> {}\n"
+ "<b>Кругляшков:</b> {}\n"
+ "<b>Файлов:</b> {}\n"
+ "<b>Ссылок:</b> {}\n"
+ "<b>Гифок:</b> {}\n"
+ "<b>Координат:</b> {}\n"
+ "<b>Контактов:</b> {}"
).format(al, ph, vi, mu, vo, vv, do, urls, gifs, geos, cont)
)

View File

@@ -0,0 +1,223 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import re
from typing import *
import pytgcalls
import youtube_dl
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.input_stream.quality import HighQualityAudio, HighQualityVideo
from telethon import types
from .. import loader, utils # type: ignore
# meta developer: @D4n13l3k00
# requires: py-tgcalls youtube-dl
@loader.tds
class ChatVoiceMod(loader.Module):
"""Module for working with voicechat"""
strings = {
"name": "ChatVoiceMod",
"downloading": "<b>[ChatVoiceMod]</b> Downloading...",
"playing": "<b>[ChatVoiceMod]</b> Playing...",
"notjoined": "<b>[ChatVoiceMod]</b> You are not joined",
"stop": "<b>[ChatVoiceMod]</b> Playing stopped!",
"leave": "<b>[ChatVoiceMod]</b> Leaved!",
"pause": "<b>[ChatVoiceMod]</b> Paused!",
"resume": "<b>[ChatVoiceMod]</b> Resumed!",
"mute": "<b>[ChatVoiceMod]</b> Muted!",
"unmute": "<b>[ChatVoiceMod]</b> Unmuted!",
"error": "<b>[ChatVoiceMod]</b> Error: <code>{}</code>",
"noargs": "<b>[ChatVoiceMod]</b> No args",
"noreply": "<b>[ChatVoiceMod]</b> No reply",
"nofile": "<b>[ChatVoiceMod]</b> No file",
"nofiles": "<b>[ChatVoiceMod]</b> No files",
"deleted": "<b>[ChatVoiceMod]</b> <code>{}</code> successfully deleted",
"downloaded": "<b>[ChatVoiceMod]</b> Downloaded to <code>dl/{0}</code>. For playing use:\n<code>.cplaya dl/{0}</code>\n<code>.cplayv dl/{0}</code>",
}
async def client_ready(self, client, _):
self.client = client
self.call = PyTgCalls(client)
@self.call.on_stream_end()
async def _(_, update):
with contextlib.suppress(Exception):
await self.call.leave_group_call(update.chat_id)
await self.call.start()
async def parse_args(self, args):
if not args or not re.match(
r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?",
args,
):
return args
with youtube_dl.YoutubeDL({"format": "best"}) as ydl:
info = ydl.extract_info(args, download=False)
return info["formats"][0]["url"]
async def cdlcmd(self, m: types.Message):
"<reply_to_media> <name: optional> - Download media to server in `dl` folder"
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, self.strings("noreply"))
name = args or reply.file.name
try:
m = await utils.answer(m, self.strings("downloading"))
await reply.download_media(f"dl/{name}")
await utils.answer(m, self.strings("downloaded").format(name))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def clscmd(self, m: types.Message):
"List all files in `dl` folder"
if not os.path.isdir("dl") or not os.listdir("dl"):
return await utils.answer(m, self.strings("nofiles"))
files = [f"<code>dl/{f}</code>" for f in os.listdir("dl")]
await utils.answer(m, "\n".join(files))
# command for deleting file from dl folder
async def cdelcmd(self, m: types.Message):
"<name> - Delete file from `dl` folder"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("noargs"))
if not args.startswith("dl/"):
args = f"dl/{args}"
if not os.path.isfile(f"{args}"):
return await utils.answer(m, self.strings("nofile"))
try:
os.remove(f"{args}")
await utils.answer(m, self.strings("deleted").format(args))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayvcmd(self, m: types.Message):
"<link/path/reply_to_video> - Play video in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioVideoPiped(
path,
HighQualityAudio(),
HighQualityVideo(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayacmd(self, m: types.Message):
"<link/path/reply_to_audio> - Play audio in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioPiped(
path,
HighQualityAudio(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cleavecmd(self, m: types.Message):
"Leave"
try:
self.call.get_active_call(m.chat.id)
await self.call.leave_group_call(m.chat.id)
await utils.answer(m, self.strings("leave"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cmutecmd(self, m: types.Message):
"Mute"
try:
self.call.get_active_call(m.chat.id)
await self.call.mute_stream(m.chat.id)
await utils.answer(m, self.strings("mute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cunmutecmd(self, m: types.Message):
"Unmute"
try:
self.call.get_active_call(m.chat.id)
await self.call.unmute_stream(m.chat.id)
await utils.answer(m, self.strings("unmute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cpausecmd(self, m: types.Message):
"Pause"
try:
self.call.get_active_call(m.chat.id)
await self.call.pause_stream(m.chat.id)
await utils.answer(m, self.strings("pause"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cresumecmd(self, m: types.Message):
"Resume"
try:
self.call.get_active_call(m.chat.id)
await self.call.resume_stream(m.chat.id)
await utils.answer(m, self.strings("resume"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))

View File

@@ -0,0 +1,85 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import aiohttp
from .. import loader, utils # type: ignore
@loader.tds
class CheckerTGMod(loader.Module):
"""CheckerTG"""
strings = {
"name": "CheckerTG",
"check": "<b>[CheckerAPI]</b> Делаем запрос к API...",
"response": "<b>[CheckerAPI]</b> Ответ API: <code>{}</code>\nВремя выполнения: <code>{}</code>",
}
@loader.owner
async def checkcmd(self, m):
"""Проверить id на слитый номер
Жуёт либо <reply> либо <uid>
"""
reply = await m.get_reply_message()
if utils.get_args_raw(m):
user = utils.get_args_raw(m)
elif reply:
try:
user = str(reply.sender.id)
except Exception:
return await m.edit("<b>Err</b>")
else:
return await m.edit("[CheckerAPI] А кого чекать?")
await m.edit(self.strings["check"])
async with aiohttp.ClientSession() as s, s.get(
f"https://api.d4n13l3k00.ru/tg/leaked/check?uid={user}"
) as r:
r = await r.json()
await m.edit(
self.strings["response"].format(
r["data"], str(round(r["time"], 3)) + "ms"
)
)
@loader.owner
async def rcheckcmd(self, m):
"""Обратный поиск
Жуёт <phone number>
"""
reply = await m.get_reply_message()
if utils.get_args_raw(m):
phone = utils.get_args_raw(m)
elif reply:
try:
phone = reply.raw_text
except Exception:
return await m.edit("<b>Err</b>")
else:
return await m.edit("[CheckerAPI] А кого чекать?")
await m.edit(self.strings["check"])
async with aiohttp.ClientSession() as s, s.get(
f"https://api.d4n13l3k00.ru/tg/leaked/check?r=1?uid={phone}"
) as r:
r = await r.json()
await m.edit(
self.strings["response"].format(
r["data"], str(round(r["time"], 3)) + "ms"
)
)

View File

@@ -0,0 +1,106 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from asyncio import sleep
from telethon import functions
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.tl.functions.users import GetFullUserRequest
from .. import loader, utils # type: ignore
@loader.tds
class CuMod(loader.Module):
"""Полное копирование юзера(ава, имя|фамилия, био)"""
strings = {"name": "CopyUser"}
@loader.owner
async def cucmd(self, message):
""".cu <s> <a> <reply/@username>
<s> - Скрытый режим
<a> - Удалить ваши аватарки
Аргументы после юзера не указывайте, не скушает
Примеры:
.cu s @user/reply
.cu a @user/reply
.cu s a @user/reply"""
reply = await message.get_reply_message()
user = None
s = False
a = False
if utils.get_args_raw(message):
args = utils.get_args_raw(message).split(" ")
for i in args:
if i.lower() == "s":
s = True
elif i.lower() in ["а", "a"]:
a = True
else:
try:
user = await message.client.get_entity(i)
break
except Exception:
continue
if user is None and reply is not None:
user = reply.sender
if user is None and reply is None:
if not s:
await message.edit("Кого?")
return
if s:
await message.delete()
if not s:
for i in range(11):
await message.edit(
f"Получаем доступ к аккаунту пользователя [{i*10}%]\n[{(i*'#').ljust(10, '')}]"
)
await sleep(0.3)
if a:
avs = await message.client.get_profile_photos("me")
if len(avs) > 0:
await message.client(
functions.photos.DeletePhotosRequest(
await message.client.get_profile_photos("me")
)
)
full = await message.client(GetFullUserRequest(user.id))
if not s:
await message.edit("Получаем аватарку... [35%]\n[###]")
if full.profile_photo:
up = await message.client.upload_file(
await message.client.download_profile_photo(user, bytes)
)
if not s:
await message.edit("Ставим аватарку... [50%]\n[#####]")
await message.client(functions.photos.UploadProfilePhotoRequest(up))
if not s:
await message.edit("Получаем данные... [99%]\n[#########]")
await message.client(
UpdateProfileRequest(
user.first_name if user.first_name is not None else "",
user.last_name if user.last_name is not None else "",
full.about[:70] if full.about is not None else "",
)
)
if not s:
await message.edit("Аккаунт клонирован! [100%]\n[##########]")
await sleep(5)
await message.edit("Аккаунт клонирован!")

View File

@@ -0,0 +1,181 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import base64
import io
from typing import List
import aiohttp
from PIL import Image
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class CraiyonMod(loader.Module):
"Craiyon - Mini DALL-E for FTG"
strings = {
"name": "Craiyon",
"preparing": "<b>[Craiyon] 📥 Preparing...</b>",
"generating": "<b>[Craiyon] ✨ Generating images...</b>",
"uploading": "<b>[Craiyon] 📤 Uploading images...</b>",
"result_with_url": "<b>[Craiyon] 🎉 Generated images:</b>\n{}",
"error": "<b>[Craiyon]\n❌ Python error:</b>\n<code>{}</code>\n<b> 📜 Response of server:</b>\n<code>{}</code>",
}
async def client_ready(self, client, db):
self.me = await client.get_me()
self.telegraph_short_name = "Craiyon-FTG"
self.telegraph_author_name = (
f"@{self.me.username or self.me.id} via Craiyon-FTG by @DekFTGModules"
)
self.telegraph_author_url = "https://t.me/DekFTGModules"
self.db = db
class NullResponseError(Exception):
"""Raised when the response is null or has no 'images' key"""
pass
@loader.owner
async def craiyoncmd(self, m: types.Message):
".craiyon <text> - Generate images with text using Craiyon (Mini DALL-E)"
args = utils.get_args_raw(m)
async with aiohttp.ClientSession() as session:
m = await utils.answer(m, self.strings("preparing", m))
async with session.post(
"https://api.telegra.ph/createAccount",
json={
"short_name": self.telegraph_short_name,
"author_name": self.telegraph_author_name,
"author_url": self.telegraph_author_url,
},
) as resp:
try:
data = await resp.json(content_type=None)
if "error" in data:
raise self.NullResponseError(
"No images in response (has no 'images' key)"
)
except Exception as e:
err_json = await resp.text()
await utils.answer(
m, self.strings("error", m).format(str(e), err_json)
)
return
try:
self.author_name = data["result"]["author_name"]
self.author_url = data["result"]["author_url"]
self.access_token = data["result"]["access_token"]
except KeyError:
await utils.answer(
m,
self.strings("error", m).format(
"No author_name, author_url or access_token in response",
data,
),
)
return
m = await utils.answer(m, self.strings("generating", m))
async with session.post(
"https://backend.craiyon.com/generate",
json={
"prompt": args,
},
headers={
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0",
},
) as resp:
try:
data = await resp.json(content_type=None)
if "images" not in data:
raise self.NullResponseError(
"No images in response (has no 'images' key)"
)
except Exception as e:
err_json = await resp.text()
await utils.answer(
m, self.strings("error", m).format(str(e), err_json)
)
return
imgs: List[io.BytesIO] = []
uploaded_imgs = []
await utils.answer(m, self.strings("uploading", m))
for i in data["images"]:
image_data = base64.b64decode(i.encode())
image = Image.open(io.BytesIO(image_data))
image_buffer = io.BytesIO()
image.save(image_buffer, format="JPEG")
imgs.append(image_buffer)
for i, img in enumerate(imgs, 1):
img.name = f"craiyon-{i}.jpg"
file = aiohttp.FormData()
file.add_field("file", img.getvalue(), content_type="image/jpeg")
async with session.post(
"https://telegra.ph/upload", data=file
) as resp:
try:
data = await resp.json(content_type=None)
if "error" in data:
raise self.NullResponseError(
"Error API: {}".format(data)
)
uploaded_imgs.append(data[0]["src"])
except Exception as e:
err_json = await resp.text()
await utils.answer(
m, self.strings("error", m).format(str(e), err_json)
)
return
async with session.post(
"https://api.telegra.ph/createPage",
json={
"title": "Craiyon-FTG",
"content": [
{
"tag": "img",
"attrs": {"src": i},
}
for i in uploaded_imgs
],
"access_token": self.access_token,
},
) as resp:
if resp.status != 200:
await utils.answer(
self.strings("error", m).format(
f"Status code: {resp.status}", await resp.text()
)
)
return
try:
data: dict = await resp.json(content_type=None)
except Exception as e:
err_json = await resp.text()
await utils.answer(
m, self.strings("error", m).format(str(e), err_json)
)
return
page_url = data["result"]["url"]
await utils.answer(m, self.strings("result_with_url", m).format(page_url))

View File

@@ -0,0 +1,78 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import io
import requests
from .. import loader # type: ignore
def register(cb):
cb(DeepAIMod())
class DeepAIMod(loader.Module):
strings = {"name": "DeepAI"}
def __init__(self):
self.name = self.strings["name"]
async def client_ready(self, client, db):
self._db = db
async def dai_set_tokencmd(self, m):
self._db.set("deepai", "token", str(m.raw_text.split(" ", 1)[1]))
await m.edit("[DeepAI] Токен установлен")
async def cnsfwcmd(self, m):
""".cnsfw <reply to photo/sticker> - Check on nsfw content by DeepAI"""
reply = await m.get_reply_message()
if not reply:
await m.edit("<b>Reply to media</b>")
return
try:
media = reply.media
except Exception:
await m.edit("<b>Only media</b>")
return
if token := self._db.get("deepai", "token", None):
await m.edit("[DeepAI] Детектим nsfw...")
photo = io.BytesIO()
await m.client.download_media(media, photo)
photo.seek(0)
r = requests.post(
"https://api.deepai.org/api/nsfw-detector",
files={
"image": photo.read(),
},
headers={"api-key": token},
)
try:
await m.edit(
"[DeepAI] Тут Nsfw на "
+ str(round(r.json()["output"]["nsfw_score"] * 100, 1))
+ "%"
)
except Exception:
await m.edit(f"[DeepAI] {str(r.json())}")
else:
await m.edit(
"[DeepAI] Укажите токен для работы с API\n<code>.dai_set_token TOKEN</code>"
)

View File

@@ -0,0 +1,44 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import re
from asyncio import sleep
from .. import loader, utils # type: ignore
@loader.tds
class DelTmMod(loader.Module):
strings = {"name": "Delete Timer"}
@loader.owner
async def deltmcmd(self, m):
"<реплай> <секунды>\nУдалить сообщение в реплае через указанное время"
reply = await m.get_reply_message()
if not reply:
return await m.edit("reply...")
r = re.compile(r"^\d+$")
time = utils.get_args_raw(m)
if r.match(time):
await m.delete()
await sleep(int(time))
await reply.delete()
else:
await m.edit("shit...")
return

View File

@@ -0,0 +1,63 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from .. import loader, utils # type: ignore
@loader.tds
class dmt228Mod(loader.Module):
"""Демотиватор 228 @super_rjaka_demotivator_bot"""
strings = {"name": "Демотиватор 228"}
@loader.owner
async def dmtcmd(self, message):
""".dmt [текст по желанию] <reply to video, photo or gif>"""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
return await message.edit("<b>Reply to media</b>")
try:
media = reply.media
except Exception:
return await message.edit("<b>Only media</b>")
chat = "@super_rjaka_demotivator_bot"
await message.edit("<b>Демотивируем...</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=1016409811)
)
mm = await message.client.send_file(chat, media, caption=args)
response = await response
await mm.delete()
except YouBlockedUserError:
return await message.reply(
"<b>Разблокируй @super_rjaka_demotivator_bot</b>"
)
await message.delete()
await response.delete()
await message.client.send_file(
message.to_id,
response.media,
reply_to=await message.get_reply_message(),
)

View File

@@ -0,0 +1,98 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import io
from .. import loader, utils # type: ignore
def register(cb):
cb(DUsersMod())
class DUsersMod(loader.Module):
"""DUsers"""
strings = {"name": "DUsers"}
def __init__(self):
self.name = self.strings["name"]
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
async def ducmd(self, message):
""".du <n> <m> <s>
Дамп юзеров чата
<n> - Получить только пользователей с открытыми номерами
<m> - Отправить дамп в избранное
<s> - Тихий дамп
"""
if not message.chat:
await message.edit("<b>Это не чат</b>")
return
chat = message.chat
num = False
silent = False
tome = False
if utils.get_args_raw(message):
a = utils.get_args_raw(message)
if "n" in a:
num = True
if "s" in a:
silent = True
if "m" in a:
tome = True
if not silent:
await message.edit("🖤Дампим чат...🖤")
else:
await message.delete()
f = io.BytesIO()
f.name = f"Dump by {chat.id}.csv"
f.write("FNAME;LNAME;USER;ID;NUMBER\n".encode())
me = await message.client.get_me()
for i in await message.client.get_participants(message.to_id):
if i.id == me.id:
continue
if (num) and i.phone or not (num):
f.write(
f"{str(i.first_name)};{str(i.last_name)};{str(i.username)};{str(i.id)};{str(i.phone)}\n".encode()
)
f.seek(0)
if tome:
await message.client.send_file("me", f, caption="Дамп чата " + str(chat.id))
else:
await message.client.send_file(
message.to_id, f, caption=f"Дамп чата {str(chat.id)}"
)
if not silent:
if tome:
if num:
await message.edit("🖤Дамп юзеров чата сохранён в избранных!🖤")
else:
await message.edit(
"🖤Дамп юзеров чата с открытыми номерами сохранён в избранных!🖤"
)
else:
await message.delete()
f.close()

View File

@@ -0,0 +1,183 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import base64
import io
import requests
import telethon
from telethon.tl.types import *
from .. import loader, utils # type: ignore
@loader.tds
class FDQuoteMod(loader.Module):
strings = {
"name": "FDQuote",
"processing": "<b>[FDQ]</b> Processing...",
"processing_api": "<b>[FDQ]</b> </code>API Processing...</code>",
"photo": "Фото{}",
"video": "Видео{}",
"audio": "Аудио{}",
"gif": "GIF{}",
"voice": "Голосовое сообщение{}",
"videonote": "Видеосообщение",
"poll": "Опрос",
"quiz": "Викторина",
"sticker": "{}Стикер",
"file": "Файл {}",
"api_error": "<b>[FDQ]</b> API Error: <code>{}</code>",
"error": "<b>[FDQ]</b> Err...",
"deleted_acc": "Удалённый аккаунт",
"need_reply": "<b>[FDQ]</b> Reply to message...",
}
def __init__(self):
self.name = self.strings["name"]
self.api_url = "https://api.d4n13l3k00.ru/quotes/generate"
self.debug = False
@loader.owner
async def fdqcmd(self, m: Message):
".fdq <реплай на юзера и текст> или <@username и текст> или <реплай и @username> или <реплай> - Создать квотес"
message = await m.get_reply_message()
args = m.text.split(maxsplit=2)
args.pop(0)
catch_reply = reply = viabot = pic = None
if message:
if args:
if args[0].startswith("@"):
user_id = args[0][1:]
text = message.text
else:
user_id = message.from_id or message.fwd_from.channel_id
text = " ".join(args)
else:
user_id = message.from_id or message.fwd_from.channel_id
text = message.text
catch_reply = True
elif len(args) == 2 and args[0].startswith("@"):
user_id = args[0][1:]
text = args[1]
else:
return await utils.answer(m, self.strings["need_reply"])
try:
user = await m.client.get_entity(user_id)
except ValueError:
return await utils.answer(m, self.strings["error"])
await utils.answer(m, self.strings["processing"])
name = (
telethon.utils.get_display_name(user)
if type(user) == Channel
else (
self.strings["deleted_acc"]
if user and user.deleted
else telethon.utils.get_display_name(user)
)
)
id = user.id
avatar = await m.client.download_profile_photo(user, bytes)
reply = await message.get_reply_message()
### / Message / ###
if message.file and "image" in message.file.mime_type:
pic = await message.download_media(bytes)
elif message.video or message.gif:
pic = await message.download_media(bytes, thumb=-1)
if message.via_bot_id:
viabot = str((await m.client.get_entity(message.via_bot_id)).username)
### / Reply / ###
if reply and catch_reply:
r = await m.client.get_entity(reply.from_id or reply.fwd_from.channel_id)
if reply.photo:
replText = self.strings["photo"].format(
f", {reply.raw_text}" if reply.raw_text else ""
)
elif reply.gif:
replText = self.strings["gif"].format(
f", {reply.raw_text}" if reply.raw_text else ""
)
elif reply.video:
if reply.video.attributes[0].round_message:
replText = self.strings["videonote"]
else:
replText = self.strings["video"].format(
f", {reply.raw_text}" if reply.raw_text else ""
)
elif reply.audio:
replText = self.strings["audio"].format(
f", {reply.raw_text}" if reply.raw_text else ""
)
elif reply.voice:
replText = self.strings["voice"].format(
f", {reply.raw_text}" if reply.raw_text else ""
)
elif reply.poll:
replText = (
self.strings["quiz"]
if reply.media.poll.quiz
else self.strings["poll"]
)
elif reply.sticker:
replText = self.strings["sticker"].format(
reply.sticker.attributes[1].alt + " "
)
elif reply.file:
replText = self.strings["file"].format(
f", {reply.raw_text}" if reply.caption else ""
)
elif reply.raw_text:
replText = reply.raw_text or ""
reply = {
"name": telethon.utils.get_display_name(r)
if type(r) == Channel
else (
self.strings["deleted_acc"]
if r and r.deleted
else telethon.utils.get_display_name(r)
),
"text": replText,
}
else:
reply = None
await utils.answer(m, self.strings["processing_api"])
js = {
"avatar": base64.b64encode(avatar).decode() if avatar else None,
"name": name,
"text": text,
"id": id,
"pic": base64.b64encode(pic).decode() if pic else None,
"reply": reply,
"viabot": viabot,
}
if self.debug:
f = io.BytesIO(str(js).encode("utf-8"))
f.name = "request.debug"
await m.respond(file=f)
r = requests.post(self.api_url, json=js)
if r.status_code == 200:
quote = io.BytesIO(r.content)
quote.name = "q.webp"
if message:
await message.reply(file=quote)
else:
await m.respond(file=quote)
await m.delete()
else:
await utils.answer(m, self.strings["api_error"].format(r.json()["err"]))

View File

@@ -0,0 +1,70 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import re
from asyncio import sleep
from .. import loader, utils # type: ignore
@loader.tds
class ChatFuckerMod(loader.Module):
"""Чатоёб"""
strings = {"name": "Чатоёб"}
@loader.owner
async def fccmd(self, message):
""".fc <Количество заёба> <reply to text/text>
Заебать чат (СРЁТ В ЛОГИ)
"""
reply = await message.get_reply_message()
repeat = 0
text = ""
if reply:
if utils.get_args_raw(message):
try:
if reply.text:
text = reply.text
repeat = int(utils.get_args_raw(message))
else:
await message.edit("Текста нет!")
return
except Exception:
await message.edit("<b>Err</b>")
return
else:
await message.edit("А скольо раз надо?")
return
elif utils.get_args_raw(message):
try:
repeat = int(utils.get_args_raw(message).split(" ")[0])
text = re.split(r".[a-z-0-9]{1,} [0-9]{1,} ", message.text)[1]
except Exception:
await message.edit("<b>Err</b>")
return
else:
await message.edit("А как же текст/реплай на текст?")
return
await message.delete()
for _ in range(repeat):
m = await message.client.send_message(message.to_id, text)
await sleep(0.5)
await m.delete()
await sleep(0.1)

View File

@@ -0,0 +1,39 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from requests import get
from .. import loader, utils # type: ignore
@loader.tds
class FullApiMod(loader.Module):
"""Фулл"""
strings = {"name": "FullApi"}
@loader.owner
async def rndfullcmd(self, m):
"получить рандомный фулл :)"
await utils.answer(
m,
'<a href="'
+ get("https://api.d4n13l3k00.ru/shit/random_full").json()["url"]
+ '">Подгончик для братков</a>',
)

View File

@@ -0,0 +1,282 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# require httpx
import json
from typing import List
import httpx
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class OpenAIGPTMod(loader.Module):
"OpenAI GPT"
strings = {
"name": "GPT",
"pref": "<b>[GPT]</b> {}",
"prefcgpt": "<b>[ChatGPT]</b> {}",
"prefom": "<b>[OpenModerator]</b> {}",
"result": "<b>Prompt</b>: {prompt}\n\n<b>Result:</b> {text}\n\n"
"<b>Used tokens:</b> {prompt_tokens}+{completion_tokens}={total_tokens}",
}
def __init__(self):
self.config = loader.ModuleConfig(
*("MODEL", "text-davinci-003", "Model name"),
*(
"COMPLETION_ENDPOINT",
"https://api.openai.com/v1/completions",
"Completions API endpoint",
),
*("MAX_TOKENS", 512, "Maximum tokens"),
*("TEMPERATURE", 0.7, "Temperature"),
*("DEBUG", False, "Debug mode for answers"),
*(
"CGPT_ENDPOINT",
"https://api.openai.com/v1/chat/completions",
"ChatGPT API endpoint",
),
*("CGPT_MODEL", "gpt-3.5-turbo", "ChatGPT model name"),
*("CGPT_TEMPERATURE", 0.7, "ChatGPT temperature"),
*(
"CGPT_SYSTEM_MSG",
"You are Pavel Durov, CEO and owner of Telegram",
"ChatGPT system message",
),
*(
"MODERATION_ENDPOINT",
"https://api.openai.com/v1/moderations",
"OpenAI's moderation endpoint",
),
)
async def client_ready(self, client, db):
self._client = client
self._db = db
self._db_name = "OpenAI_GPT"
self.messages_history_default = [
{
"role": "system",
"content": self.config["CGPT_SYSTEM_MSG"],
}
]
self.messages_history = [] + self.messages_history_default
@loader.owner
async def setgptcmd(self, m: types.Message):
"<token> - set OpenAI access token"
token: str or None = utils.get_args_raw(m)
if not token:
return await utils.answer(m, self.strings("pref", m).format("No token"))
self._db.set(self._db_name, "token", token)
await utils.answer(m, self.strings("pref", m).format("Token set"))
@loader.owner
async def gptcmd(self, m: types.Message):
"<text/reply_to_text> - generate text"
token = self._db.get(self._db_name, "token")
if not token:
return await utils.answer(
m, self.strings("pref", m).format("No token set! Use .setgpt <token>")
)
prompt = utils.get_args_raw(m)
reply = await m.get_reply_message()
if reply:
prompt = prompt or reply.raw_text
if not prompt:
return await utils.answer(m, self.strings("pref", m).format("No text"))
m = await utils.answer(m, self.strings("pref", m).format("Generating..."))
async with httpx.AsyncClient(timeout=300) as client:
response = await client.post(
self.config["COMPLETION_ENDPOINT"],
headers={
"Authorization": f"Bearer {token}",
},
json={
"model": self.config["MODEL"],
"prompt": prompt,
"max_tokens": self.config["MAX_TOKENS"],
"temperature": self.config["TEMPERATURE"],
},
)
j = response.json()
if response.status_code != 200:
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
return await utils.answer(
m,
self.strings("pref", m).format(
f"<b>Error:</b> {response.status_code} {response.reason_phrase}"
),
)
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
text = j["choices"][0]["text"].strip("\n").strip(" ")
if j["choices"][0]["finish_reason"] == "length":
text += "\n<code>TOKEN_LIMIT. Use .config to change them.</code>"
await utils.answer(
m,
self.strings("pref", m).format(
self.strings("result", m).format(
prompt=prompt, text=text, **j["usage"]
)
),
)
@loader.owner
async def cgptcmd(self, m: types.Message):
"<text/reply_to_text> - answer ChatGPT (gpt-3.5-turbo)"
token = self._db.get(self._db_name, "token")
if not token:
return await utils.answer(
m,
self.strings("prefcgpt", m).format("No token set! Use .setgpt <token>"),
)
prompt = utils.get_args_raw(m)
reply = await m.get_reply_message()
if reply:
prompt = prompt or reply.raw_text
if not prompt:
return await utils.answer(m, self.strings("prefcgpt", m).format("No text"))
m = await utils.answer(m, self.strings("prefcgpt", m).format("Generating..."))
async with httpx.AsyncClient(timeout=300) as client:
response = await client.post(
self.config["CGPT_ENDPOINT"],
headers={
"Authorization": f"Bearer {token}",
},
json={
"model": self.config["CGPT_MODEL"],
"messages": self.messages_history
+ [{"role": "user", "content": prompt}],
"temperature": self.config["CGPT_TEMPERATURE"],
},
)
j = response.json()
if response.status_code != 200:
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
return await utils.answer(
m,
self.strings("prefcgpt", m).format(
f"<b>Error:</b> {response.status_code} {response.reason_phrase}"
),
)
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
text = j["choices"][0]["message"]["content"].strip("\n").strip(" ")
self.messages_history.append({"role": "user", "content": prompt})
self.messages_history.append({"role": "assistant", "content": text})
if j["choices"][0]["finish_reason"] == "length":
text += "\n<code>TOKEN_LIMIT. Use .config to change them.</code>"
await utils.answer(
m,
self.strings("prefcgpt", m).format(
self.strings("result", m).format(
prompt=prompt, text=text, **j["usage"]
)
),
)
@loader.owner
async def cgptresetcmd(self, m: types.Message):
"Reset ChatGPT history"
self.messages_history = [] + self.messages_history_default
await utils.answer(m, self.strings("prefcgpt", m).format("History reset"))
@loader.owner
async def omodercmd(self, m: types.Message):
"turn chat text moderation with moderation endpoint (eng only)"
token = self._db.get(self._db_name, "token")
if not token:
return await utils.answer(
m,
self.strings("prefom", m).format("No token set! Use .setgpt <token>"),
)
if not m.chat:
return await utils.answer(
m, self.strings("prefom", m).format("Only chat command")
)
chats: List[int] = self._db.get(self._db_name, "moderation", [])
if m.chat.id not in chats:
chats.append(m.chat.id)
await utils.answer(
m, self.strings("prefom", m).format("Moderation enabled for this chat")
)
else:
chats.remove(m.chat.id)
await utils.answer(
m, self.strings("prefom", m).format("Moderation disabled for this chat")
)
self._db.set(self._db_name, "moderation", chats)
async def watcher(self, m: types.Message):
if not isinstance(m, types.Message):
return
if not m.chat:
return
chats: List[int] = self._db.get(self._db_name, "moderation", [])
if m.chat.id not in chats:
return
token = self._db.get(self._db_name, "token")
async with httpx.AsyncClient(timeout=300) as client:
response = await client.post(
self.config["MODERATION_ENDPOINT"],
headers={
"Authorization": f"Bearer {token}",
},
json={"input": m.raw_text},
)
j = response.json()
if response.status_code != 200:
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
return await utils.answer(
m,
self.strings("prefcgpt", m).format(
f"<b>Error:</b> {response.status_code} {response.reason_phrase}"
),
)
if self.config["DEBUG"]:
return await utils.answer(
m, "<code>{}</code>".format(str(json.dumps(j, indent=1)))
)
if j["results"]["flagged"]:
return await m.delete()

View File

@@ -0,0 +1,244 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: Pillow aiohttp fake-useragent
import hashlib
import io
import re
from datetime import date
import aiohttp
from fake_useragent import UserAgent
from PIL import Image, ImageEnhance, ImageOps
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class ImageEditorMod(loader.Module):
"ImageEditor - Simple tool for working with images"
strings = {
"name": "ImageEditor",
"downloading": "<b>[{}]</b> Downloading...",
"working": "<b>[{}]</b> Working...",
"exporting": "<b>[{}]</b> Exporting...",
"set_value": "<b>[{}]</b> Specify the level...",
"set_size": "<b>[{}]</b> Specify the size...",
"reply": "<b>[{}]</b> reply to image...",
"set_time": "<b>[{}]</b> Specify the time in the format start(ms):end(ms)",
}
@loader.owner
async def resizeicmd(self, m: types.Message):
".resizei <w> <h> - Resize image"
_pref = "Resize"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d+)\s+(\d+)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_size", m).format(_pref))
w, h = [int(i) for i in r.match(args).groups()]
im = await get_image(self, m, _pref)
if not im:
return
out = im.image.resize((w, h))
await go_out(self, m, im, out, _pref)
@loader.owner
async def rmbgicmd(self, m: types.Message):
".rmbgi - Remove background via AI [Powered by Indian's AI]"
_pref = "RemoveBg"
im = await get_image(self, m, _pref)
if not im:
return
b = io.BytesIO()
b.name = "i.png"
im.image.save(b, "PNG")
b.seek(0)
out = None
async with aiohttp.ClientSession(
headers={"User-Agent": UserAgent().chrome}
) as s:
form = aiohttp.FormData()
form.add_field("file", b)
form.add_field("filenameOverride", "true")
form.add_field(
"path",
f"__editor/{date.year}-{date.month}-{date.day}/{hashlib.md5(b.read()).hexdigest()}",
)
b.seek(0)
async with s.post(
"https://api.erase.bg/service/panel/assets/v1.0/upload/direct",
data=form,
) as r:
_url = (await r.json())["url"]
async with s.get(
_url.replace("dummy-cloudname/original", "dummy-cloudname/erase.bg()")
) as r:
i = io.BytesIO(await r.read())
i.name = "ImageEditor.jpeg"
out = Image.open(i)
await go_out(self, m, im, out, _pref, True)
@loader.owner
async def inverticmd(self, m: types.Message):
".inverti - Invert colors"
_pref = "Invert"
im = await get_image(self, m, _pref)
if not im:
return
out = ImageOps.invert(im.image)
await go_out(self, m, im, out, _pref)
@loader.owner
async def bwicmd(self, m: types.Message):
".bwi - BlackWhite"
_pref = "BlackWhite"
im = await get_image(self, m, _pref)
if not im:
return
out = im.image.convert("L")
await go_out(self, m, im, out, _pref)
@loader.owner
async def convicmd(self, m: types.Message):
".convi - Sticker to image | Image to sticker"
_pref = "Converter"
im = await get_image(self, m, _pref)
if not im:
return
im.is_webp = not im.is_webp
await go_out(self, m, im, im.image, _pref)
@loader.owner
async def rotateicmd(self, m: types.Message):
".rotatei <degrees> - Rotate image"
_pref = "Rotate"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d+)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_value", m).format(_pref))
degrees = int(r.match(args).groups()[0])
im = await get_image(self, m, _pref)
if not im:
return
out = im.image.rotate(degrees, expand=True)
await go_out(self, m, im, out, _pref)
@loader.owner
async def contrasticmd(self, m: types.Message):
".contrasti <float> - Change contrast"
_pref = "Contrast"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d*\.?\d*)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_value", m).format(_pref))
level = float(r.match(args).groups()[0])
im = await get_image(self, m, _pref)
if not im:
return
out = ImageEnhance.Contrast(im.image).enhance(level)
await go_out(self, m, im, out, _pref)
@loader.owner
async def sharpnessicmd(self, m: types.Message):
".sharpnessi <float> - Change sharpness"
_pref = "Sharpness"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d*\.?\d*)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_value", m).format(_pref))
level = float(r.match(args).groups()[0])
im = await get_image(self, m, _pref)
if not im:
return
out = ImageEnhance.Sharpness(im.image).enhance(level)
await go_out(self, m, im, out, _pref)
@loader.owner
async def brighticmd(self, m: types.Message):
".brighti <float> - Change bright"
_pref = "Color"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d*\.?\d*)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_value", m).format(_pref))
level = float(r.match(args).groups()[0])
im = await get_image(self, m, _pref)
if not im:
return
out = ImageEnhance.Brightness(im.image).enhance(level)
await go_out(self, m, im, out, _pref)
@loader.owner
async def coloricmd(self, m: types.Message):
".colori <float> - Change color factor"
_pref = "Color"
args = utils.get_args_raw(m)
r = re.compile(r"^(\d*\.?\d*)$")
if not args or not r.match(args):
return await utils.answer(m, self.strings("set_value", m).format(_pref))
level = float(r.match(args).groups()[0])
im = await get_image(self, m, _pref)
if not im:
return
out = ImageEnhance.Color(im.image).enhance(level)
await go_out(self, m, im, out, _pref)
class ImageEditorClass:
image: Image.Image = None
message = None
is_webp: bool = None
pref: str = None
reply = None
async def get_image(self, m, pref: str) -> ImageEditorClass:
r = await m.get_reply_message()
if r and r.file and r.file.mime_type.split("/")[0] in ["image"]:
im = ImageEditorClass()
im.pref = pref
im.reply = r
im.is_webp = r.file.ext == ".webp"
m = await utils.answer(m, self.strings("downloading", m).format(pref))
im.image = Image.open(io.BytesIO(await r.download_media(bytes)))
im.message = await utils.answer(m, self.strings("working", m).format(pref))
return im
await utils.answer(m, self.strings("reply", m).format(pref))
async def go_out(
self, m, im: ImageEditorClass, out: Image.Image, pref, force_document=False
):
m = await utils.answer(m, self.strings("exporting", m).format(pref))
iba = io.BytesIO()
if im.is_webp:
out.thumbnail((512, 512))
out.save(iba, format="WEBP" if im.is_webp else "PNG")
iba.name = "ImageEditor." + ("webp" if im.is_webp else "png")
iba.seek(0)
await utils.answer(
m,
iba,
reply_to=im.reply.id,
supports_streaming=True,
force_document=force_document if not im.is_webp else False,
)

View File

@@ -0,0 +1,157 @@
# Attribution-NonCommercial-NoDerivatives 4.0 International
> *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.*
>
> ### Using Creative Commons Public Licenses
>
> Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
>
> * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
>
> * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org).

View File

@@ -0,0 +1,73 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import requests
from .. import loader, utils # type: ignore
@loader.tds
class MailSearcherMod(loader.Module):
"AntiPublic MYRZ"
strings = {"name": "AntiPublic MYRZ"}
def __init__(self):
self.name = self.strings["name"]
async def client_ready(self, client, db):
self.db = db
async def myrz_keycmd(self, m):
self.db.set("myrz", "key", str(m.raw_text.split(" ", 1)[1]))
await m.edit("[AntiPublic MYRZ] Токен установлен")
@loader.owner
async def msrchcmd(self, m):
"Получить пароли почты/логина"
key = self.db.get("myrz", "key", None)
if not key:
await m.edit(
"<b>Укажите ключ из антипаблика myrz!</b>\n\n<code>.myrz_key [KEY]</code>"
)
return
if args := utils.get_args_raw(m):
await m.edit("Делаю запрос...")
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
}
data = requests.post(
"https://myrz.org/api/email_search.php",
data={"key": key, "email": args},
headers=headers,
).json()
try:
if data["success"] is True:
psswds = "\n".join(
f"<code>{i['line']}</code>" for i in data["results"]
)
psswds += f"\n\nОсталось запросов: {data['awailableQueries']}\nНайдено: {data['resultCount']}\nЗапрос: <code>{args}</code>"
await utils.answer(m, str(psswds))
else:
await m.edit(
f"Ничего не найдено по запросу <code>{args}</code>\nОсталось запросов: {data['awailableQueries']}"
)
except Exception:
await m.edit(str(data))
else:
await m.edit("shit...")

View File

@@ -0,0 +1,121 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import requests
from .. import loader, utils # type: ignore
@loader.tds
class nkapimdMod(loader.Module):
strings = {"name": "NekosLife"}
@loader.owner
async def nkcmd(self, m):
"Отправить фото/гиф\nПо умолчанию отправляется neko\nМожно указать другую категорию(.nkct)"
args = utils.get_args_raw(m)
typ = None
if args:
if args in types_of:
typ = args
else:
typ = "neko"
if typ is None:
return await m.edit("<b>не знаю такого</b>")
await m.edit("<b>Mmm...</b>")
reply = await m.get_reply_message()
await m.client.send_file(
m.to_id,
requests.get(f"https://nekos.life/api/v2/img/{typ}").json()["url"],
reply_to=reply.id if reply else None,
)
await m.delete()
async def nkctcmd(self, m):
await m.edit(
"Доступные категории:\n" + "\n".join(f"<code>{i}</code>" for i in types_of)
)
types_of = [
"femdom",
"tickle",
"classic",
"ngif",
"erofeet",
"meow",
"erok",
"poke",
"les",
"hololewd",
"lewdk",
"keta",
"feetg",
"nsfw_neko_gif",
"eroyuri",
"kiss",
"_8ball",
"kuni",
"tits",
"pussy_jpg",
"cum_jpg",
"pussy",
"lewdkemo",
"lizard",
"slap",
"lewd",
"cum",
"cuddle",
"spank",
"smallboobs",
"goose",
"Random_hentai_gif",
"avatar",
"fox_girl",
"nsfw_avatar",
"hug",
"gecg",
"boobs",
"pat",
"feet",
"smug",
"kemonomimi",
"solog",
"holo",
"wallpaper",
"bj",
"woof",
"yuri",
"trap",
"anal",
"baka",
"blowjob",
"holoero",
"feed",
"neko",
"gasm",
"hentai",
"futanari",
"ero",
"solo",
"waifu",
"pwankg",
"eron",
"erokemo",
]

View File

@@ -0,0 +1,47 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: pornhub-api
from random import choice
from pornhub_api import PornhubApi
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class PhSrchMod(loader.Module):
strings = {"name": "PornHub"}
@loader.owner
async def sphcmd(self, m: types.Message):
"Найти видео на pornhub"
if args := utils.get_args_raw(m):
srch = args
else:
return await m.delete()
api = PornhubApi()
data = api.search.search(srch, ordering="mostviewed")
video = choice(data.videos)
await utils.asnwer(
m,
f'<b>Нашёл кое-что по запросу</b> <code>{srch}</code>: <a href="{video.url}">{video.title}</a>',
)

View File

@@ -0,0 +1,239 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: glQiwiApi pycryptodome
import asyncio
import hashlib
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from glQiwiApi import QiwiWrapper
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class QiwiMod(loader.Module):
"Модуль для работы с Qiwi кошельком"
strings = {
"name": "Qiwi",
"pref": "<b>[Qiwi]</b> ",
"need_arg": "{}need args...",
"phone_setted_successfully": "{}Номер и токен установлены!",
"p2p_setted_successfully": "{}Секретный P2P токен установлен!",
"need_phone_token": "{}Необходимо установить номер токен!",
"need_p2p": "{}Необходимо установить P2P токен!",
"bal": "{}Баланс: {}",
"commission": "{}Итоговая сумма: {}\nКомиссия Qiwi: {}\nСумма к зачислению: {}",
"sent": "{}Средства отправлены!\nID: <code>{}</code>",
"bill_created": "{}Счёт создан!\n{}\nСтатус счёта: <code>{}</code>",
"bill_payed": "Оплачен",
"bill_notpayed": "Не оплачен",
"bill_disabled": "Автопроверка отключена после 5 минут",
"bill_link_exp": "Ссылка истекла по причине оплаты",
}
_db = "QiwiMod"
async def client_ready(self, _, db):
self.db = db
self.me = await _.get_me()
def __pad(self, text: bytes):
return text[:8] if len(text) > 8 else text
def __get_enc(self, key: str) -> str:
c = DES.new(
self.__pad(
hashlib.md5((self.me.phone + str(self.me.id)).encode("utf-8"))
.hexdigest()
.encode("utf-8")
),
DES.MODE_ECB,
)
return unpad(c.decrypt(self.db.get(self._db, key, b"")), 8).decode("utf-8")
def __set_enc(self, key: str, value: str):
c = DES.new(
self.__pad(
hashlib.md5((self.me.phone + str(self.me.id)).encode("utf-8"))
.hexdigest()
.encode("utf-8")
),
DES.MODE_ECB,
)
self.db.set(self._db, key, c.encrypt(pad(value.encode("utf-8"), 8)))
def __need_token(func):
async def wrapper(self, m: types.Message):
if not self.db.get(self._db, "phone") or not self.db.get(self._db, "token"):
return await utils.answer(
m,
self.strings("need_phone_token").format(self.strings("pref")),
)
return await func(self, m)
return wrapper
def __need_p2p(func):
async def wrapper(self, m: types.Message):
return (
await func(self, m)
if self.db.get(self._db, "p2p")
else await utils.answer(
m,
self.strings("need_p2p").format(self.strings("pref")),
)
)
return wrapper
async def qsetp2pcmd(self, m: types.Message):
""".qsetp2p <TOKEN>
Установить секретный p2p ключ"""
if args := utils.get_args(m):
self.__set_enc("p2p", args[0])
return await utils.answer(
m, self.strings("p2p_setted_successfully").format(self.strings("pref"))
)
await utils.answer(m, self.strings("need_arg").format(self.strings("pref")))
async def qsetcmd(self, m: types.Message):
""".qset <phone> <TOKEN>
Установить номер и токен"""
if args := utils.get_args(m):
self.__set_enc("phone", args[0])
self.__set_enc("token", args[1])
return await utils.answer(
m,
self.strings("phone_setted_successfully").format(self.strings("pref")),
)
await utils.answer(m, self.strings("need_arg").format(self.strings("pref")))
@__need_token
async def qbalcmd(self, m: types.Message):
".qbal - Получить баланс"
async with QiwiWrapper(self.__get_enc("token"), self.__get_enc("phone")) as w:
w: QiwiWrapper
bal = await w.get_balance()
await utils.answer(
m,
self.strings("bal").format(
self.strings("pref"), str(bal.amount) + bal.currency.symbol
),
)
@__need_token
async def qswalcmd(self, m: types.Message):
".qswal <phone> <amount> <?comment> - Отправить средства по номеру"
async with QiwiWrapper(self.__get_enc("token"), self.__get_enc("phone")) as w:
w: QiwiWrapper
args = utils.get_args(m)
args_raw = utils.get_args_raw(m)
trans_id = await w.to_wallet(
to_number=args[0],
amount=int(args[1]),
comment=args_raw.split(args[1])[1].strip() if len(args) > 2 else None,
)
await utils.answer(
m,
self.strings("sent").format(
self.strings("pref"), str(trans_id.payment_id)
),
)
@__need_token
async def qscardcmd(self, m: types.Message):
".qscard <card_num[no_spaces]> <amount> - Отправить средства на карту"
async with QiwiWrapper(self.__get_enc("token"), self.__get_enc("phone")) as w:
w: QiwiWrapper
args = utils.get_args(m)
trans_id = await w.to_card(
to_card=args[0],
trans_sum=float(args[1]),
)
await utils.answer(
m,
self.strings("sent").format(
self.strings("pref"), str(trans_id.payment_id)
),
)
@__need_token
async def qcmscmd(self, m: types.Message):
".qcms <card_num/phone> <amount> - Посчитать комиссию"
async with QiwiWrapper(self.__get_enc("token"), self.__get_enc("phone")) as w:
w: QiwiWrapper
args = utils.get_args(m)
commission = await w.calc_commission(args[0], float(args[1]))
await utils.answer(
m,
self.strings("commission").format(
self.strings("pref"),
str(commission.withdraw_sum.amount)
+ commission.withdraw_sum.currency.symbol,
str(commission.qiwi_commission.amount)
+ commission.qiwi_commission.currency.symbol,
str(commission.enrollment_sum.amount)
+ commission.enrollment_sum.currency.symbol,
),
)
@__need_p2p
async def qp2pcmd(self, m: types.Message):
".qp2p <amount> <?comment> - Создать счёт для оплаты"
async with QiwiWrapper(secret_p2p=self.__get_enc("p2p")) as w:
w: QiwiWrapper
args = utils.get_args(m)
args_raw = utils.get_args_raw(m)
bill = await w.create_p2p_bill(
amount=args[0],
comment=args_raw.split(args[0])[1].strip() if len(args) > 1 else None,
)
last_status = None
url = bill.pay_url
n = 0
while True:
if n >= 72:
await utils.answer(
m,
self.strings("bill_created").format(
self.strings("pref"),
self.strings("bill_link_exp"),
self.strings("bill_disabled"),
),
)
break
status = (await w.check_p2p_bill_status(bill_id=bill.id)) == "PAID"
if status != last_status:
last_status = status
await utils.answer(
m,
self.strings("bill_created").format(
self.strings("pref"),
url,
self.strings("bill_payed" if status else "bill_notpayed"),
),
)
if status:
break
n += 1
await asyncio.sleep(5)

View File

@@ -0,0 +1,11 @@
# FTG-Modules
📥 Все мои Friendly-Telegram модули
`✅ Совместимы с Friendly-Telegram, GeekTG Userbot`
[@DekFTGModules](https://t.me/DekFTGModules)
---
[Шаблон багрепорта](/bug_report.md) | [Поддержка [Чат]](https://t.me/dftgmchat)

View File

@@ -0,0 +1,73 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import random
import re
from .. import loader, utils # type: ignore
@loader.tds
class RandomizerMod(loader.Module):
strings = {"name": "Рандомайзер"}
prefix = "<b>[Рандомайзер]</b>\n"
@loader.owner
async def rndintcmd(self, m):
".rndint <int> <int> - рандомное число из заданногоо диапозона"
args = utils.get_args_raw(m)
check = re.compile(r"^(\d+)\s+(\d+)$")
if check.match(args):
fr, to = check.match(args).groups()
if int(fr) < int(to):
rndint = random.randint(int(fr), int(to))
await m.edit(
self.prefix
+ f"<b>Режим:</b> Рандомное число из диапозона\n<b>Диапозон:</b> <code>{fr}-{to}</code>\n<b>Выпало число:</b> <code>{rndint}</code>"
)
else:
await m.edit(f"{self.prefix}Вася, укажи диапозон чисел!")
else:
await m.edit(f"{self.prefix}Вася, укажи диапозон чисел!")
@loader.owner
async def rndelmcmd(self, m):
".rndelm <элементы через запятую> - рандомный элемент из списка"
args = utils.get_args_raw(m)
if not args:
await m.edit(f"{self.prefix}Вася, напиши список элементов через запятую!")
return
lst = [i.strip() for i in args.split(",") if i]
await m.edit(
self.prefix
+ f"<b>Режим:</b> Рандомный элемент из списка\n<b>Список:</b> <code>{', '.join(lst)}</code>\n<b>Выпало:</b> <code>{random.choice(lst)}</code>"
)
@loader.owner
async def rndusercmd(self, m):
".rnduser - выбор рандомного юзера из чата"
if not m.chat:
await m.edit(f"{self.prefix}<b>Это не чат</b>")
return
users = await m.client.get_participants(m.chat)
user = random.choice(users)
await m.edit(
self.prefix
+ f'<b>Режим:</b> Рандомный юзер из чата\n<b>Юзер:</b> <a href="tg://user?id={user.id}">{user.first_name}</a> | <code>{user.id}</code>'
)

View File

@@ -0,0 +1,120 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import contextlib
from random import choice
from telethon import functions
from .. import loader # type: ignore
@loader.tds
class ReactionsMod(loader.Module):
"Telegram reactions"
strings = {"name": __doc__}
async def client_ready(self, client, _):
self.client = client
def reaction(func):
async def wrapper(self, *args):
"<reply>"
message = args[0]
emoji = await func(self)
if reply := await message.get_reply_message():
with contextlib.suppress(Exception):
await self.client(
functions.messages.SendReactionRequest(
reply.peer_id, reply.id, reaction=emoji
)
)
if message.out:
await message.delete()
return wrapper
@reaction
async def randrcmd(self):
return choice("👍👎❤️🔥🎉🤩😱😁😢💩🤮🥰🤯🤔🤬👏")
@reaction
async def lovecmd(self):
return ""
@reaction
async def sadcmd(self):
return "😢"
@reaction
async def nastycmd(self):
return "🤮"
@reaction
async def cutecmd(self):
return "🥰"
@reaction
async def clapcmd(self):
return "👏"
@reaction
async def fuckcmd(self):
return "🤬"
@reaction
async def wtfcmd(self):
return "🤯"
@reaction
async def hmmcmd(self):
return "🤔"
@reaction
async def hooraycmd(self):
return "🎉"
@reaction
async def likecmd(self):
return "👍"
@reaction
async def dislikecmd(self):
return "👎"
@reaction
async def firecmd(self):
return "🔥"
@reaction
async def omgcmd(self):
return "😱"
@reaction
async def wowcmd(self):
return "🤩"
@reaction
async def hehecmd(self):
return "😁"
@reaction
async def shitcmd(self):
return "💩"

View File

@@ -0,0 +1,209 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import datetime
import random
from telethon import events, functions
from telethon.errors.rpcerrorlist import YouBlockedUserError
from .. import loader, utils # type: ignore
def register(cb):
cb(RandomNSFWMod())
class RandomNSFWMod(loader.Module):
"""RndNsfw"""
strings = {"name": "RndNsfw"}
def __init__(self):
self.name = self.strings["name"]
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def crncmd(self, message):
"""
Random pic from @wallhaven_nsfw
"""
await message.edit("<b>_-*Wallhaven_NSFW*-_</b>")
chat = "@wallhaven_nsfw"
result = await message.client(
functions.messages.GetHistoryRequest(
peer=chat,
offset_id=0,
offset_date=datetime.datetime.now(),
add_offset=random.choice(range(1, 101, 2)),
limit=1,
max_id=0,
min_id=0,
hash=0,
)
)
await message.delete()
await message.client.send_file(message.to_id, result.messages[0].media)
async def crdcmd(self, message):
"""
Random post from @dvach18
"""
await message.edit("<b>_-*2ch_18+*-_</b>")
chat = "@dvach18"
result = await message.client(
functions.messages.GetHistoryRequest(
peer=chat,
offset_id=0,
offset_date=datetime.datetime.now(),
add_offset=random.randint(0, 1000),
limit=1,
max_id=0,
min_id=0,
hash=0,
)
)
await message.delete()
await message.client.send_message(message.to_id, result.messages[0])
async def crdbcmd(self, message):
"""
Random post from @ru2ch_ban
"""
await message.edit("<b>_-*2ch_Ban*-_</b>")
chat = "@ru2ch_ban"
result = await message.client(
functions.messages.GetHistoryRequest(
peer=chat,
offset_id=0,
offset_date=datetime.datetime.now(),
add_offset=random.randint(0, 1000),
limit=1,
max_id=0,
min_id=0,
hash=0,
)
)
await message.delete()
await message.client.send_message(message.to_id, result.messages[0])
async def crfncmd(self, message):
"""
Random Furry from channel
"""
links = ["https://t.me/joinchat/AAAAAEKWTxZPnvacazjM2Q"]
await message.edit("<b>_-*Furry*-_</b>")
chat = links[random.randint(0, len(links) - 1)]
result = await message.client(
functions.messages.GetHistoryRequest(
peer=chat,
offset_id=0,
offset_date=datetime.datetime.now(),
add_offset=random.randint(0, 1000),
limit=1,
max_id=0,
min_id=0,
hash=0,
)
)
await message.delete()
await message.client.send_message(message.to_id, result.messages[0])
async def crhcmd(self, message):
"""
Random Hentai from channels
"""
#
links = [
"https://t.me/joinchat/AAAAAEWrsWbhMQppqTMNUw",
"https://t.me/joinchat/AAAAAEkJjU8L9J6TDdkAIw",
"@hentai",
]
await message.edit("<b>_-*Hentai*-_</b>")
chat = links[random.randint(0, len(links) - 1)]
result = await message.client(
functions.messages.GetHistoryRequest(
peer=chat,
offset_id=0,
offset_date=datetime.datetime.now(),
add_offset=random.randint(0, 1000),
limit=1,
max_id=0,
min_id=0,
hash=0,
)
)
await message.delete()
await message.client.send_message(message.to_id, result.messages[0])
async def rh2dcmd(self, message):
"""
Random Hentai2D pic/gif from @murglar_bot
You can type category as argument(mustn't)
"""
chat = "@murglar_bot"
args = utils.get_args_raw(message)
if args:
arg = args
else:
arg = None
await message.edit("<b>_-*Hentai_2D*-_</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=507490514)
)
if arg:
m1 = await message.client.send_message(chat, f"/nudes2d {arg}")
else:
m1 = await message.client.send_message(chat, "/nudes2d")
response = await response
except YouBlockedUserError:
await message.reply("<code>Unblock @murglar_bot</code>")
return
await message.delete()
await m1.delete()
await response.delete()
await message.client.send_message(message.to_id, response.message)
async def rn3dcmd(self, message):
"""
Random Nudes3D from @murglar_bot
"""
chat = "@murglar_bot"
await message.edit("<b>_-*Nudes_3D*-_</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(
events.NewMessage(incoming=True, from_users=507490514)
)
m1 = await message.client.send_message(chat, "/nudes3d")
response = await response
except YouBlockedUserError:
await message.reply("<code>Unblock @murglar_bot</code>")
return
await message.delete()
await m1.delete()
await response.delete()
await message.client.send_message(message.to_id, response.message)

View File

@@ -0,0 +1,72 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from telethon import types
import rsa
import aioboto3
from .. import loader, utils # type: ignore
@loader.tds
class S3Mod(loader.Module):
"""S3 file manager"""
strings = {"name": "S3 file manager", "pref": "<b>[S3]</b> {}"}
async def client_ready(self, client, db):
self._db = db
self._db_name = "S3"
async def set_auth_data(
self, endpoint: str, region: str, username: str, password: str, bucket: str
) -> None:
self._db.set(self._db_name, "endpoint", endpoint)
self._db.set(self._db_name, "region", region)
self._db.set(self._db_name, "username", username)
self._db.set(self._db_name, "password", password)
self._db.set(self._db_name, "bucket", bucket)
async def get_client(self) -> aioboto3.Session.client:
session = aioboto3.Session(
aws_access_key_id=self._db.get(self._db_name, "username"),
aws_secret_access_key=self._db.get(self._db_name, "password"),
region_name=self._db.get(self._db_name, "region"),
)
return session.client(
service_name="s3",
endpoint_url=f"https://{self._db.get(self._db_name, 'endpoint')}",
)
@loader.owner
async def s3upcmd(self, m: types.Message):
reply = await m.get_reply_message()
if not reply or not reply.document:
return await utils.answer(m, self.strings("s3").format("Reply to a document"))
session = await self.generate_session()
client = await self.get_client()
async with client as s3:
await s3.upload_fileobj(
await bot.download_file_by_id(video.file_id),
os.getenv("S3_BUCKET_NAME"),
video_s3_path,
)
# @loader.owner
# async def s3authcmd(self, m: types.Message):
# pass

View File

@@ -0,0 +1,65 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import io
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class SaverMod(loader.Module):
strings = {"name": "Saver"}
async def client_ready(self, client, db):
self.db = db
@loader.owner
async def бляcmd(self, m: types.Message):
".бля <reply> - скачать самоуничтожающееся фото"
reply = await m.get_reply_message()
if not reply or not reply.media or not reply.media.ttl_seconds:
return await m.edit("бля")
await m.delete()
new = io.BytesIO(await reply.download_media(bytes))
new.name = reply.file.name
await m.client.send_file("me", new)
@loader.owner
async def swбляcmd(self, m: types.Message):
"Переключить режим автозагрузки фото в лс"
new_val = not self.db.get("Saver", "state", False)
self.db.set("Saver", "state", new_val)
await utils.answer(m, f"<b>[Saver]</b> <pre>{new_val}</pre>")
async def watcher(self, m: types.Message):
if (
m
and m.media
and m.media.ttl_seconds
and self.db.get("Saver", "state", False)
):
new = io.BytesIO(await m.download_media(bytes))
new.name = m.file.name
await m.client.send_file(
"me",
new,
caption=f"<b>[Saver] Фото от</b> {f'@{m.sender.username}' if m.sender.username else m.sender.first_name} | <pre>{m.sender.id}</pre>\n"
f"Время жизни: <code>{m.media.ttl_seconds}sec</code>",
)

View File

@@ -0,0 +1,52 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from .. import loader, utils # type: ignore
def register(cb):
cb(SearcherMod())
class SearcherMod(loader.Module):
strings = {"name": "Searcher"}
def __init__(self):
self.name = self.strings["name"]
async def srchcmd(self, m):
""".srch <канал/чат> <запрос>
Найти пост в канале/чате сообщение и переслать
"""
args = utils.get_args_raw(m)
if not args:
return await m.edit("[Search] Укажите аргументы!")
if len(args.split(" ")) == 1:
return await m.edit("[Search] Укажите запрос!")
ch = args.split(" ")[0]
req = args.split(" ", 1)[1]
try:
ms = await m.client.get_messages(ch, search=req, limit=100)
except Exception as e:
return await m.edit("[Searcher] " + str(e.args))
if ms.total == 0:
return await m.edit("[Searcher] Данных по запросу нет")
for i in ms:
await i.forward_to(m.to_id)
await m.delete()

View File

@@ -0,0 +1,49 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import re
from telethon.errors import ChannelInvalidError
from .. import loader, utils # type: ignore
@loader.tds
class SenderMod(loader.Module):
strings = {"name": "Sender"}
@loader.owner
async def sndcmd(self, m):
""".snd <канал/чат/id> <reply>
Отпрпвить сообшение в чат/канал(без авторства)
"""
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not args:
return await m.edit("[Sender] Укажите канал/чат")
try:
this = await m.client.get_input_entity(
int(args) if re.match(r"-{0,1}\d+", args) else args
)
except ChannelInvalidError:
return await m.edit("[Sender] Такого канала/чата не существует!")
except Exception as e:
return await m.edit("[Sender] Неизвестная мне ошибка:\n" + " ".join(e.args))
await m.client.send_message(this, reply)
await m.edit("[Sender] Сообщение отправлено!")

View File

@@ -0,0 +1,91 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: ShazamAPI
import io
from ShazamAPI import Shazam
from .. import loader, utils # type: ignore
@loader.tds
class ShazamMod(loader.Module):
"""Shazam API"""
strings = {"name": "Shazam API"}
tag = "<b>[Shazam]</b> "
@loader.owner
async def shazamcmd(self, m):
""".shazam <reply to audio> - распознать трек"""
s = await get_audio_shazam(m)
if not s:
return
try:
shazam = Shazam(s.track.read())
recog = shazam.recognizeSong()
track = next(recog)[1]["track"]
await m.client.send_file(
m.to_id,
file=track["images"]["background"],
caption=self.tag + "Распознанный трек: " + track["share"]["subject"],
reply_to=s.reply.id,
)
await m.delete()
except:
await m.edit(f"{self.tag}Не удалось распознать...")
async def shazamtextcmd(self, m):
""".shazamtext <reply to audio> - узнать текст трека"""
s = await get_audio_shazam(m)
if not s:
return
try:
shazam = Shazam(s.track.read())
recog = shazam.recognizeSong()
track = next(recog)[1]["track"]
text = track["sections"][1]["text"]
await utils.answer(
m,
"\n".join(
self.tag + f"Текст трека {track['share']['subject']}\n\n" + text
),
)
except Exception:
await m.edit(f"{self.tag}Не удалось распознать... | Текста нет...")
async def get_audio_shazam(m):
class rct:
track = io.BytesIO()
reply = None
reply = await m.get_reply_message()
if reply and reply.file and reply.file.mime_type.split("/")[0] == "audio":
ae = rct()
await utils.answer(m, "<b>[Shazam]</b> Скачиваю...")
ae.track = io.BytesIO(await reply.download_media(bytes))
ae.reply = reply
await m.edit("<b>[Shazam]</b> Распознаю...")
return ae
else:
await utils.answer(m, "<b>[Shazam]</b> reply to audio...")
return None

View File

@@ -0,0 +1,40 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import os
from .. import loader # type: ignore
@loader.tds
class TesseractMod(loader.Module):
strings = {"name": "Tesseract"}
@loader.owner
async def ocrcmd(self, m):
"Распознать текст с картинки"
reply = await m.get_reply_message()
if not reply:
return await m.edit("[OCR] Реплай на пикчу")
await m.edit("[OCR] Распознаём")
file = await reply.download_media()
rec = os.popen(f"tesseract -l rus+eng {file} stdout").read()
await m.edit(
"[OCR]\n" + (("<code>" + rec + "</code>") if rec != "" else "НЕ_РАСПОЗНАНО")
)
os.remove(file)

View File

@@ -0,0 +1,48 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import random
from .. import loader, utils # type: ignore
@loader.tds
class TryMod(loader.Module):
"""Try"""
strings = {"name": "Try"}
@loader.owner
async def trycmd(self, message):
""".try действие"""
do = utils.get_args_raw(message)
rnd = random.choice(
[
"Удачно",
"Удачно",
"Неудачно",
"Неудачно",
"Удачно",
"Неудачно",
"Удачно",
"Неудачно",
"Удачно",
"Неудачно",
]
)
await message.edit(f"<b>{do}</b>\n\n<code>{rnd}</code>")

View File

@@ -0,0 +1,298 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import random as rnd
import re
import string
import requests
from moviepy.editor import *
from telethon import types
from .. import loader, utils # type: ignore
# meta developer: @D4n13l3k00
# requires: moviepy requests
@loader.tds
class VideoEditorMod(loader.Module):
"Module for working with video"
strings = {
"name": "VideoEditor",
"downloading": "<b>[{}]</b> Downloading...",
"working": "<b>[{}]</b> Working...",
"exporting": "<b>[{}]</b> Exporting...",
"set_value": "<b>[{}]</b> Specify the level from {} to {}...",
"reply": "<b>[{}]</b> reply to video/gif...",
"set_time": "<b>[{}]</b> Specify the time in the format start(ms):end(ms)",
"set_link": "<b>[{}]</b> Enter link...",
}
@loader.owner
async def xflipvcmd(self, m: types.Message):
""".xflipv <reply_to_video> - Flip video by X"""
vid = await get_video(self, m, "XFlip")
if not vid:
return
out = vid.video.fx(vfx.mirror_x)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def yflipvcmd(self, m: types.Message):
""".yflipv <reply_to_video> - Flip video by Y"""
vid = await get_video(self, m, "YFlip")
if not vid:
return
out = vid.video.fx(vfx.mirror_y)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def bwvcmd(self, m: types.Message):
""".bwv <reply_to_video> - BlackWhite"""
vid = await get_video(self, m, "BlackWhite")
if not vid:
return
out = vid.video.fx(vfx.blackwhite)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def revvcmd(self, m: types.Message):
""".revv <reply_to_video> - Reverse video"""
vid = await get_video(self, m, "Reverse")
if not vid:
return
out = vid.video.fx(vfx.time_mirror)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def paintvcmd(self, m: types.Message):
""".paintv <reply_to_video> - Paint effect"""
vid = await get_video(self, m, "Paint")
if not vid:
return
out = vid.video.fx(vfx.painting)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def invertvcmd(self, m: types.Message):
""".invertv <reply_to_video> - Invert colors"""
vid = await get_video(self, m, "Invert")
if not vid:
return
out = vid.video.fx(vfx.invert_colors)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def rmsvcmd(self, m: types.Message):
""".rmsv <reply_to_video> - Remove sound (to gif without compression)"""
vid = await get_video(self, m, "NoAudio")
if not vid:
return
out = vid.video.without_audio()
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def cutvcmd(self, m: types.Message):
""".cutv <int [Default 30]> <reply_to_video> - Cut video"""
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("set_time", m).format("Cut"))
r = re.compile(r"^(?P<start>\d+){0,1}:(?P<end>-?\d+){0,1}$")
ee = r.match(args)
if not ee:
return await utils.answer(m, self.strings("set_time", m).format("Cut"))
start = int(ee.group("start")) if ee.group("start") else 0
end = int(ee.group("end")) if ee.group("end") else None
vid = await get_video(self, m, "Cut")
if not vid:
return
out = vid.video.subclip(start, end)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def audvcmd(self, m: types.Message):
""".audv <link> <reply_to_video> - Add audio to video"""
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("set_link", m).format("Audio"))
r = re.compile(
r"((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
)
ee = r.match(args)
if not ee:
return await utils.answer(m, self.strings("set_link", m).format("Audio"))
vid = await get_video(self, m, "Audio")
if not vid:
return
a = requests.get(args)
nm = "".join(rnd.sample(string.ascii_letters, 24)) + ".mp3"
if a.status_code == 200:
open(nm, "wb").write(a.content)
else:
return
out = vid.video
out.audio = CompositeAudioClip([AudioFileClip(nm)])
await go_out(self, vid.message, vid, out, vid.pref)
try:
os.remove(nm)
except Exception:
pass
@loader.owner
async def fpsvcmd(self, m: types.Message):
""".fpsv <int [Default 30]> <reply_to_video> - Change fps"""
args = utils.get_args_raw(m)
if not args:
fps = 30
elif re.match(r"^\d+$", args) and (0 < int(args) < 241):
fps = int(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("FPS", 1, 240)
)
vid = await get_video(self, m, "FPS")
if not vid:
return
out = vid.video.set_fps(fps)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def marginvcmd(self, m: types.Message):
""".marginv <int [Default 5]> <reply_to_video> - Add marging"""
args = utils.get_args_raw(m)
if not args:
margin = 5
elif re.match(r"^\d+$", args) and (0 < int(args) < 101):
margin = int(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Scale", 1, 100)
)
vid = await get_video(self, m, "Margin")
if not vid:
return
out = vid.video.fx(vfx.margin, margin)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def speedvcmd(self, m: types.Message):
""".speedv <float [Default 1.5]> <reply_to_video> - Speed"""
args = utils.get_args_raw(m)
if not args:
speed = 1.5
elif re.match(r"^\d+(\.\d+)?$", args) and (0.009 < float(args) < 10.1):
speed = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Speed", 0.01, 10.0)
)
vid = await get_video(self, m, "Speed")
if not vid:
return
out = vid.video.fx(vfx.speedx, speed)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def contrastvcmd(self, m: types.Message):
""".contrastv <float [Default 1.5]> <reply_to_video> - Contrast"""
args = utils.get_args_raw(m)
if not args:
contrast = 1.5
elif re.match(r"^\d+(\.\d+)?$", args) and (0.009 < float(args) < 100.1):
contrast = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Contrast", 0.01, 100.0)
)
vid = await get_video(self, m, "Contrast")
if not vid:
return
out = vid.video.fx(vfx.lum_contrast, contrast=contrast)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def lumvcmd(self, m: types.Message):
""".lumv <float [Default 25]> <reply_to_video> - Lum"""
args = utils.get_args_raw(m)
if not args:
lum = 25
elif re.match(r"^\d+(\.\d+)?$", args) and (0.009 < float(args) < 100.1):
lum = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Lum", 0.01, 100.0)
)
vid = await get_video(self, m, "Lum")
if not vid:
return
out = vid.video.fx(vfx.lum_contrast, lum=lum)
await go_out(self, vid.message, vid, out, vid.pref)
@loader.owner
async def scalevcmd(self, m: types.Message):
""".scalev <float [Default 0.75]> <reply_to_video> - Scale("Resize") video"""
args = utils.get_args_raw(m)
if not args:
scale = 0.75
elif re.match(r"^\d+(\.\d+)?$", args) and (0.009 < float(args) < 100.1):
scale = float(args)
else:
return await utils.answer(
m, self.strings("set_value", m).format("Scale", 0.01, 100.0)
)
vid = await get_video(self, m, "Scale")
if not vid:
return
out = vid.video.resize(scale)
await go_out(self, vid.message, vid, out, vid.pref)
class VideoEditorClass:
video: VideoFileClip = None
message = None
pref: str = None
reply = None
async def get_video(self, m, pref: str):
r = await m.get_reply_message()
if r and r.file and r.file.mime_type.split("/")[0] in ["video"]:
vid = VideoEditorClass()
vid.pref = pref
vid.reply = r
vid.message = await utils.answer(m, self.strings("downloading", m).format(pref))
vid.video = VideoFileClip(await r.download_media())
return vid
await utils.answer(m, self.strings("reply", m).format(pref))
async def go_out(self, m, vid: VideoEditorClass, out: VideoFileClip, pref):
m = await utils.answer(m, self.strings("exporting", m).format(pref))
filename = "".join(rnd.sample(string.ascii_letters, 24)) + ".mp4"
out.write_videofile(filename)
await utils.answer(
m, open(filename, "rb"), reply_to=vid.reply.id, supports_streaming=True
)
with contextlib.suppress(Exception):
os.remove(filename)
with contextlib.suppress(Exception):
os.remove(vid.video.filename)

View File

@@ -0,0 +1,71 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import os
import random
import string
from .. import loader, utils # type: ignore
@loader.tds
class VSHAKALMod(loader.Module):
strings = {"name": "Video Shakal"}
@loader.owner
async def vshcmd(self, m):
".vsh <реплай на видео> <уровень от 1 до 6 (по умолчанию 3)>\n" "Сшакалить видео"
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, "reply...")
if reply.file.mime_type.split("/")[0] != "video":
return await utils.answer(m, "shit...")
args = utils.get_args_raw(m)
lvls = {
"1": "1M",
"2": "0.5M",
"3": "0.1M",
"4": "0.05M",
"5": "0.01M",
}
if args:
if args in lvls:
lvl = lvls[args]
else:
return await utils.answer(m, "не знаю такого")
else:
lvl = lvls["3"]
m = await utils.answer(m, "[Шакал] Качаю...")
vid = await reply.download_media(
"".join(random.choice(string.ascii_letters) for _ in range(25)) + ".mp4"
)
out = "".join(random.choice(string.ascii_letters) for _ in range(25)) + ".mp4"
m = await utils.answer(m, "[Шакал] Шакалю...")
os.system(
f'ffmpeg -y -i "{vid}" '
f"-b:v {lvl} -maxrate:v {lvl} "
f'-b:a {lvl} -maxrate:a {lvl} "{out}"'
)
m = await utils.answer(m, "[Шакал] Отправляю...")
await utils.answer(m, out)
os.remove(vid)
os.remove(out)

View File

@@ -0,0 +1,58 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
from io import BytesIO
# requires: pydub speechRecognition
import speech_recognition as srec
from pydub import AudioSegment as auds
from .. import loader, utils # type: ignore
@loader.tds
class VoiceRecognitionMod(loader.Module):
"Распознавание речи через Google Recognition API"
strings = {"name": "VoiceRecognition", "pref": "<b>[VRC]</b> "}
@loader.owner
async def recvcmd(self, m):
".recv <reply to voice/audio> - распознать речь"
reply = await m.get_reply_message()
if reply and reply.file.mime_type.split("/")[0] == "audio":
m = await utils.answer(m, self.strings["pref"] + "Downloading...")
source = BytesIO(await reply.download_media(bytes))
source.name = reply.file.name
out = BytesIO()
out.name = "recog.wav"
m = await utils.answer(m, self.strings["pref"] + "Converting...")
auds.from_file(source).export(out, "wav")
out.seek(0)
m = await utils.answer(m, self.strings["pref"] + "Processing...")
recog = srec.Recognizer()
sample_audio = srec.AudioFile(out)
with sample_audio as audio_file:
audio_content = recog.record(audio_file)
await utils.answer(
m,
self.strings["pref"]
+ recog.recognize_google(audio_content, language="ru-RU"),
)
else:
await utils.answer(m, self.strings["pref"] + "reply to audio/voice...")

View File

@@ -0,0 +1,47 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import aiohttp
from .. import loader, utils # type: ignore
@loader.tds
class WttrInMod(loader.Module):
"""WttrIn"""
strings = {"name": __doc__}
@loader.owner
async def wthrcmd(self, m):
""".wthr <Город если надо>
Получить текущую погоду
"""
rr = utils.get_args_raw(m)
await utils.answer(
m,
"<code>{}</code>".format(
await (
await aiohttp.ClientSession().get(
f"https://wttr.in/{rr if rr is not None else ''}?0Tq&lang=ru"
)
).text()
),
)

View File

@@ -0,0 +1,167 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
# requires: yt-dlp
import os
from telethon.tl.types import DocumentAttributeAudio
from yt_dlp import YoutubeDL
from yt_dlp.utils import (
ContentTooShortError,
DownloadError,
ExtractorError,
GeoRestrictedError,
MaxDownloadsReached,
PostProcessingError,
UnavailableVideoError,
XAttrMetadataError,
)
from .. import loader, utils # type: ignore
@loader.tds
class YtDlMod(loader.Module):
"""Youtube-Dl Module"""
strings = {
"name": "Youtube-Dl",
"preparing": "<b>[YouTube-Dl]</b> Preparing...",
"downloading": "<b>[YouTube-Dl]</b> Downloading...",
"working": "<b>[YouTube-Dl]</b> Working...",
"exporting": "<b>[YouTube-Dl]</b> Exporting...",
"reply": "<b>[YouTube-Dl]</b> No link!",
"noargs": "<b>[YouTube-Dl]</b> No args!",
"content_too_short": "<b>[YouTube-Dl]</b> Downloading content too short!",
"geoban": "<b>[YouTube-Dl]</b> The video is not available "
"for your geographical location due to geographical "
"restrictions set by the website!",
"maxdlserr": '<b>[YouTube-Dl]</b> The download limit is as follows: " oh ahah"',
"pperr": "<b>[YouTube-Dl]</b> Error in post-processing!",
"noformat": "<b>[YouTube-Dl]</b> Media is not available in "
"the requested format",
"xameerr": "<b>[YouTube-Dl]</b> {0.code}: {0.msg}\n{0.reason}",
"exporterr": "<b>[YouTube-Dl]</b> Error when exporting video",
"err": "<b>[YouTube-Dl]</b> {}",
"err2": "<b>[YouTube-Dl]</b> {}: {}",
}
async def ripvcmd(self, m):
""".ripv <link / reply_to_link> - download video"""
await self.riper(m, "video")
async def ripacmd(self, m):
""".ripa <link / reply_to_link> - download audio"""
await self.riper(m, "audio")
async def riper(self, m, type):
reply = await m.get_reply_message()
args = utils.get_args_raw(m)
url = args or reply.raw_text
if not url:
return await utils.answer(m, self.strings("noargs", m))
m = await utils.answer(m, self.strings("preparing", m))
if type == "audio":
opts = {
"format": "bestaudio",
"addmetadata": True,
"key": "FFmpegMetadata",
"writethumbnail": True,
"prefer_ffmpeg": True,
"geo_bypass": True,
"nocheckcertificate": True,
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "320",
}
],
"outtmpl": "%(id)s.mp3",
"quiet": True,
"logtostderr": False,
}
video = False
song = True
elif type == "video":
opts = {
"format": "best",
"addmetadata": True,
"key": "FFmpegMetadata",
"prefer_ffmpeg": True,
"geo_bypass": True,
"nocheckcertificate": True,
"postprocessors": [
{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}
],
"outtmpl": "%(id)s.mp4",
"logtostderr": False,
"quiet": True,
}
song = False
video = True
try:
await utils.answer(m, self.strings("downloading", m))
with YoutubeDL(opts) as rip:
rip_data = rip.extract_info(url)
except DownloadError as DE:
return await utils.answer(m, self.strings("err", m).format(str(DE)))
except ContentTooShortError:
return await utils.answer(m, self.strings("content_too_short", m))
except GeoRestrictedError:
return await utils.answer(m, self.strings("geoban", m))
except MaxDownloadsReached:
return await utils.answer(m, self.strings("maxdlserr", m))
except PostProcessingError:
return await utils.answer(m, self.strings("pperr", m))
except UnavailableVideoError:
return await utils.answer(m, self.strings("noformat", m))
except XAttrMetadataError as XAME:
return await utils.answer(m, self.strings("xameerr", m).format(XAME))
except ExtractorError:
return await utils.answer(m, self.strings("exporterr", m))
except Exception as e:
return await utils.answer(
m, self.strings("err2", m).format(str(type(e)), str(e))
)
if song:
u = rip_data["uploader"] if "uploader" in rip_data else "Northing"
await utils.answer(
m,
open(f"{rip_data['id']}.mp3.mp3", "rb"),
supports_streaming=True,
reply_to=reply.id if reply else None,
attributes=[
DocumentAttributeAudio(
duration=int(rip_data["duration"]),
title=str(rip_data["title"]),
performer=u,
)
],
)
os.remove(f"{rip_data['id']}.mp3")
elif video:
await utils.answer(
m,
open(f"{rip_data['id']}.mp4", "rb"),
reply_to=reply.id if reply else None,
supports_streaming=True,
caption=rip_data["title"],
)
os.remove(f"{rip_data['id']}.mp4")

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