mirror of
https://github.com/MuRuLOSE/limoka.git
synced 2026-06-16 14:34:17 +02:00
Compare commits
2 Commits
main
...
update-sub
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40cbc93717 | ||
|
|
9962abc74b |
@@ -1,125 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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)
|
||||
@@ -1,253 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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")
|
||||
@@ -1,95 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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
|
||||
)
|
||||
@@ -1,661 +0,0 @@
|
||||
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/>.
|
||||
@@ -1,139 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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)
|
||||
@@ -1,54 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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))
|
||||
@@ -1,135 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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>")
|
||||
@@ -1,80 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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)
|
||||
@@ -1,284 +0,0 @@
|
||||
# ---------------------------------------------------------------------------------
|
||||
# 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())
|
||||
@@ -1,8 +0,0 @@
|
||||
Autotime
|
||||
Counter
|
||||
PMStat
|
||||
ChannelImitator
|
||||
StickerStealer
|
||||
Timer
|
||||
MessageEraser
|
||||
Tracker
|
||||
@@ -1,454 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,125 +0,0 @@
|
||||
# -*- 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"])
|
||||
@@ -1,42 +0,0 @@
|
||||
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, он вам поможет")
|
||||
@@ -1,95 +0,0 @@
|
||||
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]
|
||||
))
|
||||
@@ -1,131 +0,0 @@
|
||||
# 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/)"
|
||||
})
|
||||
@@ -1,143 +0,0 @@
|
||||
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)}
|
||||
@@ -1,154 +0,0 @@
|
||||
# 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.'
|
||||
})
|
||||
@@ -1,298 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,147 +0,0 @@
|
||||
# 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)
|
||||
@@ -1,66 +0,0 @@
|
||||
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)
|
||||
@@ -1,81 +0,0 @@
|
||||
# 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)
|
||||
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
# 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 !!"
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
# 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("Ты гей")
|
||||
@@ -1,245 +0,0 @@
|
||||
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]))
|
||||
@@ -1,94 +0,0 @@
|
||||
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()
|
||||
@@ -1,3 +0,0 @@
|
||||

|
||||
# amoremods
|
||||
My mods for userbot
|
||||
@@ -1,53 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta pic: https://te.legra.ph/file/868a280910e7f61f6ab0e.png
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Abstract.jpg
|
||||
|
||||
|
||||
from .. import utils, loader
|
||||
|
||||
chat = "@aeabstractbot"
|
||||
|
||||
|
||||
class AbstractMod(loader.Module):
|
||||
"""Write a beautiful summary on a notebook"""
|
||||
|
||||
strings = {
|
||||
"name": "Abstract",
|
||||
"processing": (
|
||||
"<emoji document_id='6318766236746384900'>🕔</emoji> <b>Processing...</b>"
|
||||
),
|
||||
}
|
||||
|
||||
@loader.owner
|
||||
@loader.command(ru_doc="<текст> - Создать конспект")
|
||||
async def konspcmd(self, message):
|
||||
"""<text> - Create summary"""
|
||||
text = utils.get_args_raw(message)
|
||||
message = await utils.answer(message, self.strings("processing"))
|
||||
async with self._client.conversation(chat) as conv:
|
||||
msgs = []
|
||||
msgs += [await conv.send_message("/start")]
|
||||
msgs += [await conv.get_response()]
|
||||
msgs += [await conv.send_message(text)]
|
||||
m = await conv.get_response()
|
||||
|
||||
await self._client.send_file(
|
||||
message.peer_id,
|
||||
m.media,
|
||||
reply_to=message.reply_to_msg_id,
|
||||
)
|
||||
|
||||
for msg in msgs + [m]:
|
||||
await msg.delete()
|
||||
|
||||
if message.out:
|
||||
await message.delete()
|
||||
|
||||
await self.client.delete_dialog(chat)
|
||||
@@ -1,33 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Activity.jpg
|
||||
# requires: deep_translator
|
||||
|
||||
import requests
|
||||
import deep_translator
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
def generate_activity():
|
||||
return requests.get("http://api.farkhodovme.tk/activity/en").json()['activity']
|
||||
|
||||
|
||||
class Activity(loader.Module):
|
||||
"""Generate activity if you're bored"""
|
||||
|
||||
strings = {"name": "Activity", "activity": "⛩ <b>Activity:</b> <code>{}</code>", "lang": "en"}
|
||||
strings_ru = {"activity": "⛩ <b>Занятие:</b> <code>{}</code>", "lang": "ru"}
|
||||
strings_uz = {"activity": "⛩ <b>Harakat:</b> <code>{}</code>", "lang": "uz"}
|
||||
|
||||
@loader.command(ru_doc="Сгенерировать занятие", uz_doc="Harakat yaratish")
|
||||
async def activity(self, message):
|
||||
"""Generate activity"""
|
||||
res = (deep_translator.GoogleTranslator(source="auto", target=self.strings["lang"]).translate(generate_activity()) if self.strings["lang"] != "en" else generate_activity())
|
||||
txt = self.strings['activity'].format(res)
|
||||
await utils.answer(message, txt)
|
||||
@@ -1,287 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/Aeconv.jpg?raw=true
|
||||
# meta pic: https://cdn-icons-png.flaticon.com/512/5670/5670084.png
|
||||
|
||||
import re
|
||||
import logging
|
||||
|
||||
from bs4 import BeautifulSoup as bs
|
||||
from requests import get
|
||||
from asyncio import sleep
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from hikkatl.tl.types import Message
|
||||
from hikkatl.errors.common import AlreadyInConversationError
|
||||
|
||||
from .. import utils, loader
|
||||
from ..inline.types import InlineCall
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@loader.tds
|
||||
class Aeconv(loader.Module):
|
||||
"""Easy and fast valute converter"""
|
||||
|
||||
bot = "@exchange_rates_vsk_bot"
|
||||
strings = {
|
||||
"name": "Aeconv",
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Converting...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Where are the arguments?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Unsupported currency!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Converted <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Wait until the bot responds!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Wrong currency</b>",
|
||||
"choose_currency": "📉 <b> Choose currency</b>",
|
||||
"processing": "🕔 <b>Processing...</b>",
|
||||
"done": "✅ <b>Done!</b>",
|
||||
"already_in_conv": "⚠️ <b>Already in conversation!</b>",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Конвертирую...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Где аргументы?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Валюта не поддерживается!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Сконвертирован <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Подожди пока бот ответит!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Неправильная валюта</b>",
|
||||
"choose_currency": "📉 <b> Выберите валюту</b>",
|
||||
"processing": "🕔 Обрабатываю...",
|
||||
"done": "<code>[Aeconv]</code> ✅ <b> Готово!</b>",
|
||||
"already_in_conv": "⚠️ <b>Жди пока закончится процесс!</b>",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Valyuta konvertatsiyasi...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Argumetlar qayerda?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Valyuta qo'llab-quvvatlanmaydi!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Konvertatsiya qilindi <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Bot javob berishini kuting!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Noto'g'ri valyuta</b>",
|
||||
"choose_currency": "📉 <b> Valyutani tanlang</b>",
|
||||
"processing": "🕔 Qayta ishlayapman...",
|
||||
"done": "<code>[Aeconv]</code> ✅ <b>Tayyor!</b>",
|
||||
"already_in_conv": "⚠️ <b>Protsess tugaguncha kuting!</b>",
|
||||
}
|
||||
|
||||
strings_de = { # i'm really sorry for translations, i'm not good at it
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Konvertiere...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Wo sind die Argumente?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Nicht unterstützte Währung!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Konvertiert <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Warten Sie, bis der Bot antwortet!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Falsche Währung</b>",
|
||||
"choose_currency": "📉 <b> Währung auswählen</b>",
|
||||
"processing": "🕔 Verarbeitung...",
|
||||
"done": "<code>[Aeconv]</code> ✅ <b>Fertig!</b>",
|
||||
"already_in_conv": "⚠️ <b>Warten Sie, bis der Prozess beendet ist!</b>",
|
||||
|
||||
}
|
||||
|
||||
strings_tr = { # i'm really sorry for translations, i'm not good at it
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Dönüştürülüyor...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Argümanlar nerede?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Desteklenmeyen para birimi!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Dönüştürüldü <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Bot cevap verene kadar bekleyin!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Yanlış para birimi</b>",
|
||||
"choose_currency": "📉 <b> Para birimini seçin</b>",
|
||||
"processing": "🕔 İşleniyor...",
|
||||
"done": "<code>[Aeconv]</code> ✅ <b>Tamam!</b>",
|
||||
"already_in_conv": "⚠️ <b>İşlem bitene kadar bekleyin!</b>",
|
||||
}
|
||||
|
||||
strings_kk = { # i'm really sorry for translations, i'm not good at it
|
||||
"wait": "<emoji document_id=5346192260029489215>💵</emoji> <b>Валюта айырбасталуда...</b>",
|
||||
"no_args": "<emoji document_id=5343820329980535275>🖕</emoji> <b>Аргументтер қайда?</b>",
|
||||
"unsupported": "<emoji document_id=5307761055873638139>🚫</emoji> <b>Валюта қолдау көрсетілмейді!</b>",
|
||||
"converted": "<emoji document_id=6037400506823871682>💸</emoji> <b>Айырбасталды <code>{}</code></b>\n\n",
|
||||
"already": "<emoji document_id=5348177037431414677>⚠️</emoji> <b>Бот жауап бергенге дейін күтіңіз!</b>",
|
||||
"wrong_currency": "<emoji document_id=5345937796102104039>🤷♀️</emoji><b> Дұрыс валюта емес</b>",
|
||||
"choose_currency": "📉 <b> Валютаны таңдаңыз</b>",
|
||||
"processing": "🕔 Қайта өңдеу...",
|
||||
"done": "<code>[Aeconv]</code> ✅ <b>Тайық!</b>",
|
||||
"already_in_conv": "⚠️ <b>Процесс аяқталғанда дейін күтіңіз!</b>",
|
||||
}
|
||||
|
||||
custom_emojis = {
|
||||
"🇬🇧": "<emoji document_id=6323589145717376403>🇬🇧</emoji>",
|
||||
"🇺🇿": "<emoji document_id=6323430017179059570>🇺🇿</emoji>",
|
||||
"🇺🇸": "<emoji document_id=6323374027985389586>🇺🇸</emoji>",
|
||||
"🇷🇺": "<emoji document_id=6323139226418284334>🇷🇺</emoji>",
|
||||
"🇰🇿": "<emoji document_id=6323135275048371614>🇰🇿</emoji>",
|
||||
"🇪🇺": "<emoji document_id=6323217102765295143>🇪🇺</emoji>",
|
||||
"🇺🇦": "<emoji document_id=6323289850921354919>🇺🇦</emoji>",
|
||||
"🇹🇷": "<emoji document_id=6321003171678259486>🇹🇷</emoji>",
|
||||
"🇵🇱": "<emoji document_id=6323602387101550101>🇵🇱</emoji>",
|
||||
"🇰🇬": "<emoji document_id=6323615997852910673>🇰🇬</emoji>",
|
||||
"bit": "<emoji document_id=6034931909945985955>💰</emoji>",
|
||||
"eth": "<emoji document_id=5280647120607521572>🔹</emoji>",
|
||||
"ton": "<emoji document_id=5863980370340351884>💰</emoji>"
|
||||
}
|
||||
|
||||
currency_mapping = {
|
||||
"EU": ("🇪🇺", "EUR"),
|
||||
"GB": ("🇬🇧", "GBP"),
|
||||
"UZ": ("🇺🇿", "UZS"),
|
||||
"US": ("🇺🇸", "USD"),
|
||||
"RU": ("🇷🇺", "RUB"),
|
||||
"KZ": ("🇰🇿", "KZT"),
|
||||
"UA": ("🇺🇦", "UAH"),
|
||||
"PL": ("🇵🇱", "PLN"),
|
||||
"TR": ("🇹🇷", "TRY"),
|
||||
"KG": ("🇰🇬", "KGS")
|
||||
}
|
||||
|
||||
currencies = [
|
||||
"EUR", "GBP", "UZS", "USD", "RUB", "KZT", "UAH", "PLN", "TRY", "KGS", "TON", "ETH", "BTC"
|
||||
]
|
||||
|
||||
currency_flags = {
|
||||
"EUR": "🇪🇺",
|
||||
"GBP": "🇬🇧",
|
||||
"UZS": "🇺🇿",
|
||||
"USD": "🇺🇸",
|
||||
"RUB": "🇷🇺",
|
||||
"KZT": "🇰🇿",
|
||||
"UAH": "🇺🇦",
|
||||
"PLN": "🇵🇱",
|
||||
"TRY": "🇹🇷",
|
||||
"KGS": "🇰🇬"
|
||||
}
|
||||
|
||||
letters_stashing = {
|
||||
"E": "cur_df",
|
||||
"G": "cur_gh",
|
||||
"P": "cur_nq",
|
||||
"R": "cur_rs",
|
||||
"S": "cur_rs",
|
||||
"T": "cur_tu",
|
||||
"U": "cur_tu",
|
||||
}
|
||||
|
||||
def currencies_markup(self, argument: str = "") -> list:
|
||||
return utils.chunks(
|
||||
[
|
||||
{
|
||||
"text": f"{self.currency_flags[cur]} {cur}",
|
||||
"callback": self.callback_4_currency,
|
||||
"args": (cur,),
|
||||
}
|
||||
for cur in [
|
||||
i
|
||||
for i in self.currency_flags.keys()
|
||||
if i.startswith(argument.upper())
|
||||
]
|
||||
if cur.startswith(argument.upper())
|
||||
],
|
||||
5,
|
||||
)
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
await utils.dnd(client, self.bot, archive=True)
|
||||
|
||||
async def get_ton_in_rub(self, am, what: str = "uzs", cup: bool = False) -> str:
|
||||
r = (
|
||||
get(f"https://coinchefs.com/{what}/ton/{am}/")
|
||||
if cup
|
||||
else get(f"https://coinchefs.com/ton/{what}/{am}/")
|
||||
)
|
||||
soup = bs(r.text, "html.parser")
|
||||
if result_div := soup.find('div', class_='convert-result'):
|
||||
if result_text_div := result_div.find(
|
||||
'div', class_='col-xs-10 col-sm-10 text-center result-text'
|
||||
):
|
||||
if value_element := result_text_div.b:
|
||||
return value_element.get_text(strip=True)
|
||||
else:
|
||||
logger.debug("Value element not found")
|
||||
else:
|
||||
logger.debug("Result text div not found")
|
||||
else:
|
||||
logger.debug("Result div not found")
|
||||
return None
|
||||
|
||||
async def callback_4_currency(self, call: InlineCall, currency: str):
|
||||
try:
|
||||
first_letter = currency[0]
|
||||
await call.answer(self.strings["processing"], show_alert=True)
|
||||
await call.delete()
|
||||
async with self.client.conversation(self.bot) as conv:
|
||||
m = await conv.send_message("/settings")
|
||||
r = await conv.get_response()
|
||||
await r.click(data=b'cur_menu')
|
||||
await r.click(data=b'cur_curmenu')
|
||||
await r.click(data=self.letters_stashing[first_letter])
|
||||
await r.click(data=f"cur_{currency.upper()}")
|
||||
await r.delete()
|
||||
await m.delete()
|
||||
await self.inline.bot.send_message(self.tg_id, self.strings["done"])
|
||||
except AlreadyInConversationError:
|
||||
await call.answer(self.strings["already_in_conv"], show_alert=True)
|
||||
|
||||
@loader.command(ru_doc="<количество> [валюта] должны быть разделены пробелом")
|
||||
async def conv(self, message: Message):
|
||||
"""<amount> [currency] should be separated by space"""
|
||||
args = utils.get_args_raw(message)
|
||||
if not args:
|
||||
await utils.answer(message, self.strings["no_args"])
|
||||
return
|
||||
# if args.split(" ")[1].upper() not in self.currencies:
|
||||
# await utils.answer(message, self.strings["wrong_currency"])
|
||||
# return
|
||||
await utils.answer(message, self.strings["wait"])
|
||||
if "ton".lower() in args.lower():
|
||||
li_args = args.split(" ")
|
||||
ex_ = await self.get_ton_in_rub(li_args[0])
|
||||
try:
|
||||
async with message.client.conversation(self.bot) as conv:
|
||||
msg = await conv.send_message(args) if "ton".lower() not in args.lower() else await conv.send_message(ex_)
|
||||
r = await conv.get_response()
|
||||
res = r.text
|
||||
text_ = ""
|
||||
text_ += (
|
||||
self.strings["converted"].format(args)
|
||||
if "ton".lower() not in args.lower()
|
||||
else self.strings["converted"].format(f"{li_args[0]} TON")
|
||||
)
|
||||
for emoji, currency, *_ in self.currency_mapping.values():
|
||||
if match := re.findall(f"{emoji} ?(.*) {currency}", res):
|
||||
text_ += (
|
||||
f"<b>{self.custom_emojis.get(emoji)} {currency}:</b> "
|
||||
f"<code>{match[0]}</code>\n"
|
||||
)
|
||||
|
||||
if match := re.findall(r"(.*) BTC", res):
|
||||
text_ += f"\n<b>{self.custom_emojis['bit']} BTC:</b> <code>{match[0]}</code>\n"
|
||||
if match := re.findall(r"(.*) ETH", res):
|
||||
text_ += f"<b>{self.custom_emojis['eth']} ETH:</b> <code>{match[0]}</code>\n"
|
||||
|
||||
if ex_ := await self.get_ton_in_rub(args.split(" ")[0], args.split(" ")[1].lower(), True):
|
||||
text_ += f"<b>{self.custom_emojis['ton']} TON:</b> <code>{ex_.split(' = ')[1]}</code>\n"
|
||||
await utils.answer(message, text_)
|
||||
await msg.delete()
|
||||
await r.delete()
|
||||
except AlreadyInConversationError:
|
||||
await utils.answer(message, self.strings["already"])
|
||||
except TimeoutError:
|
||||
await utils.answer(message, self.strings["unsupported"])
|
||||
except IndexError:
|
||||
await utils.answer(message, self.strings["no_args"])
|
||||
|
||||
|
||||
@loader.command(ru_doc="[валюта] | без аргументов покажет список валют для включения/выключения")
|
||||
async def controlvalute(self, message: Message):
|
||||
"""[currency] | without arguments will show list of currencies for enable/disable"""
|
||||
if args := utils.get_args_raw(message):
|
||||
await utils.answer(message, self.strings["choose_currency"], reply_markup=self.currencies_markup(args))
|
||||
else:
|
||||
return await utils.answer(message, self.strings["choose_currency"], reply_markup=self.currencies_markup())
|
||||
|
||||
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Alarm.jpg
|
||||
|
||||
import re
|
||||
import pytz
|
||||
import random
|
||||
import logging
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
|
||||
from .. import utils, loader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
day_to_weekday = {
|
||||
"mon": 0,
|
||||
"tue": 1,
|
||||
"wed": 2,
|
||||
"thu": 3,
|
||||
"fri": 4,
|
||||
"sat": 5,
|
||||
"sun": 6,
|
||||
"пн": 0,
|
||||
"вт": 1,
|
||||
"ср": 2,
|
||||
"чт": 3,
|
||||
"пт": 4,
|
||||
"сб": 5,
|
||||
"вс": 6,
|
||||
}
|
||||
|
||||
|
||||
@loader.tds
|
||||
class AlarmMod(loader.Module):
|
||||
"""Alarm module for remind you about something"""
|
||||
|
||||
strings = {
|
||||
"name": "Alarm",
|
||||
"set": "<emoji document_id=5870729937215819584>⏰</emoji> <b>Alarm set for <code>{}</code>!</b>",
|
||||
"unset": "<emoji document_id=5213107179329953547>⏰</emoji> <b>Alarm for <code>{}</code> unset!</b>",
|
||||
"unset_all": "<emoji document_id=5213107179329953547>⏰</emoji> <b>All alarms unset!</b>",
|
||||
"list_item": (
|
||||
"<emoji document_id=6334603778326529773>⏰</emoji> <b>Alarm for <code>{}</code>!</b> <code>#{}</code>"
|
||||
"\n<emoji document_id=6334699757960693635>🕔</emoji> <b>Time:</b> <code>{}</code>"
|
||||
"\n<emoji document_id=6334388660594542334>🔊</emoji> <b>Message:</b> <code>{}</code>"
|
||||
),
|
||||
"no_alarms": "<emoji document_id=5208549407280078951>🙅♂️</emoji> <b>No alarms!</b>",
|
||||
"off_button": "✋ Off",
|
||||
"notification": "⏰ <b>Alarm!</b>\n\n<code>{}</code>",
|
||||
"turned_off": "✔️ <b>Alarm turned off!</b>",
|
||||
"incorrect_time": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Incorrect time!</b>",
|
||||
"where_args": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Where arguments?</b>",
|
||||
"incorrect_args": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Incorrect arguments! Write like this:</b> <code>.setalarm mon 12:00 text</code>",
|
||||
"interval_doc": "Interval of sending notifications in seconds",
|
||||
"time_zone_doc": "Time zone for alarms (for example, Europe/Moscow)",
|
||||
}
|
||||
strings_ru = {
|
||||
"set": "<emoji document_id=5870729937215819584>⏰</emoji> <b>Напоминание установлено на <code>{}</code>!</b>",
|
||||
"unset": "<emoji document_id=5213107179329953547>⏰</emoji> <b>Напоминание для <code>{}</code> отменено!</b>",
|
||||
"unset_all": "<emoji document_id=5213107179329953547>⏰</emoji> <b>Все напоминания отменены!</b>",
|
||||
"list_item": (
|
||||
"<emoji document_id=6334603778326529773>⏰</emoji> <b>Напоминание для <code>{}</code>!</b> <code>#{}</code>"
|
||||
"\n<emoji document_id=6334699757960693635>🕔</emoji> <b>Время:</b> <code>{}</code>"
|
||||
"\n<emoji document_id=6334388660594542334>🔊</emoji> <b>Сообщение:</b> <code>{}</code>"
|
||||
),
|
||||
"no_alarms": "<emoji document_id=5208549407280078951>🙅♂️</emoji> <b>Нет напоминаний!</b>",
|
||||
"off_button": "✋ Выключить",
|
||||
"notification": "⏰ <b>Напоминание!</b>\n\n<code>{}</code>",
|
||||
"turned_off": "✔️ <b>Напоминание выключено!</b>",
|
||||
"incorrect_time": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Неправильное время!</b>",
|
||||
"where_args": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Где аргументы?</b>",
|
||||
"incorrect_args": "<emoji document_id=5371015453013450536>🖕</emoji> <b>Неправильные аргументы! Пиши так:</b> <code>.setalarm пн 12:00 текст</code>",
|
||||
"interval_doc": "Интервал отправления напоминаний в секундах",
|
||||
"time_zone_doc": "Часовой пояс для напоминаний (например, Europe/Moscow)",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"interval",
|
||||
5,
|
||||
lambda: self.strings("interval_doc"),
|
||||
validator=loader.validators.Integer(minimum=1, maximum=60),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"time_zone",
|
||||
"Europe/Moscow",
|
||||
lambda: self.strings("time_zone_doc"),
|
||||
validator=loader.validators.RegExp(
|
||||
r"^[\w/]+$",
|
||||
)
|
||||
),
|
||||
)
|
||||
@loader.command(ru_doc="<день недели> <время> <сообщение> - установить напоминание")
|
||||
async def setalarm(self, message):
|
||||
"""<day of the week> <time> <message> - set alarm"""
|
||||
|
||||
args = utils.get_args_raw(message)
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings("where_args"))
|
||||
try:
|
||||
re_args = re.match(r"^(.+) (\d{1,2}):(\d{1,2}) (.*)$", args)
|
||||
day = re_args.group(1).lower()
|
||||
hour = int(re_args.group(2))
|
||||
minute = int(re_args.group(3))
|
||||
text = re_args.group(4)
|
||||
except AttributeError:
|
||||
return await utils.answer(message, self.strings("incorrect_args"))
|
||||
|
||||
if not (0 <= hour <= 23 and 0 <= minute <= 59):
|
||||
return await utils.answer(message, self.strings("incorrect_time"))
|
||||
if day not in day_to_weekday.keys():
|
||||
text = f"<b>Wrong day of the week!</b>\n<b>Available days:</b> <code>{', '.join(day_to_weekday.keys())}</code>"
|
||||
return await utils.answer(message, text)
|
||||
|
||||
id_ = random.randint(100, 999)
|
||||
self.set(
|
||||
"alarms",
|
||||
{
|
||||
**self.get("alarms", {}),
|
||||
day: {
|
||||
"hour": hour,
|
||||
"minute": minute,
|
||||
"text": text,
|
||||
"id": id_,
|
||||
"status": "on",
|
||||
},
|
||||
},
|
||||
)
|
||||
await utils.answer(message, self.strings("set").format(day))
|
||||
|
||||
@loader.command(ru_doc="получить список напоминаний")
|
||||
async def alarms(self, message):
|
||||
"""get alarms list"""
|
||||
|
||||
alarms = self.get("alarms", {})
|
||||
if not alarms:
|
||||
return await utils.answer(message, self.strings("no_alarms"))
|
||||
|
||||
text = ""
|
||||
for day, alarm in alarms.items():
|
||||
text += self.strings("list_item").format(
|
||||
day,
|
||||
f"{alarm['id']}",
|
||||
f"{alarm['hour']}:{alarm['minute']}",
|
||||
alarm["text"],
|
||||
)
|
||||
text += "\n\n"
|
||||
await utils.answer(message, text)
|
||||
|
||||
@loader.command(ru_doc="<id> - отменить напоминание")
|
||||
async def unsetalarm(self, message):
|
||||
"""<id> - unset alarm"""
|
||||
|
||||
args = utils.get_args_raw(message)
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings("where_time"))
|
||||
if args.startswith("#"):
|
||||
args = args[1:]
|
||||
|
||||
alarms = self.get("alarms", {})
|
||||
for day, alarm in alarms.items():
|
||||
if str(alarm["id"]) == args:
|
||||
alarms.pop(day)
|
||||
self.set("alarms", alarms)
|
||||
return await utils.answer(
|
||||
message, self.strings("unset").format(day)
|
||||
)
|
||||
await utils.answer(message, self.strings("unset").format(args))
|
||||
|
||||
@loader.command(ru_doc="отменить все напоминания")
|
||||
async def unsetallalarms(self, message):
|
||||
"""unset all alarms"""
|
||||
|
||||
self.set("alarms", {})
|
||||
await utils.answer(message, self.strings("unset_all"))
|
||||
|
||||
@loader.loop(interval=2, autostart=True)
|
||||
async def check_alarms(self):
|
||||
alarms = self.get("alarms", {})
|
||||
if not alarms:
|
||||
return
|
||||
now = datetime.now(tz=pytz.timezone(self.config["time_zone"]))
|
||||
day = now.weekday()
|
||||
hour = now.hour
|
||||
minute = now.minute
|
||||
for day_, alarm in alarms.items():
|
||||
if (
|
||||
day_to_weekday[day_] == day
|
||||
and alarm["hour"] == hour
|
||||
and alarm["minute"] == minute
|
||||
):
|
||||
while alarm["status"] == "on":
|
||||
self._markup = self.inline.generate_markup(
|
||||
{
|
||||
"text": self.strings("off_button"),
|
||||
"callback": self.off_alarm,
|
||||
"args": (alarm["id"],),
|
||||
}
|
||||
)
|
||||
await self.inline.bot.send_message(
|
||||
self.tg_id,
|
||||
self.strings("notification").format(alarm["text"]),
|
||||
reply_markup=self._markup,
|
||||
)
|
||||
await asyncio.sleep(self.config["interval"])
|
||||
break
|
||||
|
||||
async def off_alarm(self, call, id_):
|
||||
alarms = self.get("alarms", {})
|
||||
for day, alarm in alarms.items():
|
||||
if alarm["id"] == id_:
|
||||
alarm["status"] = "off"
|
||||
self.set("alarms", alarms)
|
||||
await call.edit(self.strings("turned_off"))
|
||||
return False
|
||||
await call.answer("Не найдено!")
|
||||
@@ -1,118 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/Amethyste.jpg?raw=true
|
||||
|
||||
from .. import utils, loader
|
||||
from hikkatl.errors.common import AlreadyInConversationError
|
||||
from telethon.tl.types import Message
|
||||
|
||||
|
||||
@loader.tds
|
||||
class Amethyste(loader.Module):
|
||||
"""Generate memes image"""
|
||||
|
||||
strings = {
|
||||
"name": "Amethyste",
|
||||
"wait": "<emoji document_id=5328115567314346398>🫥</emoji> <b>Wait...</b>",
|
||||
"already_open": "<emoji document_id=5330241494521487534>😹</emoji> <b>Conversation already opened Please wait.</b>",
|
||||
"r_photo": "<emoji document_id=5298636457982826800>🖼</emoji> <b>Please reply to image.</b>",
|
||||
"no_args": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Pls provide args</b>",
|
||||
"not_found": "<emoji document_id=5345937796102104039>🤷♀️</emoji> <b>Not found</b>",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"wait": "<emoji document_id=5328115567314346398>🫥</emoji> <b>Подождите...</b>",
|
||||
"already_open": "<emoji document_id=5330241494521487534>😹</emoji> <b>Диалог уже открыт. Подождите.</b>",
|
||||
"r_photo": "<emoji document_id=5298636457982826800>🖼</emoji> <b>Ответьте на фото.</b>",
|
||||
"no_args": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Укажите аргументы</b>",
|
||||
"not_found": "<emoji document_id=5345937796102104039>🤷♀️</emoji> <b>Не найдено</b>",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"wait": "<emoji document_id=5328115567314346398>🫥</emoji> <b>Kuting...</b>",
|
||||
"already_open": "<emoji document_id=5330241494521487534>😹</emoji> <b>Dialog allaqachon ochilgan. Iltimos, kuting.</b>",
|
||||
"r_photo": "<emoji document_id=5298636457982826800>🖼</emoji> <b>Rasmga javob bering.</b>",
|
||||
"no_args": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Argumetlarni ko'rsating</b>",
|
||||
"not_found": "<emoji document_id=5345937796102104039>🤷♀️</emoji> <b>Topilmadi</b>",
|
||||
}
|
||||
|
||||
_list = [
|
||||
"3000years",
|
||||
"approved",
|
||||
"beautiful",
|
||||
"brazzers",
|
||||
"burn",
|
||||
"challenger",
|
||||
"circle",
|
||||
"contrast",
|
||||
"crush",
|
||||
"ddungeon",
|
||||
"dictator",
|
||||
"distort",
|
||||
"emboss",
|
||||
"fire",
|
||||
"frame",
|
||||
"afusion",
|
||||
"glitch",
|
||||
"greyscale",
|
||||
"instagram",
|
||||
"invert",
|
||||
"jail",
|
||||
"magik",
|
||||
"missionpassed",
|
||||
"moustache",
|
||||
"ps4",
|
||||
"posterize",
|
||||
"rejected",
|
||||
"rip",
|
||||
"scary",
|
||||
"scrolloftruth",
|
||||
"sepia",
|
||||
"sharpen",
|
||||
"sniper",
|
||||
"thanos",
|
||||
"trinity",
|
||||
"triggered",
|
||||
"unsharpen",
|
||||
"utatoo",
|
||||
"wanted",
|
||||
"wasted",
|
||||
]
|
||||
|
||||
async def amegencmd(self, message: Message):
|
||||
"""Generate memes image"""
|
||||
reply = await message.get_reply_message()
|
||||
args = utils.get_args_raw(message)
|
||||
await utils.answer(message, self.strings["wait"])
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings["no_args"])
|
||||
elif not reply.photo:
|
||||
return await utils.answer(message, self.strings["r_photo"])
|
||||
elif args not in self._list:
|
||||
return await utils.answer(message, self.strings["not_found"])
|
||||
async with self.client.conversation("@aozoram_bot") as conv:
|
||||
try:
|
||||
msg = await conv.send_message("/start")
|
||||
s = await conv.get_response()
|
||||
f = await conv.send_file(file=reply)
|
||||
m = await f.reply(f"/amegen {args}")
|
||||
await conv.get_response() # wait for response
|
||||
response = await conv.get_response()
|
||||
await utils.answer_file(message, response.media)
|
||||
await s.delete()
|
||||
await msg.delete()
|
||||
await m.delete()
|
||||
except AlreadyInConversationError:
|
||||
await utils.answer(message, self.strings["already_open"])
|
||||
await self.client.delete_dialog("@aozoram_bot")
|
||||
|
||||
async def amelistcmd(self, message: Message):
|
||||
"""List of memes"""
|
||||
spis = "\n".join([f"• <code>{i}</code>" for i in self._list])
|
||||
await utils.answer(message, f"<b>Available memes:</b>\n\n{spis}")
|
||||
@@ -1,258 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/AmoreInfo.jpg
|
||||
|
||||
import logging
|
||||
import git
|
||||
|
||||
from telethon.tl.types import Message
|
||||
from telethon.utils import get_display_name
|
||||
|
||||
from .. import loader, main, utils
|
||||
import datetime
|
||||
import time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@loader.tds
|
||||
class AmoreindoMod(loader.Module):
|
||||
"""Show userbot info"""
|
||||
|
||||
strings = {
|
||||
"name": "AmoreInfo",
|
||||
"owner": "Owner",
|
||||
"version": "Version",
|
||||
"build": "Build",
|
||||
"prefix": "Prefix",
|
||||
"time": "Time",
|
||||
"platform": "Platform",
|
||||
"uptime": "Uptime",
|
||||
"up-to-date": "😌 Actual version",
|
||||
"update_required": "😕 Outdated version </b><code>.update</code><b>",
|
||||
"_cfg_cst_msg": "Custom message for info. May contain {me}, {version}, {build}, {prefix}, {platform}, {upd}, {time}, {uptime} keywords",
|
||||
"_cfg_cst_btn": "Custom button for info. Leave empty to remove button",
|
||||
"_cfg_cst_bnr": "Custom Banner for info.",
|
||||
"_cfg_cst_frmt": "Custom fileformat for Banner info.",
|
||||
"_cfg_banner": "Set `True` in order to disable an image banner",
|
||||
"_cfg_time": "Use 1, -1, -3 etc.",
|
||||
"_cfg_close": "Here you can change close button name",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"owner": "Владелец",
|
||||
"version": "Версия",
|
||||
"build": "Сборка",
|
||||
"prefix": "Префикс",
|
||||
"uptime": "Аптайм",
|
||||
"platform": "Платформа",
|
||||
"time": "Время",
|
||||
"up-to-date": "😌 Актуальная версия",
|
||||
"update_required": "😕 Требуется обновление </b><code>.update</code><b>",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"owner": "Egasi",
|
||||
"version": "Versiya",
|
||||
"build": "Yig'ish",
|
||||
"prefix": "Prefix",
|
||||
"uptime": "Uptime",
|
||||
"platform": "Platforma",
|
||||
"time": "Soat",
|
||||
"up-to-date": "😌 Joriy versiya",
|
||||
"update_required": "😕 Yangilanish talab qilinadi </b><code>.update</code><b>",
|
||||
}
|
||||
|
||||
strings_de = {
|
||||
"owner": "Besitzer",
|
||||
"version": "Version",
|
||||
"build": "Zusammenbau",
|
||||
"prefix": "Präfix",
|
||||
"uptime": "Betriebszeit",
|
||||
"platform": "Plattform",
|
||||
"time": "Die Zeit",
|
||||
"up-to-date": "😌 Aktuelle Version",
|
||||
"update_required": "😕 Aktualisierung erforderlich </b><code>.update</code><b>",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"custom_message",
|
||||
"no",
|
||||
doc=lambda: self.strings("_cfg_cst_msg"),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_button1",
|
||||
["🏡 Modules", "https://t.me/amoremods"],
|
||||
lambda: self.strings("_cfg_cst_btn"),
|
||||
validator=loader.validators.Series(min_len=0, max_len=2),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_button2",
|
||||
[],
|
||||
lambda: self.strings("_cfg_cst_btn"),
|
||||
validator=loader.validators.Series(min_len=0, max_len=2),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_button3",
|
||||
[],
|
||||
lambda: self.strings("_cfg_cst_btn"),
|
||||
validator=loader.validators.Series(min_len=0, max_len=2),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_banner",
|
||||
"https://te.legra.ph/file/64bde7bf6b8e377521134.mp4",
|
||||
lambda: self.strings("_cfg_cst_bnr"),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"disable_banner",
|
||||
False,
|
||||
lambda: self.strings("_cfg_banner"),
|
||||
validator=loader.validators.Boolean(),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_format",
|
||||
"gif",
|
||||
lambda: self.strings("_cfg_cst_frmt"),
|
||||
validator=loader.validators.Choice(["photo", "video", "gif"]),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"timezone",
|
||||
"+5",
|
||||
lambda: self.strings("_cfg_time"),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"close_btn",
|
||||
"🔻Close",
|
||||
lambda: self.strings("_cfg_close"),
|
||||
),
|
||||
)
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
self._db = db
|
||||
self._client = client
|
||||
self._me = await client.get_me()
|
||||
|
||||
def _render_info(self) -> str:
|
||||
ver = utils.get_git_hash() or "Unknown"
|
||||
|
||||
try:
|
||||
repo = git.Repo()
|
||||
diff = repo.git.log(["HEAD..origin/master", "--oneline"])
|
||||
upd = (
|
||||
self.strings("update_required") if diff else self.strings("up-to-date")
|
||||
)
|
||||
except Exception:
|
||||
upd = ""
|
||||
|
||||
me = f'<b><a href="tg://user?id={self._me.id}">{utils.escape_html(get_display_name(self._me))}</a></b>'
|
||||
version = f'<i>{".".join(list(map(str, list(main.__version__))))}</i>'
|
||||
build = f'<a href="https://github.com/hikariatama/Hikka/commit/{ver}">#{ver[:8]}</a>' # fmt: skip
|
||||
prefix = f"«<code>{utils.escape_html(self.get_prefix())}</code>»"
|
||||
platform = utils.get_named_platform()
|
||||
uptime = utils.formatted_uptime()
|
||||
offset = datetime.timedelta(hours=self.config["timezone"])
|
||||
tz = datetime.timezone(offset)
|
||||
time1 = datetime.datetime.now(tz)
|
||||
time = time1.strftime("%H:%M:%S")
|
||||
|
||||
return (
|
||||
"<b> </b>\n"
|
||||
+ self.config["custom_message"].format(
|
||||
me=me,
|
||||
version=version,
|
||||
build=build,
|
||||
upd=upd,
|
||||
prefix=prefix,
|
||||
platform=platform,
|
||||
uptime=uptime,
|
||||
time=time,
|
||||
)
|
||||
if self.config["custom_message"] != "no"
|
||||
else (
|
||||
"<b>🎢 AmoreInfo </b>\n"
|
||||
f'<b>🤴 {self.strings("owner")}: </b>{me}\n\n'
|
||||
f"<b>🕶 {self.strings('version')}: </b>{version} {build}\n"
|
||||
f"<b>{upd}</b>\n"
|
||||
f"<b>⏳ {self.strings('uptime')}: {uptime}</b>\n\n"
|
||||
f"<b>⌚ {self.strings('time')}: {time}</b>\n"
|
||||
f"<b>📼 {self.strings('prefix')}: </b>{prefix}\n"
|
||||
f"{platform}\n"
|
||||
)
|
||||
)
|
||||
|
||||
def _get_mark(self, int):
|
||||
if int == 1:
|
||||
return (
|
||||
{
|
||||
"text": self.config["custom_button1"][0],
|
||||
"url": self.config["custom_button1"][1],
|
||||
}
|
||||
if self.config["custom_button1"]
|
||||
else None
|
||||
)
|
||||
|
||||
elif int == 2:
|
||||
return (
|
||||
{
|
||||
"text": self.config["custom_button2"][0],
|
||||
"url": self.config["custom_button2"][1],
|
||||
}
|
||||
if self.config["custom_button2"]
|
||||
else None
|
||||
)
|
||||
|
||||
elif int == 3:
|
||||
return (
|
||||
{
|
||||
"text": self.config["custom_button3"][0],
|
||||
"url": self.config["custom_button3"][1],
|
||||
}
|
||||
if self.config["custom_button3"]
|
||||
else None
|
||||
)
|
||||
|
||||
elif int == 4:
|
||||
return (
|
||||
{
|
||||
"text": self.config["close_btn"],
|
||||
"action": "close",
|
||||
}
|
||||
if self.config["close_btn"]
|
||||
else None
|
||||
)
|
||||
|
||||
@loader.owner
|
||||
async def ainfocmd(self, message: Message):
|
||||
"""Send userbot info"""
|
||||
m1 = self._get_mark(1)
|
||||
m2 = self._get_mark(2)
|
||||
m3 = self._get_mark(3)
|
||||
m4 = self._get_mark(4)
|
||||
|
||||
await self.inline.form(
|
||||
message=message,
|
||||
text=self._render_info(),
|
||||
reply_markup=[
|
||||
[
|
||||
*([m1] if m1 else []),
|
||||
],
|
||||
[
|
||||
*([m2] if m2 else []),
|
||||
*([m3] if m3 else []),
|
||||
],
|
||||
[
|
||||
*([m4] if m4 else []),
|
||||
],
|
||||
],
|
||||
**{}
|
||||
if self.config["disable_banner"]
|
||||
else {self.config["custom_format"]: self.config["custom_banner"]},
|
||||
)
|
||||
@@ -1,473 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/AnimeVoices.jpg
|
||||
|
||||
from .. import loader
|
||||
|
||||
@loader.tds
|
||||
class AnimeVoicesMod(loader.Module):
|
||||
"""🎤 Popular Anime Voices"""
|
||||
|
||||
strings = {"name": "AnimeVoices"}
|
||||
|
||||
async def smexkcmd(self, message):
|
||||
"""Смех Канеки"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/9",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def smexycmd(self, message):
|
||||
"""Смех Ягами"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/7",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def znaycmd(self, message):
|
||||
"""Знай свое место ничтожество"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/35",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def madaracmd(self, message):
|
||||
"""Учиха Мадара"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/24",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def sharingancmd(self, message):
|
||||
"""Итачи Шаринган"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/VoiceAmore/29",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def itachicmd(self, message):
|
||||
"""Учиха Итачи"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/26",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def imsasukecmd(self, message):
|
||||
"""Учиха Саске"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/VoiceAmore/30",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def paincmd(self, message):
|
||||
"""Познайте боль"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/15",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def rascmd(self, message):
|
||||
"""Расширение территории"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/17",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def tenseicmd(self, message):
|
||||
"""Shinra tensei"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/18",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def dazaicmd(self, message):
|
||||
"""Dazai"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/3",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def gaycmd(self, message):
|
||||
"""I'm gay"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/20",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def bankaicmd(self, message):
|
||||
"""Bankai"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/21",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def satecmd(self, message):
|
||||
"""Sate sate sate"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/5",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def yoaimocmd(self, message):
|
||||
"""Yoaimo"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/11",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def ghoulcmd(self, message):
|
||||
"""Я гуль"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/12",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def welawcmd(self, message):
|
||||
"""Мы закон"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/13",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def dattebayocmd(self, message):
|
||||
"""Даттебайо"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/14",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def hardlifecmd(self, message):
|
||||
"""Жизнь такова"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/16",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def hanmacmd(self, message):
|
||||
"""Я Ханма Шужи"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/25",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def surprisecmd(self, message):
|
||||
"""Surprise MxtherFxcker"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/30",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def equalcmd(self, message):
|
||||
"""Мы созданы равными"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/31",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def beautytreecmd(self, message):
|
||||
"""Красота леса"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/32",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def bankaiicmd(self, message):
|
||||
"""Bankai remix"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/33",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def yametecmd(self, message):
|
||||
"""Фулл ямете кудасай"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/47",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def mafiacmd(self, message):
|
||||
"""Просыпается мафия"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/48",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def sharinganncmd(self, message):
|
||||
"""Sharingan remix"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/49",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def smexecmd(self, message):
|
||||
"""Смех Эрен"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/50",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def narutocmd(self, message):
|
||||
"""Naruto heroes"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/51",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def smexrcmd(self, message):
|
||||
"""Смех рюк"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/52",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def ohayocmd(self, message):
|
||||
"""Охаё"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/53",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def iamhungrycmd(self, message):
|
||||
"""Есть хочу"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/54",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def amaterasucmd(self, message):
|
||||
"""Аматерасу remix"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/55",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def owocmd(self, message):
|
||||
"""Full OwO"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/56",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
|
||||
async def ghoulrucmd(self, message):
|
||||
"""Русский Tokyo Ghoul"""
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
await message.delete()
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
"https://t.me/animevoicesbyamore/57",
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
return
|
||||
#voices by @dziru
|
||||
@@ -1,283 +0,0 @@
|
||||
# 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/>.
|
||||
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods, FTG
|
||||
__version__ = (1, 1, 0)
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
|
||||
from telethon.tl import functions
|
||||
from telethon.utils import get_display_name
|
||||
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
@loader.tds
|
||||
class AutoProfileMod(loader.Module):
|
||||
"""Automatic stuff for your profile :P"""
|
||||
|
||||
strings = {
|
||||
"name": "AutoProfile",
|
||||
"invalid_args": (
|
||||
"<b>Missing parameters, please read the <code>.aguide</code> <emoji document_id=5213468029597261187>✔️</emoji></b>"
|
||||
),
|
||||
"missing_time": (
|
||||
"<b>Time was not specified in bio <emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"enabled_bio": (
|
||||
"<b>Enabled bio clock <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"bio_not_enabled": (
|
||||
"<b>Bio clock is not enabled <emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"disabled_bio": (
|
||||
"<b>Disabled bio clock <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"enabled_name": (
|
||||
"<b>Enabled name clock <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"name_not_enabled": (
|
||||
"<b>Name clock is not enabled <emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"disabled_name": (
|
||||
"<b>Name clock disabled <emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"_cfg_time": "Use timezone 1, -1, -3 etc.",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"invalid_args": (
|
||||
"<b>to'g'ri argumetlar emas, <code > ni o'qing.aguide</code> <emoji document_id=5213468029597261187>✔️</emoji></b>"
|
||||
),
|
||||
"missing_time": (
|
||||
"<b>vaqt bio-da o'rnatilmagan<emoji document_id=5215273032553078755 > ❎< / emoji></b>"
|
||||
),
|
||||
"enabled_bio": (
|
||||
"<b>Bio soat muvaffaqiyatli o'rnatildi <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"bio_not_enabled": (
|
||||
"<b>soat bio-ga o'rnatilmagan<emoji document_id=5215273032553078755 > ❎< / emoji > </b>"
|
||||
),
|
||||
"disabled_bio": (
|
||||
"<b > Bio-dagi vaqt muvaffaqiyatli o'chirildi <emoji document_id = 5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"enabled_name": (
|
||||
"<b>soat taxallusga muvaffaqiyatli o'rnatildi <emoji document_id = 5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"name_not_enabled": (
|
||||
"<b>soat taxallusga o'rnatilmagan<emoji document_id=5215273032553078755 > ❎< / emoji > </b>"
|
||||
),
|
||||
"disabled_name": (
|
||||
"<b>taxallusdagi vaqt muvaffaqiyatli o'chirildi <emoji document_id = 5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"_cfg_time": "vaqt zonasidan foydalaning 1, -1, -3 va boshqalar.",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"invalid_args": (
|
||||
"<b>Не правильные аргуметы, прочитай <code>.aguide</code> <emoji document_id=5213468029597261187>✔️</emoji></b>"
|
||||
),
|
||||
"missing_time": (
|
||||
"<b>Время не было установлено в био<emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"enabled_bio": (
|
||||
"<b>Био часы успешно установлены <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"bio_not_enabled": (
|
||||
"<b>Часы не установлено в био<emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"disabled_bio": (
|
||||
"<b>Время в био успешно отключен <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"enabled_name": (
|
||||
"<b>Часы в ник успешно установлены <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"name_not_enabled": (
|
||||
"<b>Часы не установлены в ник<emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"disabled_name": (
|
||||
"<b>Время в нике успешно отключен <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"_cfg_time": "Используй таймзону 1, -1, -3 и тд.",
|
||||
}
|
||||
|
||||
strings_de = {
|
||||
"invalid_args": (
|
||||
"<b>Sind nicht die richtigen Argumente, lies <code>.aguide</code> <emoji document_id=5213468029597261187>✔️</emoji></b>"
|
||||
),
|
||||
"missing_time": (
|
||||
"<b>Die Zeit wurde nicht auf bio gesetzt<emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"enabled_bio": (
|
||||
"<b>Bio-Uhr wurde erfolgreich installiert <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"bio_not_enabled": (
|
||||
"<b>Die Uhr ist nicht auf bio eingestellt<emoji document_id=5215273032553078755>❎</emoji></b>"
|
||||
),
|
||||
"disabled_bio": (
|
||||
"<b>Zeit in bio erfolgreich deaktiviert <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"enabled_name": (
|
||||
"<b>Die Uhr wurde erfolgreich auf den Nickname gesetzt <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"name_not_enabled": (
|
||||
"<b>Die Uhr ist nicht auf den Spitznamen<emoji document_id=5215273032553078755>❎</emoji></b> eingestellt"
|
||||
),
|
||||
"disabled_name": (
|
||||
"<b>Nickzeit wurde erfolgreich deaktiviert <emoji document_id=5212932275376759608>✅</emoji></b>"
|
||||
),
|
||||
"_cfg_time": "Benutze die Zeitzone 1, -1, -3 usw.",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.bio_enabled = False
|
||||
self.name_enabled = False
|
||||
self.raw_bio = None
|
||||
self.raw_name = None
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"timezone",
|
||||
"+5",
|
||||
lambda: self.strings("_cfg_time"),
|
||||
),
|
||||
)
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
self.client = client
|
||||
self._me = await client.get_me()
|
||||
|
||||
@loader.command(ru_doc="""Что-бы указать таймзону через конфиг""")
|
||||
async def cfautoprofcmd(self, message):
|
||||
"""To specify the timezone via the config"""
|
||||
name = self.strings("name")
|
||||
await self.allmodules.commands["config"](
|
||||
await utils.answer(message,
|
||||
f"{self.get_prefix()}config {name}")
|
||||
)
|
||||
|
||||
@loader.command(ru_doc="""Автоматически изменяет биографию вашей учетной записи с учетом текущего времени, использования: .autobio 'сообщение, время как {time}'""")
|
||||
async def autobiocmd(self, message):
|
||||
"""Automatically changes your account's bio with current time, usage:
|
||||
.autobio 'message, time as {time}'"""
|
||||
|
||||
msg = utils.get_args(message)
|
||||
if len(msg) != 1:
|
||||
return await utils.answer(message, self.strings("invalid_args", message))
|
||||
raw_bio = msg[0]
|
||||
if "{time}" not in raw_bio:
|
||||
return await utils.answer(message, self.strings("missing_time", message))
|
||||
|
||||
|
||||
self.bio_enabled = True
|
||||
self.raw_bio = raw_bio
|
||||
await self.allmodules.log("start_autobio")
|
||||
await utils.answer(message, self.strings("enabled_bio", message))
|
||||
|
||||
while self.bio_enabled:
|
||||
offset = datetime.timedelta(hours=self.config["timezone"])
|
||||
tz = datetime.timezone(offset)
|
||||
time1 = datetime.datetime.now(tz)
|
||||
current_time = time1.strftime("%H:%M")
|
||||
bio = raw_bio.format(time=current_time)
|
||||
await self.client(functions.account.UpdateProfileRequest(about=bio))
|
||||
await asyncio.sleep(60)
|
||||
|
||||
@loader.command(ru_doc="""Что-бы остановить время в био введи .stopautobio""")
|
||||
async def stopautobiocmd(self, message):
|
||||
"""Stop autobio cmd."""
|
||||
|
||||
if self.bio_enabled is False:
|
||||
return await utils.answer(message, self.strings("bio_not_enabled", message))
|
||||
self.bio_enabled = False
|
||||
|
||||
await self.allmodules.log("stop_autobio")
|
||||
await utils.answer(message, self.strings("disabled_bio", message))
|
||||
await self.client(
|
||||
functions.account.UpdateProfileRequest(about=self.raw_bio.format(time=""))
|
||||
)
|
||||
|
||||
@loader.command(ru_doc="""Автоматически изменяет имя вашей учетной записи с учетом текущего времени, использования: .autoname 'сообщение, время как {time}'""")
|
||||
async def autonamecmd(self, message):
|
||||
"""Automatically changes your Telegram name with current time, usage:
|
||||
.autoname '<message, time as {time}>'"""
|
||||
|
||||
msg = utils.get_args(message)
|
||||
if len(msg) != 1:
|
||||
return await utils.answer(message, self.strings("invalid_args", message))
|
||||
raw_name = msg[0]
|
||||
if "{time}" not in raw_name:
|
||||
return await utils.answer(message, self.strings("missing_time", message))
|
||||
|
||||
self.name_enabled = True
|
||||
self.raw_name = raw_name
|
||||
await self.allmodules.log("start_autoname")
|
||||
await utils.answer(message, self.strings("enabled_name", message))
|
||||
|
||||
while self.name_enabled:
|
||||
offset = datetime.timedelta(hours=self.config["timezone"])
|
||||
tz = datetime.timezone(offset)
|
||||
time1 = datetime.datetime.now(tz)
|
||||
current_time = time1.strftime("%H:%M")
|
||||
name = raw_name.format(time=current_time)
|
||||
await self.client(functions.account.UpdateProfileRequest(first_name=name))
|
||||
await asyncio.sleep(60)
|
||||
|
||||
@loader.command(ru_doc="""Что-бы остановить время в имени учетной записи введи .stopautoname""")
|
||||
async def stopautonamecmd(self, message):
|
||||
"""just write .stopautoname"""
|
||||
|
||||
if self.name_enabled is False:
|
||||
return await utils.answer(
|
||||
message, self.strings("name_not_enabled", message)
|
||||
)
|
||||
|
||||
self.name_enabled = False
|
||||
await self.allmodules.log("stop_autoname")
|
||||
await utils.answer(message, self.strings("disabled_name", message))
|
||||
await self.client(
|
||||
functions.account.UpdateProfileRequest(
|
||||
first_name=self.raw_name.format(time="")
|
||||
)
|
||||
)
|
||||
|
||||
@loader.command(ru_docs="""Доки ru/en""")
|
||||
async def aguide(self, message):
|
||||
"Just guide ru/en"
|
||||
args = utils.get_args_raw(message)
|
||||
args = args if args in {"en", "ru"} else "en"
|
||||
|
||||
time = "{time}"
|
||||
nick = f'<a href="tg://user?id={self._me.id}">{utils.escape_html(get_display_name(self._me))}</a>'
|
||||
pref = f"{utils.escape_html(self.get_prefix())}"
|
||||
|
||||
await utils.answer(
|
||||
message,
|
||||
f"<emoji document_id=5789581976176430614>💸</emoji> For example:\n\n<emoji document_id=5789667570579672963>💸</emoji> AutoName: <code>{pref}autoname '{nick} | {time}'</code>\n"
|
||||
f"<emoji document_id=5789667570579672963>💸</emoji> AutoBio: <code>{pref}autobio 'smth | {time}'</code>\n"
|
||||
if args == "en"
|
||||
else (
|
||||
f"<emoji document_id=5789581976176430614>💸</emoji> Например:\n\n<emoji document_id=5789667570579672963>💸</emoji> Авто Ник: <code>{pref}autoname '{nick} | {time}'</code>\n"
|
||||
f"<emoji document_id=5789667570579672963>💸</emoji> Авто Био: <code>{pref}autobio 'что-то | {time}'</code>\n"
|
||||
),
|
||||
)
|
||||
@@ -1,124 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# If you don't like the module don't use it
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/besafe.jpg?raw=true
|
||||
|
||||
import logging
|
||||
import requests
|
||||
import ast
|
||||
import re
|
||||
from .. import loader, utils
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
__version__ = (1, 0, 0)
|
||||
|
||||
|
||||
@loader.tds
|
||||
class BeSafe(loader.Module):
|
||||
"""
|
||||
Check module before loading
|
||||
"""
|
||||
|
||||
strings = {
|
||||
"name": "BeSafe",
|
||||
"no_args_or_reply": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>[BeSafe]</b> No link or reply to file",
|
||||
"safe": "<emoji document_id=5203929938024999176>🛡</emoji> <b>Module is safe</b>",
|
||||
"suspicious": "<emoji document_id=5325771498718241219>🔎</emoji> Module is suspicious\n\n<emoji document_id=6334443713485342501>⛩</emoji> <b>Suspicious imports:</b>\n",
|
||||
'sus_keywords': "\n<emoji document_id=6334405093139416847>🔑</emoji> <b>Suspicous keywords:</b>"
|
||||
}
|
||||
strings_ru = {
|
||||
"no_args_or_reply": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>[BeSafe]</b> Нет ссылки или реплея на модуль",
|
||||
"safe": "<emoji document_id=5203929938024999176>🛡</emoji> <b>Модуль безопасен</b>",
|
||||
"suspicious": "<emoji documentx_id=5325771498718241219>🔎</emoji> Модуль подозрительный\n\n<emoji document_id=6334443713485342501>⛩</emoji> <b>Подозрительные импорты:</b>\n",
|
||||
'sus_keywords': "\n<emoji document_id=6334405093139416847>🔑</emoji> <b>Подозрительные ключевые слова:</b>"
|
||||
}
|
||||
|
||||
def extract_imports(self, code):
|
||||
code = code.lstrip('\ufeff') # крч удаление символа BOM, если он есть
|
||||
|
||||
try:
|
||||
tree = ast.parse(code)
|
||||
except SyntaxError as e:
|
||||
if "invalid non-printable character" not in str(e):
|
||||
raise
|
||||
code = code.encode('utf-8-sig').decode('utf-8')
|
||||
tree = ast.parse(code)
|
||||
imports = []
|
||||
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
imports.extend(name.name for name in node.names)
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
module_name = node.module
|
||||
imports.extend(f"{module_name}.{name.name}" for name in node.names)
|
||||
return imports
|
||||
|
||||
|
||||
|
||||
suspicious_imports = [
|
||||
'glob',
|
||||
'os',
|
||||
'sys',
|
||||
'telethon.tl.TLRequest',
|
||||
'requests',
|
||||
]
|
||||
suspicious_keywords = [
|
||||
r'0x418d4e0b',
|
||||
r'0xf5b399ac',
|
||||
r'w+z+mm+"A"+nk+u+h+lk',
|
||||
r'b"\x0bN\x8dA"'
|
||||
r'session',
|
||||
r'TestingHikka_BOT' # временно будет тут
|
||||
]
|
||||
|
||||
def extract_keywords(self, code):
|
||||
words = []
|
||||
for word in self.suspicious_keywords:
|
||||
if r := re.findall(word, code):
|
||||
words.append(r[0])
|
||||
return words
|
||||
|
||||
|
||||
|
||||
@loader.command()
|
||||
async def bs(self, message):
|
||||
"""
|
||||
BeSafe - <reply to module> or <link to module>
|
||||
"""
|
||||
args = utils.get_args_raw(message)
|
||||
reply = await message.get_reply_message()
|
||||
|
||||
if args:
|
||||
r = await utils.run_sync(requests.get, args)
|
||||
string = r.text
|
||||
elif reply:
|
||||
code = (await self._client.download_file(reply.media, bytes)).decode("utf-8")
|
||||
string = code
|
||||
else:
|
||||
await utils.answer(message, self.strings["no_args_or_reply"])
|
||||
|
||||
imports = self.extract_imports(string)
|
||||
sus_imports = [f"▫️ <code>{imp}</code>" for imp in self.suspicious_imports if imp in imports]
|
||||
sus_keywords = []
|
||||
|
||||
if sus_imports:
|
||||
kw = self.extract_keywords(string)
|
||||
sus_keywords = [f"▫️ <code>{k}</code>" for k in self.suspicious_keywords if k in kw]
|
||||
|
||||
if sus_imports or sus_keywords:
|
||||
sus_list = sus_imports + [self.strings["sus_keywords"]] + sus_keywords
|
||||
text = self.strings["suspicious"] + '\n'.join(sus_list)
|
||||
else:
|
||||
text = self.strings["safe"]
|
||||
|
||||
await utils.answer(message, text)
|
||||
|
||||
|
||||
@@ -1,229 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
|
||||
import re
|
||||
import asyncio
|
||||
import random
|
||||
from aiohttp import web
|
||||
from .. import utils, loader
|
||||
|
||||
|
||||
class WebCreator:
|
||||
def __init__(self, name, tg_link, preview_name):
|
||||
self.url = None
|
||||
self.app = web.Application()
|
||||
self.app.router.add_get("/", self.index)
|
||||
self.name = name
|
||||
self.tg_link = tg_link
|
||||
self.preview_name = preview_name
|
||||
|
||||
async def index(self, request):
|
||||
html_content = f"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<title>For {self.name}</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Indie+Flower&display=swap" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.5.1"></script>
|
||||
</head>
|
||||
|
||||
<style>
|
||||
body {{
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
background: #1d1d1d;
|
||||
font: 22px 'Indie Flower', cursive, "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
color: #fff;
|
||||
overflow-x: hidden;
|
||||
}}
|
||||
|
||||
#content {{
|
||||
position: relative;
|
||||
max-width: 470px;
|
||||
margin: 0 auto;
|
||||
line-height: 150%;
|
||||
padding: 20px;
|
||||
z-index: 1;
|
||||
}}
|
||||
|
||||
h1 {{
|
||||
font-size: 2.5rem;
|
||||
color: #f7d066;
|
||||
margin-top: 50px;
|
||||
}}
|
||||
|
||||
p {{
|
||||
font-size: 1.2rem;
|
||||
margin-top: 20px;
|
||||
}}
|
||||
|
||||
span {{
|
||||
color: #f7467e;
|
||||
}}
|
||||
|
||||
@media (max-width: 767px) {{
|
||||
#content {{
|
||||
max-width: 100%;
|
||||
padding: 10px;
|
||||
}}
|
||||
}}
|
||||
</style>
|
||||
|
||||
<body>
|
||||
<div id="content">
|
||||
<h1>Happy Birthday, {self.name}!</h1>
|
||||
<p>Dear {self.name},<br>
|
||||
On this special day, I wish you all the very best, all the joy you can ever have, and may you be blessed
|
||||
abundantly today, tomorrow, and the days to come! May you have a fantastic birthday and many more to come...
|
||||
HAPPY BIRTHDAY!!!!<br>
|
||||
<span>With love, <a href="{self.tg_link}">{self.preview_name}</a></span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function launchConfetti() {{
|
||||
const duration = 2 * 1000;
|
||||
const end = Date.now() + duration;
|
||||
|
||||
(function frame() {{
|
||||
confetti({{
|
||||
particleCount: 5,
|
||||
angle: 60,
|
||||
spread: 55,
|
||||
origin: {{ x: 0 }},
|
||||
colors: ['#f7d066', '#f7467e', '#fff']
|
||||
}});
|
||||
confetti({{
|
||||
particleCount: 5,
|
||||
angle: 120,
|
||||
spread: 55,
|
||||
origin: {{ x: 1 }},
|
||||
colors: ['#f7d066', '#f7467e', '#fff']
|
||||
}});
|
||||
|
||||
if (Date.now() < end) {{
|
||||
requestAnimationFrame(frame);
|
||||
}}
|
||||
}})();
|
||||
}}
|
||||
|
||||
window.onload = launchConfetti;
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
"""
|
||||
|
||||
return web.Response(text=html_content, content_type="text/html")
|
||||
|
||||
async def open_tunnel(self, port):
|
||||
ssh_command = f"ssh -o StrictHostKeyChecking=no -R 80:localhost:{port} nokey@localhost.run"
|
||||
process = await asyncio.create_subprocess_shell(
|
||||
ssh_command,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
url = await self._extract_tunnel_url(process.stdout)
|
||||
self.url = url or f"https://localhost:{port}"
|
||||
return self.url
|
||||
|
||||
async def _extract_tunnel_url(self, stdout):
|
||||
event = asyncio.Event()
|
||||
url = None
|
||||
|
||||
async def read_output():
|
||||
nonlocal url
|
||||
while True:
|
||||
line = await stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
decoded_line = line.decode()
|
||||
match = re.search(r"tunneled.*?(https:\/\/.+)", decoded_line)
|
||||
if match:
|
||||
url = match[1]
|
||||
break
|
||||
event.set()
|
||||
|
||||
await read_output()
|
||||
await event.wait()
|
||||
return url
|
||||
|
||||
|
||||
@loader.tds
|
||||
class BirthdayWish(loader.Module):
|
||||
"""Share warmth with your loved ones and give them this website to make their birthdays even more special and joyful."""
|
||||
|
||||
strings = {
|
||||
"name": "BirthdayWish",
|
||||
"provide_name": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>Please provide a name</b>",
|
||||
"web_url": "<emoji document_id=5334643333488713810>🌐</emoji> <b>URL: {} | Expires in <code>{}</code> seconds</b>",
|
||||
"expired": "<emoji document_id=5981043230160981261>⏱</emoji> <b>Url Expired</b>",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"provide_name": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>Пожалуйста, укажите имя</b>",
|
||||
"web_url": "<emoji document_id=5334643333488713810>🌐</emoji> <b>URL: {} | Истекает через <code>{}</code> секунд</b>",
|
||||
"expired": "<emoji document_id=5981043230160981261>⏱</emoji> <b>Url истек</b>",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.wishes = {}
|
||||
|
||||
async def tunnel_handler(self, port):
|
||||
|
||||
creator = WebCreator(
|
||||
name=self.name, tg_link=self.tg_link, preview_name=self.preview_name
|
||||
)
|
||||
|
||||
runner = web.AppRunner(creator.app)
|
||||
await runner.setup()
|
||||
|
||||
global site
|
||||
site = web.TCPSite(runner, "127.0.0.1", port)
|
||||
await site.start()
|
||||
|
||||
url = await creator.open_tunnel(port)
|
||||
return url, runner
|
||||
|
||||
async def wishcmd(self, message):
|
||||
"""Create Birthday web wishes args: <name> <time:seconds default(20)>"""
|
||||
|
||||
args = utils.get_args_raw(message).split(" ")
|
||||
|
||||
if args[0] == "":
|
||||
return await utils.answer(message, self.strings("provide_name"))
|
||||
|
||||
text = args[0]
|
||||
|
||||
expiration_time = int(args[1]) if len(args) > 1 else 20
|
||||
|
||||
me = await message.client.get_me()
|
||||
|
||||
self.tg_link = f"https://t.me/{me.username}" or "https://t.me/Unknown"
|
||||
self.preview_name = me.first_name
|
||||
self.name = text
|
||||
|
||||
port = random.randint(1000, 9999)
|
||||
|
||||
url, runner = await self.tunnel_handler(port)
|
||||
await utils.answer(
|
||||
message, self.strings("web_url").format(url, expiration_time)
|
||||
)
|
||||
|
||||
await asyncio.sleep(expiration_time)
|
||||
|
||||
await site.stop()
|
||||
await runner.cleanup()
|
||||
|
||||
await utils.answer(message, self.strings("expired"))
|
||||
@@ -1,100 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta pic: https://te.legra.ph/file/7772a7dae6290f0a612a6.png
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Bull.jpg
|
||||
|
||||
import random
|
||||
from .. import loader, utils
|
||||
from ..inline.types import InlineCall
|
||||
from ..inline.types import InlineQuery
|
||||
|
||||
|
||||
|
||||
bullr = (
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ПИЗДАК В ТЕОЙ МАТРЕИ НА СВОЙ УЙ КАК МАКАРОНИНУ НАМОТАЛ БЛЯДЬ И НАЧАЛ РАСКРУЧИВАТЬ ЕЁ, ПОСЛЕ ЧЕГО ВЫКИНУЛ В КОСМОС, ЧТОБ ЕЁ ТАМ ИНОПЛАНЕТЯНЫ ХУЯМИ РВАЛИ?)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ТВОЮ МАТЬ ОТПРАВИЛ СО СВОЕГО ЪХУЯ В НЕБО, ЧТОБ ОНА СВОИМ ПИЗДАКОМ ПРИНИМАЛА МИТЕОРИТНУЮ АТАКУ?)",
|
||||
"ЕСЛИ ТЫ СЕЙЧАС ТАК И БУДЕШЬ ПРОДОЛЖАТЬ ПРОТИВОРЕЧИТЬ МОЕМУ ХУЮ, КАК ИМ КАК БЛЯДЬ НА НЛО ЗАХВОЧУ ТВОЁ ОЧКО И НАЧНУ ОПЫТЫ ПРОВОДИТЬ",
|
||||
"ТЫ ПОНИМАЕШЬЧ ТО ВТОЯ МАТЬ МОЙ ХУЙ ЗАВЕРНУЛА В ПАКЕТИК ПОТОМУ ЧТО У ЭТОЙ БОМЖИХИ НЕБЫЛО ДЕНЕГ НА ПРЕЗИКИ, И ПОКЕТИК ПОРВАЛСЯ, И РОДИЛОСЬ ТАКОЕ ХУЙЛО КАК ТЫ",
|
||||
"TЫ ПОНИМАЕШЬ ЧТО Я ТВОЮ МАТЬ СЛУЧАЙНО СВОИМ ХУЁМ СМЁЛ НАХУЙ СО СВОЕГО ПУТИ, И ОНА УЛЕТЕЛА НА РАДИУС ОБСТРЕЛА МОЕЙ ЗАЛУПЫ",
|
||||
"АМЕБА ЕБАНАЯ СУКА) МАМАШКУ ТВОЮ ДЫРЯВИЛ ЧЕТ ) НАХУЙ ТВОЯ МАМАША КРИЧИТ КОГДА Я НАЧИНАЮ ЕБАТЬ ЕЕ)",
|
||||
"АМЕБА ИЛИ ТЫ ОЛЕНЬ?) СЛЫШЬ ЕСЛИ ТЫ ПРОЛЬЕШЬ НА МОЙ ХУЙ СЛЕЗЫ , ТО ТЫ НЕ РАССЧИТЫВАЙ НА ТО , ЧТО ПОТОМ К ТЕБЕ ПРИДЕТ ФЕЯ И ПООБЕЩАЕТ ТЕБЕ ДОЛГУЮ И СЧАСТЛИВУЮ ЖИЗНЬ)",
|
||||
"ОЛЕНЬ ТЫ ЕБАНЫЙ) МАТЬ ТВОЮ ЕБУ ЧЕТ ) ДАВАЙ ТЫ ЩАС ВОЗЬМЕШЬ МОЙ ХУЙ КАК ПЕРО И СЛОВНО КАК ПИСАТЕЛЬ СЕРЕБРЯНОГО ВЕКА НАПИШЕШЬ КАКОЙ НИБУДЬ РОМАН КОТОРЫЙ БУДЕТ ПО РАЗМЕРУ ПРИМЕРНО КАК МАСТЕР И МАРГАРИТА )",
|
||||
"твоя мамка блядоебская кобыла и лезби",
|
||||
"у тебя мать сраная шлюха",
|
||||
"Я ТОВЮ МАМАШУ СВОИМ ХУЁМ РАСПЛЮЩИЛ, И ТЕПЕРЬ ОНА КАК ХОЯЧАЮ ПРУЖИТНКА БЛЯДЬ, ОТ СЕБЯ ВСЕ ХУИ ОТТАЛКИВАЕТ КРОМЕ МОЕГО, ДЛЯ МОЕГО ХУЯ ВСЕГДА ОТКРЫТ ДОСТУП В ЕЁ ПИЗДАК",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ТВОЮ МАТЬ БЛЯДЬ НАТЯНУЛ ПИЗДАКОМ НА ВЫСОКОВОЛЬТНУЮ ЭЛЕКТРО ВЫШКУ, И ОНА В СЕБЯ НАХУЙ ВЕСЬ ТОК ВТЯНУЛА, ТЕПЕРЬ ОНА БЛЯДЬ КАК ЭЛЕКТРО",
|
||||
"Я КОГДА ВЫЕБАЛ ТВОЮ МАТЬ Я СВОЙ ХУЙ ПОСТАВИЛ К ЕЁ УХУ, ЧТОБ ОНА СЛЫШАЛА ПРИБОЯ СПЕРМЫ, А ПОТОМ ОНА ШИРОКО РАСКРЫЛА РОТ МЫ В ЕЁ ЕБЛЯТНИКЕ УСТРОИЛИ ОКЕАН",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я В ПИЗДАК ТВОЕЙ МАТРЕИ СВОЙ ХУЙ ЗАСУНУ КАК БЛЯДЬ ШТТЕККЕР И ЕЁ ЗАРЯД ПОВЫСИЛСЯ КАК ОТ ЭНЕРГЕТИКА)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО ТВОЯ МАТЬ НА МОЁМ ХУЮ УСТРОИЛА БЛЯДЬ ТАНЦПОЛ, И НАЧАЛА СВОИМ ПОДРУГАМ ПРОДАВАТЬ НА НЕГО БИЛЕТЫ",
|
||||
" ЕСЛИ ТЫ СЕЙЧАС НЕ НАЧНЁШЬ МНЕ ОТВЕЧАТЬ, Я ТЕБЕ НАХУЙ ХЁМ ПАЛЬЦЫ ПЕРЕЛОМАЮ, ОБРАЗИНА ТЫ ЕБАНАЯ)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО ВТОЯ МАМАШКА КАШЁЛКА ЕБАНАЯ, НА МОЙ ХУЙ ВЕШАЕТСЯ СВОИМ ПИЗДАКОМ КАК МАГНИТИК НА ХОЛОДИЛЬНИК, ПИДОПР ТЫ БЛЯДЬ ЕБАНЫЙ",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ТВОЕЙ МАТЕРИ ГОЛОВУ ХУЁМ КАК КОПЬЁМ ПРОБИЛ БЛЯДЬ И ЕЁ КУРИНЫЙ МОЗГ УМЕР НАХУЙ)) ИЗ-ЗА ЭТОГО ОНА ТЕБЯ ДАЖЕ И НЕ ВСПОМИНАЕТ)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ВЫСТАВИЛ СВОЙ ХУЙ НА АВИТО, А ТВОЯ МАТЬ ПРОШЛА БЛЯДЬ БЕЗ ОЧЕРЕДИ И ККУПИЛА ЕГО, ОТДАВ СВОЮ ГНИЛУЮ ПОЧКУ?)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО ТВОЯ МАТЬ МОЙ ХУЙ НА НОЧЬ СЕБЕ В ПИЗДАК СУЁТ КАК ОБОГРЕВАТЕЛЬ НАХУЙ?)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ПОКА ЧТО ЕБАЛ ТВОЮ МАМАШУ В СРАКУ, У НЕЁ ТАМ ЗАСОР СПЕРМЫ БЛЯДЬ ОБРАЗОВАЛСЯ И ЗАСОХ, ТЕПЕРЬ ОНА СРАТЬ НОРМАЛЬНО НЕ МОЖЕТ, ИДИ НАХУЙ СПАСАЙ ЭТУ ШЛЮХУ",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО КОГДА Я ЕБУ ТВОЮ МАТЬ ЧТОБЫ ОНА НЕ ОРАЛА Я ЕЙ КЛЯП В РОТ СУЮ, НО ОДИН РАЗ СЛУЧИЛОСЬ ТАКОЕ, ЧТО КОГДА Я СВОИМ ХУЁМ ДАЛ ЕЙ ПО ПИЗДЕ ОНА ЭТОТ КЛЯП ПРОГЛАТИЛА, И НАЧАЛА ЗАДЫХАТЬСЯ, СПАСИ СВОЮ ШЛЮХА МАМКУ)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО МОЙ ХУЙ ВЗЛАМЫВАЕТ ОЧКО ТВОЕЙ МАТЕРИ КАК СЕЙФ НАХУЙ, И ОТ ТУДА НАЧИНАЮТ ВАЛИТЬСЯ САМОРОДКИ СПЕРМЫ?)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я В ПИЗДАКЕ ТВОЕЙ МАТЕРИ УСТРОИЛ ИЗВЕРЖЕНИЕ СВОЕГО ХУЯ НАХУЙ?",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ХУЁМ НАЧАЛ МОТАТЬ ПЕРЕД ТВОИМ ЕБАЛОИ И ТЕБЯ СЛУЧАЙНО НАХУЙ ЗАГИПНОТЕЗИРОВАЛ, И ТЫ ОБ ХУИ СТАЛ ГОЛОВОЙ БИТЬСЯ?)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО КОГДА Я ТВОЮ МАТЬ ОНА КАК ШЛЮХА ЛОЖИТСЯ НА СПИНКУ И НАЧИНАЕТ ПОСАСЫВАТЬ МОИ ЯЙЦА",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я В ПИЗДАКЕ ТВОЕЙ МАТЕРИ ИЗ ЕЁ КЛИТОРНЫЙ СТЕН ВЫРЕЗАЮ РАКЕТНИЦУ СВОИМ ХУЁМ?",
|
||||
"Я СЕЙЧАС СВОЕЙ СПЕРМОЙ ОБОЛЬЮ ТВОЙ ПИЗДАК КАК КЕРАСИНОМ, И ПУЩУ НА НЕГО ИСКРУ, ДОБЫТАЯ КОТОРАЯ БУДЕТ О ТВОИ ГНИЛЫЕ ЗУБКИ, И ТЫ СГОРИШЬ НАХУЙ)",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО ТЫ ОТ МОЕЙ ЗАЛУПЫ ПРЯЧШЬСЯ В ПИЗДАКЕ СВОЕЙ МАТЕРИ КАК НАХУЙ В БУНКЕРЕ, А Я СВОИМ ХУЁМ ЕГО НА СКВОЗЬ ПРОШИЛ И ТЕБЕ В ЕБАЛО ПОПАЛ)) ",
|
||||
"ТЫ ПОНИМАЕШЬ ЧТО Я ХУЁМ СТАЛ КАТАЛИЗИРОВАТЬ ПИЗДАК ТВОЕЙ МАТЕРИ НА РАЗДВИЖЕНИЕ ЕЁ ЖИРНЫХ НОГ?)",
|
||||
)
|
||||
|
||||
def bullme():
|
||||
iwfy = random.choice(bullr)
|
||||
return iwfy
|
||||
|
||||
@loader.tds
|
||||
class BullMod(loader.Module):
|
||||
"""Bull пиз#а собеседнику"""
|
||||
|
||||
strings = {"name": "BullMod"}
|
||||
|
||||
@loader.inline_everyone
|
||||
async def bull_inline_handler(self, query: InlineQuery):
|
||||
"""Забулить кого-то жесткими матами про мать"""
|
||||
aoa = bullme()
|
||||
|
||||
btn_a = [{"text": "🌀 Random", "callback": self.bulls}]
|
||||
|
||||
return {
|
||||
"title": "Пошутить про маму",
|
||||
"thumb": "https://te.legra.ph/file/b2a6c8d20e0034a534ac4.jpg",
|
||||
"description": "Отправить...",
|
||||
"message": f"<i>{aoa}</i>",
|
||||
"reply_markup": btn_a,
|
||||
}
|
||||
|
||||
async def bullcmd(self, message):
|
||||
"""Забулить кого-то жесткими матами про мать"""
|
||||
aoa = bullme()
|
||||
await utils.answer(message, aoa)
|
||||
|
||||
async def bullicmd(self, message):
|
||||
"""Забулить кого-то жесткими матами про мать (inline)"""
|
||||
aoa = bullme()
|
||||
await self.inline.form(
|
||||
message=message,
|
||||
text=aoa,
|
||||
reply_markup=[
|
||||
[{"text": "🌀 Random", "callback": self.bulls}],
|
||||
]
|
||||
)
|
||||
|
||||
async def bulls(self, call: InlineCall):
|
||||
aoa = bullme()
|
||||
await call.edit(
|
||||
text=aoa,
|
||||
reply_markup=[
|
||||
[{"text": "🌀 Random", "callback": self.bulls}],
|
||||
]
|
||||
)
|
||||
@@ -1,158 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta pic: https://te.legra.ph/file/388e1b26a46a8c439e479.png
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Createlinks.jpg
|
||||
|
||||
|
||||
from .. import loader, utils, security
|
||||
|
||||
|
||||
|
||||
@loader.tds
|
||||
class AmorelinksMod(loader.Module):
|
||||
"""Create links"""
|
||||
|
||||
strings = {
|
||||
"name": "AmoreLinks",
|
||||
"youtube": "🫂 <b>YouTube link special for you.</b>\n\n",
|
||||
"google": "🫂 <b>Google link special for you.</b>\n\n",
|
||||
"github": "🫂 <b>Github link special for you.</b>\n\n",
|
||||
"pornhub": "🫂 <b>Pornhub link special for you.</b>\n\n",
|
||||
"telegram": "🫂 <b>Telegram link special for you.</b>\n\n",
|
||||
"4pda": "🫂 <b>4pda link special for you.</b>\n\n",
|
||||
|
||||
}
|
||||
|
||||
async def ytcmd(self, message):
|
||||
"""<text> create YouTube link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("youtube", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "♨️ Link", "url": f"https://m.youtube.com/results?sp=mAEA&search_query={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
|
||||
|
||||
async def gugcmd(self, message):
|
||||
"""<text> create Google link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("google", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "🛰 Link", "url": f"https://www.google.com/search?q={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
|
||||
async def ghcmd(self, message):
|
||||
"""<text> create Github link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("github", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "🛰 Link", "url": f"https://github.com/search?q={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
|
||||
async def phcmd(self, message):
|
||||
"""<text> create PornHub link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("pornhub", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "🛰 Link", "url": f"https://rt.pornhub.com/video/search?search={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
|
||||
async def tgcmd(self, message):
|
||||
"""<text> create Telegram link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("telegram", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "🛰 Link", "url": f"tg://search?query={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
|
||||
async def pdacmd(self, message):
|
||||
"""<text> create 4pda link"""
|
||||
text = utils.get_args_raw(message)
|
||||
s = f"<b>✏ Input word: <code>{text}</code></b>"
|
||||
if await self.allmodules.check_security(
|
||||
message,
|
||||
security.OWNER | security.SUDO,
|
||||
):
|
||||
|
||||
try:
|
||||
await self.inline.form(
|
||||
self.strings("4pda", message) + s,
|
||||
reply_markup=[
|
||||
[{"text": "🛰 Link", "url": f"https://4pda.to/forum/index.php?act=search&source=all&forums=316&subforums=1&query={text}"}],
|
||||
[{"text": "🔻 Close", "action": f"close"}],
|
||||
],
|
||||
message=message,
|
||||
)
|
||||
except Exception:
|
||||
await utils.answer(message, self.strings("join", message))
|
||||
@@ -1,73 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/DTWR.jpg
|
||||
|
||||
from .. import loader, utils
|
||||
from telethon.tl.types import Message
|
||||
|
||||
|
||||
@loader.tds
|
||||
class DTWRMod(loader.Module):
|
||||
"""Module Don't tag wihout reason"""
|
||||
|
||||
strings = {
|
||||
"name": "DTWR",
|
||||
"text": "Your custom text",
|
||||
"username": "Input you username without '@'",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"text": "Кастомный текст",
|
||||
"username": "Введи свой юзернэйм без '@'",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"text": "Kastom text",
|
||||
"username": "Usernameingizni kiriting, '@' siz"
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"Username",
|
||||
"username",
|
||||
doc=lambda: self.strings("username"),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"custom_text",
|
||||
"😫 Please don't tag me without reason",
|
||||
doc=lambda: self.strings("text"),
|
||||
),
|
||||
)
|
||||
|
||||
@loader.command(ru_docs="Конфиг этого модуля")
|
||||
async def cfgdtwrcmd(self, message):
|
||||
"""This module config"""
|
||||
name = self.strings("name")
|
||||
await self.allmodules.commands["config"](
|
||||
await utils.answer(message, f"{self.get_prefix()}config {name}")
|
||||
)
|
||||
|
||||
@loader.tag("only_messages", "only_groups", "in")
|
||||
async def watcher(self, message: Message):
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
|
||||
tag = self.config['Username']
|
||||
if tag.startswith('@') is False:
|
||||
tag = f"@{tag}"
|
||||
|
||||
if reply:
|
||||
return False
|
||||
if message.text.lower() == tag:
|
||||
await message.reply(self.config["custom_text"])
|
||||
await self._client.send_read_acknowledge(
|
||||
message.chat_id,
|
||||
clear_mentions=True,
|
||||
)
|
||||
@@ -1,48 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Facts.jpg
|
||||
# channel @facti_p
|
||||
|
||||
from .. import loader, utils
|
||||
from telethon import functions
|
||||
from asyncio import sleep
|
||||
import random
|
||||
import datetime
|
||||
chat = "@faktiru"
|
||||
|
||||
|
||||
class FactsMod(loader.Module):
|
||||
"""More Interesting Facts"""
|
||||
|
||||
strings = {
|
||||
"name": "Facts",
|
||||
"wait": "<emoji document_id=5472146462362048818>💡</emoji> Searching..."
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"wait": "<emoji document_id=5472146462362048818>💡</emoji> Поиск..."
|
||||
}
|
||||
|
||||
@loader.command(ru_docs="Интересные Факты")
|
||||
async def afactscmd(self, message):
|
||||
"""Intersting Facts"""
|
||||
reply = await message.get_reply_message()
|
||||
await utils.answer(message, self.strings["wait"])
|
||||
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 sleep(0.30)
|
||||
await message.delete()
|
||||
await message.client.send_message(
|
||||
message.to_id,
|
||||
result.messages[0],
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
@@ -1,67 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/Figlet.jpg?raw=true
|
||||
|
||||
|
||||
|
||||
import pyfiglet
|
||||
import functools
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
class Figlet(loader.Module):
|
||||
"""Creates Figlet Text"""
|
||||
|
||||
strings = {"name": "Figlet"}
|
||||
style_to_font = {
|
||||
"slant": "slant",
|
||||
"3d": "3-d",
|
||||
"5line": "5lineoblique",
|
||||
"alpha": "alphabet",
|
||||
"banner": "banner3-D",
|
||||
"doh": "doh",
|
||||
"iso": "isometric1",
|
||||
"letter": "letters",
|
||||
"allig": "alligator",
|
||||
"dotm": "dotmatrix",
|
||||
"bubble": "bubble",
|
||||
"bulb": "bulbhead",
|
||||
"digi": "digital"
|
||||
}
|
||||
|
||||
@loader.command()
|
||||
async def listfig(self, message):
|
||||
"""List of figlet styles"""
|
||||
keys_list = " , ".join(list(self.style_to_font.keys()))
|
||||
await utils.answer(message, f"🚩 Available styles: {keys_list}")
|
||||
|
||||
@loader.command()
|
||||
async def figlet(self, message):
|
||||
"""Create figlet text, <style> | <args>"""
|
||||
args = utils.get_args_raw(message).split(" | ")
|
||||
if len(args) < 2:
|
||||
await utils.answer(message, "Not enough arguments")
|
||||
return
|
||||
|
||||
font = self.style_to_font.get(args[0], None)
|
||||
if font is None:
|
||||
await utils.answer(message, "There is no such style")
|
||||
return
|
||||
|
||||
if not args[1]:
|
||||
await utils.answer(message, "Text argument is empty")
|
||||
return
|
||||
|
||||
result = await self.figlet_format_cached(args[1], font)
|
||||
await utils.answer(message, f"<code>{result}<code>")
|
||||
|
||||
@staticmethod
|
||||
@functools.lru_cache(maxsize=None)
|
||||
async def figlet_format_cached(text, font):
|
||||
return pyfiglet.figlet_format(text, font=font)
|
||||
@@ -1,48 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/fileext.jpg
|
||||
|
||||
|
||||
from .. import loader, utils
|
||||
from telethon.tl.types import Message
|
||||
from bs4 import BeautifulSoup
|
||||
import requests
|
||||
|
||||
|
||||
async def search_extention(ext):
|
||||
sample_url = "https://www.fileext.com/file-extension/{}.html"
|
||||
response_api = requests.get(sample_url.format(ext))
|
||||
if not response_api.ok:
|
||||
return (
|
||||
f"Error fetching details for {ext}. Status code: {response_api.status_code}"
|
||||
)
|
||||
soup = BeautifulSoup(response_api.content, "html.parser")
|
||||
return soup.find_all("td", {"colspan": "3"})[-1].text
|
||||
|
||||
|
||||
@loader.tds
|
||||
class FileExtMod(loader.Module):
|
||||
"""Get file extention details"""
|
||||
|
||||
strings = {
|
||||
"name": "FileExt",
|
||||
"no_args": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>No args passed</b>",
|
||||
"response": "<emoji document_id=5467732133629926938>🔍</emoji> <b>File Extension</b>: <code>{}</code>\n<emoji document_id=5467919175160705819>🔍</emoji> <b>Description</b>: <code>{}</code>",
|
||||
}
|
||||
|
||||
@loader.command()
|
||||
async def fileext(self, message: Message):
|
||||
"""Get file extention details"""
|
||||
if args := utils.get_args_raw(message):
|
||||
await utils.answer(
|
||||
message,
|
||||
self.strings("response").format(args, await search_extention(args)),
|
||||
)
|
||||
else:
|
||||
await utils.answer(message, self.strings("no_args"))
|
||||
@@ -1,37 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/fragment_checker.jpg?raw=true
|
||||
# requires: bs4
|
||||
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from .. import loader, utils
|
||||
|
||||
class Fragment(loader.Module):
|
||||
"""Show how much is the username in the Fragment.com"""
|
||||
|
||||
strings = {"name": "FragmentChecker"}
|
||||
|
||||
@loader.command()
|
||||
async def fcheck(self, message):
|
||||
"""check username in the Fragment.com"""
|
||||
args = utils.get_args_raw(message)
|
||||
response = requests.get(f"https://fragment.com/username/{args}")
|
||||
|
||||
if response.status_code == 200:
|
||||
soup = BeautifulSoup(response.content, "html.parser")
|
||||
elements = soup.select(".table-cell-value.tm-value.icon-before.icon-ton")
|
||||
if elements:
|
||||
text = elements[0].text.strip()
|
||||
await utils.answer(message, f"<emoji document_id=5215219508670638513>💎</emoji> <b>Username Found!</b>\n<emoji document_id=5467626799556992380>✈️</emoji> <b>Username:</b> <code>{args}</code>\n<emoji document_id=5460720028288557729>🪙</emoji> <b>Cost:</b> <code>{text}</code> TON")
|
||||
if not elements:
|
||||
await utils.answer(message, f"<emoji document_id=5212926868012935693>❌</emoji> <b>Username <code>{args}</code> not found!</b>")
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
autoprofile
|
||||
animevoices
|
||||
aeconv
|
||||
amethyste
|
||||
activity
|
||||
phsticker
|
||||
amoreinfo
|
||||
abstract
|
||||
dtwr
|
||||
bull
|
||||
meowvoices
|
||||
mydiary
|
||||
createlinks
|
||||
imgbb
|
||||
instsave
|
||||
telegraphup
|
||||
inlineping
|
||||
poststealer
|
||||
searchpic
|
||||
funquotes
|
||||
facts
|
||||
hacker
|
||||
premiuminfo
|
||||
cartoonimg
|
||||
trigger
|
||||
recognition
|
||||
universaltime
|
||||
nytimer
|
||||
figlet
|
||||
fileext
|
||||
my_usernames
|
||||
fragment_checker
|
||||
alarm
|
||||
leta
|
||||
speech
|
||||
jutsu
|
||||
usernamestealer
|
||||
lexiwiz
|
||||
birthdaywish
|
||||
wakatime
|
||||
@@ -1,91 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Funquotes.jpg
|
||||
__version__ = (1, 0, 0)
|
||||
|
||||
from telethon.tl.types import Message
|
||||
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
@loader.tds
|
||||
class InlineFunMod(loader.Module):
|
||||
"""Create Fun quotes"""
|
||||
|
||||
strings = {
|
||||
"name": "FunQuotes",
|
||||
"where_text": "<emoji document_id='6041914500272098262'>🚫</emoji> <b>Provide a text to create sticker with</b>",
|
||||
"processing": (
|
||||
"<emoji document_id='6318766236746384900'>🕔</emoji> <b>Processing...</b>"
|
||||
),
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"where_text": "<emoji document_id='6041914500272098262'>🚫</emoji> <b>Укажи текст для создания стикера</b>",
|
||||
"processing": (
|
||||
"<emoji document_id='6318766236746384900'>🕔</emoji> <b>Обработка...</b>"
|
||||
),
|
||||
}
|
||||
|
||||
async def glaxcmd(self, message: Message):
|
||||
"""<text> - Create Google search quote"""
|
||||
text = utils.get_args_raw(message)
|
||||
if not text:
|
||||
await message.edit(self.strings("where_text"))
|
||||
return
|
||||
|
||||
await message.edit(self.strings("processing"))
|
||||
|
||||
try:
|
||||
query = await self._client.inline_query("@googlaxbot", text)
|
||||
await message.respond(file=query[0].document)
|
||||
except Exception as e:
|
||||
await utils.answer(message, str(e))
|
||||
return
|
||||
|
||||
if message.out:
|
||||
await message.delete()
|
||||
|
||||
async def twitcmd(self, message: Message):
|
||||
"""<text> - Create Twitter message quote"""
|
||||
text = utils.get_args_raw(message)
|
||||
if not text:
|
||||
await message.edit(self.strings("where_text"))
|
||||
return
|
||||
|
||||
await message.edit(self.strings("processing"))
|
||||
|
||||
try:
|
||||
query = await self._client.inline_query("@TwitterStatusBot", text)
|
||||
await message.respond(file=query[0].document)
|
||||
except Exception as e:
|
||||
await utils.answer(message, str(e))
|
||||
return
|
||||
|
||||
if message.out:
|
||||
await message.delete()
|
||||
|
||||
async def frogcmd(self, message: Message):
|
||||
"""<text> - Create Frog text quote"""
|
||||
text = utils.get_args_raw(message)
|
||||
if not text:
|
||||
await message.edit(self.strings("where_text"))
|
||||
return
|
||||
|
||||
await message.edit(self.strings("processing"))
|
||||
|
||||
try:
|
||||
query = await self._client.inline_query("@honka_says_bot", text + ".")
|
||||
await message.respond(file=query[0].document)
|
||||
except Exception as e:
|
||||
await utils.answer(message, str(e))
|
||||
return
|
||||
|
||||
if message.out:
|
||||
await message.delete()
|
||||
@@ -1,69 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Hacker.jpg
|
||||
__version__ = (1, 0, 0)
|
||||
|
||||
|
||||
from .. import loader, utils
|
||||
import requests
|
||||
from PIL import Image,ImageFont,ImageDraw
|
||||
import io
|
||||
from textwrap import wrap
|
||||
|
||||
@loader.tds
|
||||
class HackerMod(loader.Module):
|
||||
"""Create hacker message stickers"""
|
||||
strings = {
|
||||
'name': 'Hacker',
|
||||
'what': 'Reply to text or write text <emoji document_id="5467928559664242360">❗️</emoji>',
|
||||
'processing': 'Processing <emoji document_id="6334710044407368265">🚀</emoji>'
|
||||
}
|
||||
|
||||
@loader.owner
|
||||
async def hackercmd(self, message):
|
||||
"""Reply to text or write text"""
|
||||
|
||||
ufr = requests.get("https://0x0.st/opzq.ttf")
|
||||
f = ufr.content
|
||||
|
||||
reply = await message.get_reply_message()
|
||||
args = utils.get_args_raw(message)
|
||||
if not args:
|
||||
if not reply:
|
||||
await message.edit(self.strings('what', message))
|
||||
return
|
||||
else:
|
||||
txt = reply.raw_text
|
||||
else:
|
||||
txt = utils.get_args_raw(message)
|
||||
await message.edit(self.strings("processing"))
|
||||
pic = requests.get("https://0x0.st/opzN.jpg")
|
||||
pic.raw.decode_content = True
|
||||
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
|
||||
|
||||
W, H = img.size
|
||||
txt = txt.replace("\n", "𓃐")
|
||||
text = "\n".join(wrap(txt, 19))
|
||||
t = text + "\n"
|
||||
t = t.replace("𓃐","\n")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
|
||||
w, h = draw.multiline_textsize(t, font=font)
|
||||
imtext = Image.new("RGBA", (w+10, h+10), (255, 250, 250, 1))
|
||||
draw = ImageDraw.Draw(imtext)
|
||||
draw.multiline_text((10, 10),t,(255, 255, 255),font=font, align='left')
|
||||
imtext.thumbnail((339, 181))
|
||||
w, h = 339, 181
|
||||
img.paste(imtext, (10,10), imtext)
|
||||
out = io.BytesIO()
|
||||
out.name = "amore.webp"
|
||||
img.save(out)
|
||||
out.seek(0)
|
||||
await message.client.send_file(message.to_id, out, reply_to=reply)
|
||||
await message.delete()
|
||||
@@ -1,129 +0,0 @@
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠛⠛
|
||||
# ⣶⣦⣤⣤⣤⣤⣤⣤⣬⣭⣭⣍⣉⡙⠛⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⣋⣩⣭⣥⣤⣴⣶⣶⣶⣶⣶⣶⣶⣶⣶
|
||||
# ⣆⠀⠀⠀⢡⠁⠀⡀⠀⢸⠟⠻⣯⠙⠛⠷⣶⣬⡙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢉⣥⣶⡟⠻⣙⡉⠀⢰⡆⠀⠀⣡⠀⣧⠀⠀⠀⢨
|
||||
# ⠻⣦⠀⠀⠈⣇⣀⣧⣴⣿⣶⣶⣿⣷⠀⢀⡇⠉⠻⢶⣌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⡶⠟⠉⠀⢣⠀⣿⠷⠀⠀⠀⠀⣿⡷⢀⠇⠀⠀⢠⣿
|
||||
# ⣦⡈⢧⡀⠀⠘⢮⡙⠛⠉⠀⠄⠙⢿⣀⠞⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠈⠳⣄⠉⠓⠒⠚⠋⢀⡠⠋⠀⢀⣴⣏⣿
|
||||
# ⣿⣿⣿⣛⣦⣀⠀⠙⠓⠦⠤⣤⠔⠛⠁⠀⠀⠀⠀⠀⢀⣀⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣤⣤⣤⣀⣀⣀⣀⢙⢓⣒⡒⠚⠋⢠⣤⢶⣟⣽⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣷⣦⠀⠀⣴⣿⣷⣶⣶⣶⣾⡖⢰⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣾⣿⣿⣶⣾⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣿⣿⣿⣿⣿⣿⣿⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⡏⠀⢸⣿⣿⣿⣿⣿⣿⣿⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣷⠀⢸⣿⣿⣿⣿⣿⣿⣿⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# https://t.me/amorescam
|
||||
|
||||
#
|
||||
# █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
|
||||
# █▀█ █ █ █ █▀█ █▀▄ █
|
||||
# © Copyright 2022
|
||||
#
|
||||
# https://t.me/hikariatama
|
||||
#
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
|
||||
# meta developer: @amoremods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Imgbb.jpg
|
||||
|
||||
|
||||
import imghdr
|
||||
import io
|
||||
import random
|
||||
import re
|
||||
|
||||
import requests
|
||||
from telethon.errors.rpcerrorlist import YouBlockedUserError
|
||||
from telethon.tl.types import Message
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
@loader.tds
|
||||
class ImgbbUploader(loader.Module):
|
||||
"""Upload you photo/video/gif to https://ibb.co"""
|
||||
|
||||
strings = {
|
||||
"name": "Imgbb",
|
||||
"noargs": "🚫 <b>File not specified</b>",
|
||||
"err": "🚫 <b>Error uploading</b>",
|
||||
"ban": "🎒 @Imgbb_com_bot pls unblock this bot",
|
||||
"not_an_image": "🚫 <b>This platform only supports images </b>",
|
||||
"uploading": "📤 <b>Uploading...</b>",
|
||||
}
|
||||
|
||||
async def get_media(self, message: Message):
|
||||
reply = await message.get_reply_message()
|
||||
m = None
|
||||
if reply and reply.media:
|
||||
m = reply
|
||||
elif message.media:
|
||||
m = message
|
||||
elif not reply:
|
||||
await utils.answer(message, self.strings("noargs"))
|
||||
return False
|
||||
|
||||
if not m:
|
||||
file = io.BytesIO(bytes(reply.raw_text, "utf-8"))
|
||||
file.name = "file.txt"
|
||||
else:
|
||||
file = io.BytesIO(await self._client.download_media(m, bytes))
|
||||
file.name = (
|
||||
m.file.name
|
||||
or (
|
||||
"".join(
|
||||
[
|
||||
random.choice("abcdefghijklmnopqrstuvwxyz1234567890")
|
||||
for _ in range(16)
|
||||
]
|
||||
)
|
||||
)
|
||||
+ m.file.ext
|
||||
)
|
||||
|
||||
return file
|
||||
|
||||
async def get_image(self, message: Message):
|
||||
file = await self.get_media(message)
|
||||
if not file:
|
||||
return False
|
||||
|
||||
if imghdr.what(file) not in ["gif", "png", "jpg", "jpeg", "tiff", "bmp"]:
|
||||
await utils.answer(message, self.strings("not_an_image"))
|
||||
return False
|
||||
|
||||
return file
|
||||
|
||||
async def imgbbcmd(self, message: Message):
|
||||
"""imgbb uploader"""
|
||||
message = await utils.answer(message, self.strings("uploading"))
|
||||
file = await self.get_image(message)
|
||||
if not file:
|
||||
return
|
||||
|
||||
chat = "@Imgbb_com_bot"
|
||||
|
||||
async with self._client.conversation(chat) as conv:
|
||||
try:
|
||||
m = await conv.send_message(file=file)
|
||||
response = await conv.get_response()
|
||||
except YouBlockedUserError:
|
||||
await utils.answer(message, self.strings("ban"))
|
||||
return
|
||||
|
||||
await m.delete()
|
||||
await response.delete()
|
||||
|
||||
try:
|
||||
url = (
|
||||
re.search(
|
||||
r'<meta property="og:image" data-react-helmet="true"'
|
||||
r' content="(.*?)"',
|
||||
(await utils.run_sync(requests.get, response.raw_text)).text,
|
||||
)
|
||||
.group(1)
|
||||
.split("?")[0]
|
||||
)
|
||||
except Exception:
|
||||
url = response.raw_text
|
||||
await utils.answer(message, f"😸 Your file uploaded: <code>{url}</code>")
|
||||
@@ -1,83 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Inlineping.jpg
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from telethon.tl.types import Message
|
||||
|
||||
from .. import loader, utils
|
||||
from ..inline.types import InlineCall, InlineQuery
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@loader.tds
|
||||
class PingerMod(loader.Module):
|
||||
"""Inline Pinger For Test"""
|
||||
|
||||
strings = {
|
||||
"name": "InlinePing",
|
||||
"results_ping": "✨ <b>Telegram ping:</b> <code>{}</code> <b>ms</b>"
|
||||
}
|
||||
|
||||
strings_ru = {"results_ping": "✨ <b>Телеграм пинг:</b> <code>{}</code> <b>ms</b>"}
|
||||
|
||||
strings_uz = {"results_ping": "✨ <b>Telegram ping:</b> <code>{}</code> <b>ms</b>"}
|
||||
|
||||
strings_de = {"results_ping": "✨ <b>Telegramm Ping:</b> <code>{}</code> <b>ms</b>"}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
strings_ru = {"results_ping": "✨ <b>Скорость отклика Telegram:</b> <code>{}</code> <b>ms</b>"}
|
||||
|
||||
@loader.command(ru_doc="Проверить скорость отклика юзербота")
|
||||
async def iping(self, message: Message):
|
||||
"""Test your userbot ping"""
|
||||
start = time.perf_counter_ns()
|
||||
ping = self.strings("results_ping").format(
|
||||
round((time.perf_counter_ns() - start) / 10**3, 3),
|
||||
)
|
||||
|
||||
await self.inline.form(
|
||||
ping,
|
||||
reply_markup=[[{"text": "⏱️ PePing", "callback": self.ladno}]],
|
||||
message=message,
|
||||
)
|
||||
|
||||
async def ladno(self, call: InlineCall):
|
||||
start = time.perf_counter_ns()
|
||||
ping = self.strings("results_ping").format(
|
||||
round((time.perf_counter_ns() - start) / 10**3, 3),
|
||||
)
|
||||
await call.edit(
|
||||
ping,
|
||||
reply_markup=[[{"text": "⏱️ PePing", "callback": self.ladno,}],]
|
||||
)
|
||||
|
||||
async def ping_inline_handler(self, query: InlineQuery):
|
||||
"""Test your userbot ping"""
|
||||
start = time.perf_counter_ns()
|
||||
ping = self.strings("results_ping").format(
|
||||
round((time.perf_counter_ns() - start) / 10**3, 3),
|
||||
)
|
||||
button = [{
|
||||
"text": "⏱️ PePing",
|
||||
"callback": self.ladno
|
||||
}]
|
||||
return {
|
||||
"title": "Ping",
|
||||
"description": "Tap here",
|
||||
"thumb": "https://te.legra.ph/file/5d8c7f1960a3e126d916a.jpg",
|
||||
"message": ping,
|
||||
"reply_markup": button,
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta pic: https://te.legra.ph/file/0251f5d602a8f32cd7368.png
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Instsave.jpg
|
||||
__version__ = (1, 0, 0)
|
||||
|
||||
from .. import utils, loader
|
||||
|
||||
chat = "@SaveAsBot"
|
||||
|
||||
|
||||
class InstagramMod(loader.Module):
|
||||
"""Download video from instagram without watermark"""
|
||||
|
||||
strings = {
|
||||
"name": "InstSave",
|
||||
"processing": (
|
||||
"<emoji document_id='6318766236746384900'>🕔</emoji> <b>Processing...</b>"
|
||||
),
|
||||
"mods": (
|
||||
"<b>Successfuly downloaded</b> <emoji document_id='6320882302708614449'>🚀</emoji></b>"
|
||||
),
|
||||
}
|
||||
|
||||
@loader.group_member
|
||||
@loader.command(ru_doc="<линк> - Скачать видео из инстаграм")
|
||||
async def instascmd(self, message):
|
||||
"""instagram video/reels/photo url"""
|
||||
text = utils.get_args_raw(message)
|
||||
message = await utils.answer(message, self.strings("processing"))
|
||||
async with self._client.conversation(chat) as conv:
|
||||
msgs = []
|
||||
msgs += [await conv.send_message("/start")]
|
||||
msgs += [await conv.get_response()]
|
||||
msgs += [await conv.send_message(text)]
|
||||
m = await conv.get_response()
|
||||
|
||||
await self._client.send_file(
|
||||
message.peer_id,
|
||||
m.media,
|
||||
caption=self.strings("mods"),
|
||||
reply_to=message.reply_to_msg_id,
|
||||
)
|
||||
|
||||
for msg in msgs + [m]:
|
||||
await msg.delete()
|
||||
|
||||
if message.out:
|
||||
await message.delete()
|
||||
|
||||
await self.client.delete_dialog(chat)
|
||||
@@ -1,355 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# requires: bs4 cloudscraper loguru tqdm lxml
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
|
||||
import string
|
||||
import random
|
||||
import logging
|
||||
|
||||
from tqdm import tqdm
|
||||
from dataclasses import dataclass
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from cloudscraper import create_scraper, CloudScraper
|
||||
from telethon.tl.types import DocumentAttributeVideo
|
||||
|
||||
from aiogram.types import CallbackQuery
|
||||
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/537.36",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Season:
|
||||
title: str
|
||||
episodes_urls: list[str]
|
||||
|
||||
|
||||
def download_video(url: str, path, scraper: CloudScraper):
|
||||
with scraper.get(url, stream=True) as r:
|
||||
total_length = int(r.headers.get("Content-Length"))
|
||||
with tqdm.wrapattr(r.raw, "read", total=total_length, desc="") as raw:
|
||||
with open(path, "wb") as file:
|
||||
shutil.copyfileobj(raw, file)
|
||||
|
||||
|
||||
def remove_symbols(filename: str) -> str:
|
||||
if not filename:
|
||||
return filename
|
||||
|
||||
forbidden = '\\/*:?|"<>'
|
||||
for symbol in forbidden:
|
||||
filename.replace(symbol, "")
|
||||
return filename
|
||||
|
||||
|
||||
class JutSuD:
|
||||
def loader(self, anime_url, season_from, episode_from, season_to, episode_to):
|
||||
scraper = create_scraper(
|
||||
delay=1,
|
||||
browser={
|
||||
"custom": "ScraperBot/1.0",
|
||||
},
|
||||
)
|
||||
|
||||
response = scraper.get(anime_url)
|
||||
soup = BeautifulSoup(response.text, "lxml")
|
||||
|
||||
anime_title = soup.find("h1", {"class": "anime_padding_for_title"}).text
|
||||
anime_title = (
|
||||
anime_title.replace("Смотреть", "")
|
||||
.replace("все серии", "")
|
||||
.replace("и сезоны", "")
|
||||
.strip()
|
||||
)
|
||||
|
||||
seasons = [
|
||||
Season(
|
||||
title=season_title.text,
|
||||
episodes_urls=[],
|
||||
)
|
||||
for season_title in soup.find_all("h2", class_=["the-anime-season"])
|
||||
]
|
||||
|
||||
if not seasons:
|
||||
seasons.append(
|
||||
Season(
|
||||
title=anime_title,
|
||||
episodes_urls=[],
|
||||
)
|
||||
)
|
||||
|
||||
episodes_soup = soup.find_all(
|
||||
"a",
|
||||
class_=[
|
||||
"short-btn black video the_hildi",
|
||||
"short-btn green video the_hildi",
|
||||
],
|
||||
)
|
||||
|
||||
current_season_index = -1
|
||||
current_episode_class = None
|
||||
|
||||
for ep in episodes_soup:
|
||||
if ep["class"] != current_episode_class:
|
||||
current_episode_class = ep["class"]
|
||||
|
||||
current_season_index += 1
|
||||
|
||||
url = "https://jut.su" + ep["href"]
|
||||
seasons[current_season_index].episodes_urls.append(url)
|
||||
|
||||
for i, season in enumerate(seasons):
|
||||
season_number = i + 1
|
||||
|
||||
if season_number < season_from or season_number > season_to:
|
||||
continue
|
||||
|
||||
for j, episode_url in enumerate(season.episodes_urls):
|
||||
episode_number = j + 1
|
||||
|
||||
if (season_number == season_from and episode_number < episode_from) or (
|
||||
(season_number == season_to or season_number == len(seasons))
|
||||
and episode_number > episode_to
|
||||
):
|
||||
continue
|
||||
|
||||
response = scraper.get(episode_url)
|
||||
soup = BeautifulSoup(response.content, "lxml")
|
||||
|
||||
try:
|
||||
episode_title = (
|
||||
soup.find("div", {"class": "video_plate_title"}).find("h2").text
|
||||
)
|
||||
|
||||
except AttributeError:
|
||||
episode_title = soup.find("span", {"itemprop": "name"}).text
|
||||
episode_title = (
|
||||
episode_title.replace("Смотреть", "")
|
||||
.replace(anime_title, "")
|
||||
.strip()
|
||||
)
|
||||
|
||||
video_url = soup.find("source")["src"]
|
||||
|
||||
name_video = random.choices("".join(string.ascii_letters), k=10)
|
||||
video_path = pathlib.Path(f"{''.join(name_video)}.mp4")
|
||||
episode_slug = f"{season.title} - {episode_title} [#{episode_number}]"
|
||||
try:
|
||||
download_video(url=video_url, path=video_path, scraper=scraper)
|
||||
return video_path, episode_slug
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
return False, False
|
||||
|
||||
def get_info(self, url):
|
||||
scraper = create_scraper()
|
||||
response = scraper.get(url, headers=HEADERS)
|
||||
soup = BeautifulSoup(response.text, "lxml")
|
||||
|
||||
anime_title = soup.find("h1", {"class": "anime_padding_for_title"}).text
|
||||
|
||||
anime_title = (
|
||||
anime_title.replace("Смотреть", "")
|
||||
.replace("все серии", "")
|
||||
.replace("и сезоны", "")
|
||||
.strip()
|
||||
)
|
||||
|
||||
seasons = [
|
||||
Season(
|
||||
title=season_title,
|
||||
episodes_urls=[],
|
||||
)
|
||||
for season_title in soup.find_all("h2", class_=["the-anime-season"])
|
||||
]
|
||||
|
||||
if not seasons:
|
||||
seasons.append(
|
||||
Season(
|
||||
title=anime_title,
|
||||
episodes_urls=[],
|
||||
)
|
||||
)
|
||||
|
||||
episodes_soup = soup.find_all(
|
||||
"a",
|
||||
class_=[
|
||||
"short-btn black video the_hildi",
|
||||
"short-btn green video the_hildi",
|
||||
],
|
||||
)
|
||||
return anime_title, seasons, episodes_soup
|
||||
|
||||
|
||||
@loader.tds
|
||||
class Jutsu(loader.Module):
|
||||
"""Download and get info about anime from jut.su"""
|
||||
|
||||
strings = {
|
||||
"name": "Jutsu",
|
||||
"info": (
|
||||
"📺 <b>Anime info</b>\n\n"
|
||||
"<b>Title:</b> {}\n"
|
||||
"<b>Seasons:</b> {}\n"
|
||||
"<b>Total episodes:</b> {}\n"
|
||||
"<b>Link:</b> {}"
|
||||
),
|
||||
"download_button": "📥 Download",
|
||||
"done": "✅ Download completed!",
|
||||
"choose_season": "📺 <b>Choose season</b>",
|
||||
"choose_episode": "🪶 <b>Choose episode</b>",
|
||||
"wrong_url": "❌ Wrong url!",
|
||||
"no_args": "❌ No args!",
|
||||
"download": "📥 Downloading episode {}... (speed depends on your internet connection)",
|
||||
"close": "❌ Close",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"info": (
|
||||
"📺 <b>Информация о аниме</b>\n\n"
|
||||
"<b>Название:</b> {}\n"
|
||||
"<b>Сезонов:</b> {}\n"
|
||||
"<b>Всего серий:</b> {}\n"
|
||||
"<b>Ссылка:</b> {}"
|
||||
),
|
||||
"download_button": "📥 Скачать",
|
||||
"done": "✅ Скачивание завершено!",
|
||||
"choose_season": "📺 <b>Выберите сезон</b>",
|
||||
"choose_episode": "🪶 <b>Выберите серию</b>",
|
||||
"wrong_url": "❌ Неверная ссылка!",
|
||||
"no_args": "❌ Нет аргументов!",
|
||||
"download": "📥 Скачиваем серию {}... (скорость скачивание зависит от вашего интернета)",
|
||||
"close": "❌ Закрыть",
|
||||
}
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
asset_ch, _ = await utils.asset_channel(
|
||||
self._client,
|
||||
"JutSu downloads",
|
||||
"Downloaded anime from JutSu will be sent here. (Hikamoru back?)",
|
||||
avatar="https://i.pinimg.com/564x/0a/da/0b/0ada0bb575146736679f5ea7a78971b8.jpg",
|
||||
)
|
||||
self.chid = int(f"-100{asset_ch.id}")
|
||||
|
||||
|
||||
async def download_(self, call, url, seasons, episodes_soup):
|
||||
seasons = [season for season in range(1, len(seasons) + 1)]
|
||||
|
||||
kb = []
|
||||
|
||||
for mod_row in utils.chunks(seasons, 3):
|
||||
row = [
|
||||
{
|
||||
"text": f"• {season} •",
|
||||
"callback": self.season_,
|
||||
"args": (season, episodes_soup, url),
|
||||
}
|
||||
for season in mod_row
|
||||
]
|
||||
|
||||
kb += [row]
|
||||
|
||||
await call.edit(self.strings["choose_season"], reply_markup=kb)
|
||||
|
||||
async def season_(self, call, season, eps, url):
|
||||
episodes = [episode for episode in range(1, len(eps) + 1)]
|
||||
|
||||
kb = []
|
||||
|
||||
for mod_row in utils.chunks(episodes, 3):
|
||||
row = [
|
||||
{
|
||||
"text": f"• {episode} •",
|
||||
"callback": self.episod_,
|
||||
"args": (episode, season, url),
|
||||
}
|
||||
for episode in mod_row
|
||||
]
|
||||
|
||||
kb += [row]
|
||||
|
||||
await call.edit(self.strings["choose_episode"], reply_markup=kb)
|
||||
|
||||
async def episod_(self, call: CallbackQuery, episode, episode_number, url):
|
||||
await call.edit(self.strings["download"].format(episode_number))
|
||||
|
||||
try:
|
||||
name, title = JutSuD().loader(
|
||||
url, episode_number, episode, episode_number, episode
|
||||
)
|
||||
except TypeError:
|
||||
await call.edit("There is not such a episode (This bug with button will be fixed soon)")
|
||||
|
||||
await self.client.send_file(
|
||||
self.chid,
|
||||
open(name, "rb"),
|
||||
caption=self.strings["done"] + f"\n\n{title}",
|
||||
filetype="video",
|
||||
attributes=(DocumentAttributeVideo(0, 0, 0),),
|
||||
)
|
||||
|
||||
await call.edit(self.strings["done"])
|
||||
|
||||
os.remove(name)
|
||||
|
||||
async def close_(self, call):
|
||||
await call.delete()
|
||||
|
||||
@loader.command()
|
||||
async def jutsud(self, message):
|
||||
"""Download anime from jutsu - [url]"""
|
||||
|
||||
args = utils.get_args_raw(message)
|
||||
|
||||
if not args:
|
||||
await utils.answer(message, self.strings["no_args"])
|
||||
return
|
||||
|
||||
if not args.startswith("https://jut.su"):
|
||||
await utils.answer(message, self.strings["wrong_url"])
|
||||
return
|
||||
|
||||
anime_title, seasons, episodes_soup = JutSuD().get_info(args)
|
||||
|
||||
await utils.answer(
|
||||
message,
|
||||
self.strings["info"].format(
|
||||
anime_title, len(seasons), len(episodes_soup), args
|
||||
),
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": self.strings["download_button"],
|
||||
"callback": self.download_,
|
||||
"kwargs": {
|
||||
"url": args,
|
||||
"seasons": seasons,
|
||||
"episodes_soup": episodes_soup,
|
||||
},
|
||||
},
|
||||
{
|
||||
"text": self.strings["close"],
|
||||
"callback": self.close_,
|
||||
},
|
||||
]
|
||||
],
|
||||
)
|
||||
@@ -1,155 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/leta.jpg
|
||||
|
||||
# I don't care about other people's opinions, if you don't like it, don't use it. i will update this module in the future, if i have time.
|
||||
|
||||
import time
|
||||
import logging
|
||||
from .. import loader, utils
|
||||
from telethon.errors import ChatAdminRequiredError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class Leta(loader.Module):
|
||||
"""Customizable nightmode [Leta] for your group"""
|
||||
|
||||
strings = {
|
||||
"name": "Leta",
|
||||
"info": (
|
||||
"🐈⬛ Heeey! I'm <b>Leta</b>! I'm a module for nightmode in your group.\n"
|
||||
"📫 You can get acquainted with my settings using the command <code>.help Leta</code>."
|
||||
),
|
||||
"wrong_format": "<emoji document_id=5258419835922030550>🕔</emoji> <b>Enter the time in the format HH:MM</b>",
|
||||
"day": "<emoji document_id=6332496306593859160>🌅</emoji> <b>Good morning!</b>\n<b>Night mode is disabled.</b>",
|
||||
"night": "<emoji document_id=6334806423473489632>🌚</emoji> <b>Good night!</b>\n<b>Night mode is enabled.</b>",
|
||||
"rm": "<emoji document_id=5021905410089550576>✅</emoji> <b>Removed nightmode.</b>",
|
||||
"rm_notfound": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>Nightmode is not set.</b>",
|
||||
"set": "<emoji document_id=5980930633298350051>✅</emoji> Time set to\n<emoji document_id=6334361735444563461>🌃</emoji>🌙</emoji> Night: <code>{}</code>\n<emoji document_id=6332496306593859160>🌅</emoji> Day: <code>{}</code>",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"info": (
|
||||
"🐈⬛ Привет! Я <b>Leta</b>! Я модуль для ночного режима в вашей группе.\n"
|
||||
"📫 Ознакомиться с моими настройками можно с помощью команды <code>.help Leta</code>."
|
||||
),
|
||||
"wrong_format": "<emoji document_id=5258419835922030550>🕔</emoji> <b>Введите время в формате HH:MM</b>",
|
||||
"day": "<emoji document_id=6332496306593859160>🌅</emoji> <b>Доброе утро!</b>\n<b>Ночной режим отключен.</b>",
|
||||
"night": "<emoji document_id=6334806423473489632>🌚</emoji> <b>Доброй ночи!</b>\n<b>Ночной режим включен.</b>",
|
||||
"rm": "<emoji document_id=5021905410089550576>✅</emoji> <b>Удален ночной режим.</b>",
|
||||
"rm_notfound": "<emoji document_id=5456652110143693064>🤷♂️</emoji> <b>Ночной режим не установлен.</b>",
|
||||
"set": "<emoji document_id=5980930633298350051>✅</emoji> Время установлено на\n<emoji document_id=6334361735444563461>🌃</emoji>🌙</emoji> Ночь: <code>{}</code>\n<emoji document_id=6332496306593859160>🌅</emoji> День: <code>{}</code>",
|
||||
}
|
||||
|
||||
|
||||
def resolve_id(self, marked_id):
|
||||
if marked_id >= 0:
|
||||
return "user"
|
||||
marked_id = -marked_id
|
||||
marked_id -= 1000000000000
|
||||
return "chat"
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
if not self.get("info", False):
|
||||
await self.inline.bot.send_animation(
|
||||
self._tg_id,
|
||||
"https://0x0.st/Hpqm.mp4",
|
||||
caption=self.strings("info"),
|
||||
parse_mode="HTML",
|
||||
)
|
||||
self.set("info", True)
|
||||
|
||||
|
||||
async def lettimecmd(self, message):
|
||||
"""Set time - morning [HH:MM] evening [HH:MM]"""
|
||||
args = utils.get_args_raw(message).split(" ")
|
||||
resolving = self.resolve_id(message.chat_id)
|
||||
if resolving != "chat":
|
||||
return await utils.answer(message, "<b>Use this command in group</b>")
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings("wrong_format"))
|
||||
try:
|
||||
dh, dm = args[0].split(":")
|
||||
eh, em = args[1].split(":")
|
||||
if int(dh) > 23 or int(dh) < 0 or int(dm) > 59 or int(dm) < 0 or int(eh) > 23 or int(eh) < 0 or int(em) > 59 or int(em) < 0:
|
||||
return await utils.answer(message, self.strings("wrong_format"))
|
||||
except Exception:
|
||||
return await utils.answer(message, self.strings('wrong_format'))
|
||||
day = args[0]
|
||||
night = args[1]
|
||||
self.set(
|
||||
"ngs",
|
||||
{
|
||||
message.chat_id: {
|
||||
"time": night,
|
||||
"day": day,
|
||||
"chat": message.chat_id
|
||||
},
|
||||
}
|
||||
)
|
||||
await utils.answer(message, self.strings("set").format(night, day))
|
||||
|
||||
async def letrmchatcmd(self, message):
|
||||
"""Remove nightmode - chat-id"""
|
||||
try:
|
||||
args = int(utils.get_args_raw(message))
|
||||
d = self.get("ngs", {})
|
||||
logging.info(d)
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings("rm_notfound"))
|
||||
if args not in d:
|
||||
return await utils.answer(message, self.strings("rm_notfound"))
|
||||
del d[args]
|
||||
self.set("ngs", d)
|
||||
await utils.answer(message, self.strings("rm"))
|
||||
except ValueError:
|
||||
await utils.answer(message, self.strings("rm_notfound"))
|
||||
|
||||
@loader.loop(interval=60, autostart=True)
|
||||
async def checker_loop_night(self):
|
||||
"""Check time"""
|
||||
ngs = self.get("ngs", {})
|
||||
for i in ngs:
|
||||
if ngs[i]["time"] == time.strftime("%H:%M"):
|
||||
try:
|
||||
await self.client.send_message(ngs[i]["chat"], self.strings("night"))
|
||||
await self.client.edit_permissions(ngs[i]['chat'], send_messages=False)
|
||||
except ChatAdminRequiredError:
|
||||
await self.inline.bot.send_message(
|
||||
self._tg_id,
|
||||
f"👎 You don't have enough rights to change permissions in <code>{i['chat']}</code>",
|
||||
parse_mode="HTML",
|
||||
)
|
||||
|
||||
async def letchatscmd(self, message):
|
||||
"""Get all chats with nightmode"""
|
||||
ngs = self.get("ngs", {})
|
||||
if not ngs:
|
||||
return await utils.answer(message, "<b>There are no chats with nightmode</b>")
|
||||
msg = "<b>Chats with nightmode:</b>\n"
|
||||
for i in ngs:
|
||||
msg += f"\n<code>{i}</code>"
|
||||
await utils.answer(message, msg + "\n")
|
||||
|
||||
@loader.loop(interval=60, autostart=True)
|
||||
async def checker_loop_day(self):
|
||||
"""Check time"""
|
||||
ngs = self.get("ngs", {})
|
||||
for i in ngs:
|
||||
if ngs[i]["day"] == time.strftime("%H:%M"):
|
||||
try:
|
||||
await self.client.edit_permissions(ngs[i]['chat'], send_messages=True)
|
||||
await self.client.send_message(ngs[i]["chat"], self.strings("day"))
|
||||
except ChatAdminRequiredError:
|
||||
await self.inline.bot.send_message(
|
||||
self._tg_id,
|
||||
f"👎 You don't have enough rights to change permissions in <code>{i['chat']}</code>",
|
||||
parse_mode="HTML",
|
||||
)
|
||||
@@ -1,249 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# requires: bs4 aiohttp
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
|
||||
import aiohttp
|
||||
from bs4 import BeautifulSoup as bs
|
||||
|
||||
from .. import utils, loader
|
||||
|
||||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
|
||||
|
||||
class English:
|
||||
|
||||
async def definition_get(self, word: str):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
headers = {"User-Agent": user_agent}
|
||||
async with session.get(
|
||||
f"https://dictionary.cambridge.org/us/dictionary/english/{word}/",
|
||||
headers=headers,
|
||||
) as resp:
|
||||
if resp.status != 200:
|
||||
return f"Failed to retrieve data. Status code: {resp.status}"
|
||||
|
||||
soup = bs(await resp.text(), "html.parser")
|
||||
if not (div_element := soup.find("div", class_="def ddef_d db")):
|
||||
return "Definition not found"
|
||||
text = div_element.get_text()
|
||||
example_spans = soup.find_all("span", class_="eg deg")
|
||||
examples = []
|
||||
for ex in example_spans:
|
||||
example_text = ex.get_text()
|
||||
examples.append(example_text)
|
||||
|
||||
return {"definition": text.replace(":", ""), "examples": examples}
|
||||
|
||||
async def get_word_pronunciation_uk(self, word: str):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(
|
||||
f"https://dictionary.cambridge.org/dictionary/english/{word}",
|
||||
headers={"User-Agent": user_agent},
|
||||
) as resp:
|
||||
if resp.status == 200:
|
||||
soup = bs(await resp.text(), "html.parser")
|
||||
try:
|
||||
audio_tag = soup.find_all("audio", class_="hdn")[0]
|
||||
pron_tag = soup.find_all("span", class_="ipa dipa lpr-2 lpl-1")[
|
||||
0
|
||||
]
|
||||
audio_src = audio_tag.find("source", type="audio/mpeg")["src"]
|
||||
|
||||
return {
|
||||
"audio": f"https://dictionary.cambridge.org/us{audio_src}",
|
||||
"pron": pron_tag.get_text(),
|
||||
}
|
||||
except IndexError:
|
||||
return False
|
||||
|
||||
async def get_word_pronunciation_us(self, word: str):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(
|
||||
f"https://dictionary.cambridge.org/dictionary/english/{word}",
|
||||
headers={"User-Agent": user_agent},
|
||||
) as resp:
|
||||
if resp.status == 200:
|
||||
soup = bs(await resp.text(), "html.parser")
|
||||
try:
|
||||
audio_tag = soup.find_all("audio", class_="hdn")[1]
|
||||
audio_src = audio_tag.find("source")["src"]
|
||||
pron_tag = soup.find_all("span", class_="ipa dipa lpr-2 lpl-1")[
|
||||
1
|
||||
]
|
||||
|
||||
return {
|
||||
"audio": f"https://dictionary.cambridge.org{audio_src}",
|
||||
"pron": pron_tag.get_text(),
|
||||
}
|
||||
|
||||
except IndexError:
|
||||
return False
|
||||
|
||||
async def thesaurus_synonyms(self, word: str):
|
||||
url = f"https://thesaurus.plus/thesaurus/{word}"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, headers={"User-Agent": user_agent}) as resp:
|
||||
if resp.status == 200:
|
||||
soup = bs(await resp.text(), "html.parser")
|
||||
synonyms_list = []
|
||||
synonyms_ul = soup.find_all("ul", class_="list")[1]
|
||||
list_terms = synonyms_ul.find_all("li", class_="list_term")
|
||||
for term in list_terms:
|
||||
synonym = term.find("div", class_="p-2").get_text(strip=True)
|
||||
synonyms_list.append(synonym)
|
||||
return synonyms_list
|
||||
|
||||
async def thesaurus_antonyms(self, word: str):
|
||||
url = f"https://thesaurus.plus/thesaurus/{word}"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, headers={"User-Agent": user_agent}) as resp:
|
||||
if resp.status == 200:
|
||||
soup = bs(await resp.text(), "html.parser")
|
||||
antonyms_list = []
|
||||
antonyms_ul = soup.find_all("ul", class_="list")[0]
|
||||
list_terms = antonyms_ul.find_all("li", class_="list_term")
|
||||
for term in list_terms:
|
||||
antonym = term.find("div", class_="p-2").get_text(strip=True)
|
||||
antonyms_list.append(antonym)
|
||||
return antonyms_list
|
||||
|
||||
|
||||
@loader.tds
|
||||
class LexiwizMod(loader.Module, English):
|
||||
"""Lexical wizard - your english companion"""
|
||||
|
||||
strings = {
|
||||
"name": "Lexiwiz",
|
||||
"no_word": "🤷♂️ <b>No word provided</b>",
|
||||
"no_definition": "😖 <b>Unfortunately, I couldn't find the definition of this word.</b>",
|
||||
"definition": "📝 <b>Word:</b> <code>{}</code>\n\n🔆 <b>Definition:</b> <code>{}</code>\n\n📦 <b>Examples:</b>\n{}",
|
||||
"Pronunciation": "{} <b>{} Pronunciation:</b> <code>{}</code>\n🔊 <a href='{}'>Listen</a>",
|
||||
"no_synonyms": "😓 <b>Sorry, I couldn't find synonyms for this word.</b>",
|
||||
"synonyms": "📝 <b>Synonyms for the word:</b> <code>{}</code>\n\n🔆 <b>Synonyms:</b> <code>{}</code>",
|
||||
"no_antonyms": "😓 <b>Sorry, I couldn't find antonyms for this word.</b>",
|
||||
"antonyms": "📝 <b>Antonyms for the word:</b> <code>{}</code>\n\n🔆 <b>Antonyms:</b> <code>{}</code>",
|
||||
|
||||
}
|
||||
|
||||
@loader.command()
|
||||
async def getdef(self, message):
|
||||
"""Get definition of a word"""
|
||||
|
||||
word = utils.get_args_raw(message)
|
||||
|
||||
if not word:
|
||||
await utils.answer(message, self.strings("no_word"))
|
||||
return
|
||||
|
||||
definition = await self.definition_get(word)
|
||||
|
||||
if definition == "Definition not found":
|
||||
await utils.answer(message, self.strings("no_definition"))
|
||||
|
||||
if isinstance(definition, dict):
|
||||
text = ""
|
||||
|
||||
_definition = definition["definition"]
|
||||
_examples = definition["examples"]
|
||||
|
||||
for index, example in enumerate(_examples):
|
||||
text += f"<b>{index}</b>. <i>{example}</i>\n"
|
||||
|
||||
await utils.answer(
|
||||
message, self.strings("definition").format(word, _definition, text)
|
||||
)
|
||||
|
||||
else:
|
||||
await utils.answer(
|
||||
message, self.strings("definiotion").format(word, definition, " ")
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def getpron(self, message):
|
||||
"""Get pronunciation of a word"""
|
||||
word = utils.get_args_raw(message)
|
||||
reply = await message.get_reply_message()
|
||||
|
||||
if not word:
|
||||
await utils.answer(message, self.strings("no_word"))
|
||||
return
|
||||
|
||||
uk = await self.get_word_pronunciation_uk(word)
|
||||
us = await self.get_word_pronunciation_us(word)
|
||||
|
||||
if uk:
|
||||
await message.delete()
|
||||
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
uk["audio"],
|
||||
caption=self.strings("Pronunciation").format(
|
||||
"🇬🇧",
|
||||
"UK",
|
||||
uk["pron"],
|
||||
uk["audio"],
|
||||
),
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
|
||||
if us:
|
||||
await message.delete()
|
||||
|
||||
await message.client.send_file(
|
||||
message.to_id,
|
||||
us["audio"],
|
||||
caption=self.strings("Pronunciation").format(
|
||||
"🇺🇸",
|
||||
"US",
|
||||
us["pron"],
|
||||
us["audio"],
|
||||
),
|
||||
voice_note=True,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def getsyn(self, message):
|
||||
"""Get synonyms of a word"""
|
||||
word = utils.get_args_raw(message)
|
||||
|
||||
if not word:
|
||||
await utils.answer(message, self.strings("no_word"))
|
||||
return
|
||||
|
||||
synonyms = await self.thesaurus_synonyms(word)
|
||||
|
||||
if not synonyms:
|
||||
await utils.answer(message, self.strings("no_synonyms"))
|
||||
return
|
||||
|
||||
await utils.answer(
|
||||
message, self.strings("synonyms").format(word, ", ".join(synonyms))
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def getant(self, message):
|
||||
"""Get antonyms of a word"""
|
||||
word = utils.get_args_raw(message)
|
||||
|
||||
if not word:
|
||||
await utils.answer(message, self.strings("no_word"))
|
||||
return
|
||||
|
||||
antonyms = await self.thesaurus_antonyms(word)
|
||||
|
||||
if not antonyms:
|
||||
await utils.answer(message, self.strings("no_antonyms"))
|
||||
return
|
||||
|
||||
await utils.answer(
|
||||
message, self.strings("antonyms").format(word, ", ".join(antonyms))
|
||||
)
|
||||
@@ -1,27 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/my_usernames.jpg?raw=true
|
||||
from telethon import functions
|
||||
from telethon.tl.types import Channel
|
||||
from .. import loader, utils
|
||||
|
||||
@loader.tds
|
||||
class MyUsernames(loader.Module):
|
||||
"""The usernames I own"""
|
||||
|
||||
strings = {"name": "My Usernames"}
|
||||
@loader.command()
|
||||
async def myusern(self, message):
|
||||
"""A list of usernames that were created by me"""
|
||||
result = await self.client(functions.channels.GetAdminedPublicChannelsRequest())
|
||||
output_str = "• "
|
||||
for channel_obj in result.chats:
|
||||
if isinstance(channel_obj, Channel) and channel_obj.username is not None:
|
||||
output_str += f"<code>{channel_obj.title}</code> | <b>@{channel_obj.username}</b>\n• "
|
||||
await utils.answer(message, f"<b>💼 List usernames reserved by me</b>\n\n{output_str[:-3]}")
|
||||
@@ -1,296 +0,0 @@
|
||||
__version__ = (1, 0, 0)
|
||||
# ▀█▀ █ █ █▀█ █▀▄▀█ ▄▀█ █▀
|
||||
# █ █▀█ █▄█ █ ▀ █ █▀█ ▄█
|
||||
# https://t.me/netuzb
|
||||
#
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
|
||||
|
||||
# meta pic: https://te.legra.ph/file/4c1b4581de961df145a70.png
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Mydiary.jpg
|
||||
|
||||
# meta developer: @hikamoru & @wilsonmods
|
||||
# scope: hikka_min 1.4.0
|
||||
|
||||
|
||||
from .. import loader, utils
|
||||
from telethon.tl.types import Message
|
||||
|
||||
from ..inline.types import InlineQuery
|
||||
from ..inline.types import InlineCall
|
||||
|
||||
emoji_close = "🔻 "
|
||||
emoji_back = "↙️ "
|
||||
emoji_open = "💌 "
|
||||
emoji_about = "🚨 "
|
||||
|
||||
@loader.tds
|
||||
class PagesMod(loader.Module):
|
||||
"""Diary page"""
|
||||
|
||||
strings = {
|
||||
"name": "Diary",
|
||||
"_about_module": "What does this module do? - here you can write about your day and write notes",
|
||||
"_cfg_inline_banner": "Set `True` in order to disable an inline media banner.",
|
||||
"_cfdiary_open_text": "enter a diary name or information about it",
|
||||
"_cfdiary_second_text": "here you can write on dairy «text2»",
|
||||
"_cfdiary_three_text": "here you can write on dairy «text3»",
|
||||
"_cfdiary_four_text": "here you can write on dairy «text4»",
|
||||
"_cfdiary_first_text": "here you can write on dairy «text1»",
|
||||
"_cfdiary_second_text": "here you can write on dairy «text2»",
|
||||
"_cfdiary_three_text": "here you can write on dairy «text3»",
|
||||
"_cfdiary_four_text": "here you can write on dairy «text4»",
|
||||
"_cfg_button_1_": "here you can change button name «day1»",
|
||||
"_cfg_button_2_": "here you can change button name «day2»",
|
||||
"_cfg_button_3_": "here you can change button name «day3»",
|
||||
"_cfg_button_4_": "here you can change button name «day4»",
|
||||
"x": emoji_close + "Close",
|
||||
"back": emoji_back + "Back",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"_about_module": "Что делает этот модуль? - Ты ты можешь писать свои заметки или что делал сегодня",
|
||||
"_cfg_inline_banner": "Установите `True`, чтобы отключить встроенный медиа-баннер",
|
||||
"_cfdiary_open_text": "Введите название дневника или информацию о нем",
|
||||
"_cfdiary_first_text": "здесь ты можешь написать написать дневник на «text1»",
|
||||
"_cfdiary_second_text": "здесь ты можешь написать написать дневник на «text2»",
|
||||
"_cfdiary_three_text": "здесь ты можешь написать написать дневник на «text3»",
|
||||
"_cfdiary_four_text": "здесь ты можешь написать написать дневник на «text4»",
|
||||
"_cfg_button_1_": "здесь ты можешь поменять название кнопки «day1»",
|
||||
"_cfg_button_2_": "здесь ты можешь поменять название кнопки «day2»",
|
||||
"_cfg_button_3_": "здесь ты можешь поменять название кнопки «day3»",
|
||||
"_cfg_button_4_": "здесь ты можешь поменять название кнопки «day4»",
|
||||
"x": emoji_close + "Закрыть",
|
||||
"back": emoji_back + "Назад",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"_about_module": "Modul vazifasi nima?\n- Siz modul orqali bugungi kun rejangiz yoki eslatmani saqlab qoʻyishingiz mumkin.",
|
||||
"_cfg_inline_banner": "Media-bannerni yopish uchun `True` rejimini yoqing",
|
||||
"_cfdiary_open_text": "Kundalik nomini yoki unga bogʻliq maʼlumotni yozing",
|
||||
"_cfdiary_first_text": "Bu yerda siz «text_numb_1» sozlashingiz mumkin",
|
||||
"_cfdiary_second_text": "Bu yerda siz «text_numb_2» sozlashingiz mumkin",
|
||||
"_cfdiary_three_text": "Bu yerda siz «text_numb_3» sozlashingiz mumkin",
|
||||
"_cfdiary_four_text": "Bu yerda siz «text_numb_4» sozlashingiz mumkin",
|
||||
"_cfg_button_1_": "Bu yerda siz «button_numb_1» tugmasini sozlashingiz mumkin",
|
||||
"_cfg_button_2_": "Bu yerda siz «button_numb_2» tugmasini sozlashingiz mumkin",
|
||||
"_cfg_button_3_": "Bu yerda siz «button_numb_3» tugmasini sozlashingiz mumkin",
|
||||
"_cfg_button_4_": "Bu yerda siz «button_numb_4» tugmasini sozlashingiz mumkin",
|
||||
"x": emoji_close + "Yopish",
|
||||
"back": emoji_back + "Orqaga",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"open_text",
|
||||
"Here is a caption for my diary",
|
||||
doc=lambda: self.strings('_cfdiary_open_text'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"off_inline_banner",
|
||||
False,
|
||||
lambda: self.strings("_cfg_inline_banner"),
|
||||
validator=loader.validators.Boolean(),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"button_numb_1",
|
||||
"Day 1",
|
||||
doc=lambda: self.strings('_cfg_button_1_'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"button_numb_2",
|
||||
"Day 2",
|
||||
doc=lambda: self.strings('_cfg_button_2_'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"button_numb_3",
|
||||
"Day 3",
|
||||
doc=lambda: self.strings('_cfg_button_3_'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"button_numb_4",
|
||||
"Day 4",
|
||||
doc=lambda: self.strings('_cfg_button_4_'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"text_numb_1",
|
||||
"Today i played football with my friends then i fall,",
|
||||
doc=lambda: self.strings('_cfdiary_first_text'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"text_numb_2",
|
||||
"Today i walked with my friends and i saw my best friend who was drawer",
|
||||
doc=lambda: self.strings('_cfdiary_second_text'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"text_numb_3",
|
||||
"What are you did today?",
|
||||
doc=lambda: self.strings('_cfdiary_three_text'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"text_numb_4",
|
||||
"What are you did today?",
|
||||
doc=lambda: self.strings('_cfdiary_four_text'),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"banner_numb_1",
|
||||
"https://imgur.com/NqNGNOb",
|
||||
lambda: f"here you can write on dairy photo1",
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"banner_numb_2",
|
||||
"https://ibb.co/ZJ9hnfL",
|
||||
lambda: f"here you can write on dairy photo2",
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"banner_numb_3",
|
||||
"https://imgur.com/kITkUry",
|
||||
lambda: f"here you can write on dairy photo3",
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"banner_numb_4",
|
||||
"https://imgur.com/TOzh9u1",
|
||||
lambda: f"here you can write on dairy photo3",
|
||||
),
|
||||
)
|
||||
|
||||
async def cfdiarycmd(self, message):
|
||||
"""> Set up buttons for the module"""
|
||||
name = self.strings("name")
|
||||
await self.allmodules.commands["config"](
|
||||
await utils.answer(message,
|
||||
f"{self.get_prefix()}config {name}")
|
||||
)
|
||||
|
||||
async def mydiarycmd(self, message: Message):
|
||||
"""> Main the diary section"""
|
||||
await self.inline.form(
|
||||
text = self.config["open_text"],
|
||||
message=message,
|
||||
reply_markup=[
|
||||
[{
|
||||
"text": f"{emoji_open}Open diary",
|
||||
"callback": self.page_one
|
||||
}],
|
||||
[{
|
||||
"text": f"{emoji_about}About modules",
|
||||
"callback": self._about_us
|
||||
}]],
|
||||
**{"photo": "https://te.legra.ph/file/64bb29a68030e118dfa21.jpg"},
|
||||
)
|
||||
|
||||
async def mydiary_inline_handler(self, query: InlineQuery):
|
||||
"""> Main the diary section"""
|
||||
btn_a = [{
|
||||
"text": f"{emoji_open}Open diary",
|
||||
"callback": self.page_one
|
||||
}],
|
||||
btn_b = [{
|
||||
"text": f"{emoji_about}About modules",
|
||||
"callback": self._about_us
|
||||
}],
|
||||
msg_type = "message" if self.config["off_inline_banner"] else "caption"
|
||||
return {
|
||||
"title": "open diary",
|
||||
"description": "open my own diary page",
|
||||
msg_type: self.config['open_text'],
|
||||
"photo": "https://te.legra.ph/file/64bb29a68030e118dfa21.jpg",
|
||||
"thumb": (
|
||||
"https://te.legra.ph/file/4c1b4581de961df145a70.png"
|
||||
),
|
||||
"reply_markup": btn_a + btn_b,
|
||||
}
|
||||
|
||||
async def _back(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.config["open_text"],
|
||||
reply_markup=[
|
||||
[{
|
||||
"text": f"{emoji_open}Open diary",
|
||||
"callback": self.page_one
|
||||
}],
|
||||
[{
|
||||
"text": f"{emoji_about}About modules",
|
||||
"callback": self._about_us
|
||||
}]
|
||||
],
|
||||
**{"photo": "https://te.legra.ph/file/64bb29a68030e118dfa21.jpg"},
|
||||
)
|
||||
|
||||
async def _about_us(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.strings('_about_module'),
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": self.strings("back"),
|
||||
"callback": self._back
|
||||
},
|
||||
{
|
||||
"text": self.strings("x"),
|
||||
"action": "close"
|
||||
},
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
async def page_one(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.config["text_numb_1"],
|
||||
reply_markup=[
|
||||
[{"text": self.config["button_numb_1"], "callback": self.page_one}, {"text": self.config["button_numb_2"], "callback": self.page_two}],
|
||||
[{"text": self.config["button_numb_3"], "callback": self.page_three}, {"text": self.config["button_numb_4"], "callback": self.page_four}],
|
||||
[{
|
||||
"text": self.strings("x"),
|
||||
"action": "close"
|
||||
}]],
|
||||
**{"photo": self.config["banner_numb_1"]},
|
||||
)
|
||||
|
||||
async def page_two(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.config["text_numb_2"],
|
||||
reply_markup=[
|
||||
[{"text": self.config["button_numb_1"], "callback": self.page_one}, {"text": self.config["button_numb_2"], "callback": self.page_two}],
|
||||
[{"text": self.config["button_numb_3"], "callback": self.page_three}, {"text": self.config["button_numb_4"], "callback": self.page_four}],
|
||||
[{
|
||||
"text": self.strings("x"),
|
||||
"action": "close"
|
||||
}]],
|
||||
**{"photo": self.config["banner_numb_2"]},
|
||||
)
|
||||
|
||||
async def page_three(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.config["text_numb_3"],
|
||||
reply_markup=[
|
||||
[{"text": self.config["button_numb_1"], "callback": self.page_one}, {"text": self.config["button_numb_2"], "callback": self.page_two}],
|
||||
[{"text": self.config["button_numb_3"], "callback": self.page_three}, {"text": self.config["button_numb_4"], "callback": self.page_four}],
|
||||
[{
|
||||
"text": self.strings("x"),
|
||||
"action": "close"
|
||||
}]],
|
||||
**{"photo": self.config["banner_numb_3"]},
|
||||
)
|
||||
|
||||
async def page_four(self, call: InlineCall):
|
||||
await call.edit(
|
||||
text = self.config["text_numb_4"],
|
||||
reply_markup=[
|
||||
[{"text": self.config["button_numb_1"], "callback": self.page_one}, {"text": self.config["button_numb_2"], "callback": self.page_two}],
|
||||
[{"text": self.config["button_numb_3"], "callback": self.page_three}, {"text": self.config["button_numb_4"], "callback": self.page_four}],
|
||||
[{
|
||||
"text": self.strings("x"),
|
||||
"action": "close"
|
||||
}]],
|
||||
**{"photo": self.config["banner_numb_4"]},
|
||||
)
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Nytimer.jpg
|
||||
|
||||
from .. import loader, utils
|
||||
import datetime
|
||||
from time import strftime
|
||||
|
||||
|
||||
@loader.tds
|
||||
class NYMod(loader.Module):
|
||||
"""Check how much is left until the new year"""
|
||||
|
||||
strings = {'name': 'NewYearTimer'}
|
||||
|
||||
async def nycmd(self, message):
|
||||
"""Check date"""
|
||||
now = datetime.datetime.today()
|
||||
ng = datetime.datetime(int(strftime('%Y')) + 1, 1, 1)
|
||||
d = ng - now
|
||||
mm, ss = divmod(d.seconds, 60)
|
||||
hh, mm = divmod(mm, 60)
|
||||
soon = '<b><emoji document_id=6334530007968253960>☃️</emoji> Until the <u>New Year</u>: {} d. {} h. {} m. {} s.</b>\n<b><emoji document_id=5393226077520798225>🥰</emoji> Wait for the new year together <u>Family</u></b>'.format(
|
||||
d.days, hh, mm, ss)
|
||||
await utils.answer(message, soon)
|
||||
@@ -1,62 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/phstiker.jpg
|
||||
# requires: phlogo
|
||||
|
||||
import os
|
||||
from .. import loader, utils
|
||||
from phlogo import generate
|
||||
|
||||
@loader.tds
|
||||
class PhLogo(loader.Module):
|
||||
"""Make Pornhub logo sticker"""
|
||||
|
||||
strings = {
|
||||
"name": "Phlogo",
|
||||
"only_two": "Something's wrong. Try giving two words only like `Hello world`",
|
||||
"none_args": "Give some text bruh, e.g.: `Hello world`"
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"only_two": "Что-то не так. Попробуйте указать только два аргумента, например «Hello world».",
|
||||
"none_args": "Дай какой-нибудь текст, например: `Hello world`."
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"only_two": "Xatolik bor. `Hello world` kabi faqat ikkita matn keltirishga harakat qiling.",
|
||||
"none_args": "Bir oz matn bering, masalan: `Salom dunyo`."
|
||||
}
|
||||
|
||||
@loader.command()
|
||||
async def phl(self, message):
|
||||
"Makes PHub style logo sticker."
|
||||
args = utils.get_args_raw(message).split(' ')
|
||||
reply = await message.get_reply_message()
|
||||
if args == " ":
|
||||
await utils.answer(message, self.strings('none_args'))
|
||||
return
|
||||
try:
|
||||
p = args[0]
|
||||
h = args[1]
|
||||
except:
|
||||
await utils.answer(message, self.strings('only_two'))
|
||||
return
|
||||
result = generate(f"{p}",f"{h}")
|
||||
result.save("ph.webp")
|
||||
path = os.getcwd()
|
||||
stc = f"{path}/ph.webp"
|
||||
await message.delete()
|
||||
await self._client.send_file(
|
||||
message.peer_id,
|
||||
stc,
|
||||
caption=f"{p} {h}",
|
||||
link_preview=False,
|
||||
reply_to=reply.id if reply else None,
|
||||
)
|
||||
os.remove(stc)
|
||||
@@ -1,88 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/poststeal.jpg
|
||||
|
||||
|
||||
from .. import loader, utils
|
||||
|
||||
|
||||
@loader.tds
|
||||
class PostStealer(loader.Module):
|
||||
"Steal post from another channel to your channel"
|
||||
|
||||
strings = {
|
||||
'name': 'PostStealler',
|
||||
'enable': '<b>Steal mode enabled.</b>',
|
||||
'disable': '<b>Steal mode disabled.</b>',
|
||||
'channel': 'channel id where ub will steal messages',
|
||||
'my_channel': 'channel id where ub will send messages'
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
'enable': '<b>StealMod включен.</b>',
|
||||
'disable': '<b>StealMod отключен.</b>',
|
||||
'channel': 'айди канала откуда юб будет пересылать сообщения',
|
||||
'my_channel': 'айди канала куда юб будет пересылать сообщения'
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"my_channel",
|
||||
None,
|
||||
lambda: self.strings("my_channel"),
|
||||
),
|
||||
loader.ConfigValue(
|
||||
"channel",
|
||||
None,
|
||||
lambda: self.strings("channel"),
|
||||
),
|
||||
)
|
||||
|
||||
async def client_ready(self, client, db):
|
||||
self.client = client
|
||||
self.db = db
|
||||
|
||||
@loader.command()
|
||||
async def smode(self, message):
|
||||
"""- off/on steal mode"""
|
||||
|
||||
status = self.db.get(
|
||||
"steal_status",
|
||||
"status",
|
||||
)
|
||||
if status == "":
|
||||
self.db.set("steal_status", "status", True)
|
||||
if status == False:
|
||||
self.db.set("steal_status", "status", True)
|
||||
await utils.answer(message, self.strings("enable"))
|
||||
else:
|
||||
self.db.set("steal_status", "status", False)
|
||||
await utils.answer(message, self.strings("disable"))
|
||||
|
||||
async def watcher(self, message):
|
||||
"""Лень писать описание"""
|
||||
status = self.db.get("steal_status", "status")
|
||||
if status == False:
|
||||
return False
|
||||
if status == True:
|
||||
steal = self.config['channel']
|
||||
chatid = int(message.chat_id)
|
||||
text = message.text
|
||||
if chatid == steal:
|
||||
if message.photo:
|
||||
await self._client.send_file(int(self.config['my_channel']), message.photo, caption=message.text if text else None, link_preview=False)
|
||||
elif message.video:
|
||||
await self._client.send_file(int(self.config['my_channel']), message.video, caption=message.text if text else None, link_preview=False)
|
||||
elif message.document:
|
||||
await self._client.send_file(int(self.config['my_channel']), message.document, caption=message.text if text else None, link_preview=False)
|
||||
elif message.text:
|
||||
await message.client.send_message(int(self.config['my_channel']), message.text)
|
||||
else:
|
||||
return False
|
||||
@@ -1,80 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/recognition.jpg
|
||||
|
||||
from .. import utils, loader
|
||||
import imghdr
|
||||
import io
|
||||
import random
|
||||
from telethon.tl.types import Message
|
||||
|
||||
|
||||
@loader.tds
|
||||
class RecognitionMod(loader.Module):
|
||||
"""Recognition from photo"""
|
||||
|
||||
strings = {
|
||||
'name': 'Recognition',
|
||||
'args': "No args!"
|
||||
}
|
||||
|
||||
async def get_media(self, message: Message):
|
||||
reply = await message.get_reply_message()
|
||||
m = None
|
||||
if reply and reply.media:
|
||||
m = reply
|
||||
elif message.media:
|
||||
m = message
|
||||
elif not reply:
|
||||
await utils.answer(message, self.strings('args'))
|
||||
return False
|
||||
|
||||
if not m:
|
||||
file = io.BytesIO(bytes(reply.raw_text, "utf-8"))
|
||||
file.name = "file.txt"
|
||||
else:
|
||||
file = io.BytesIO(await self._client.download_media(m, bytes))
|
||||
file.name = (
|
||||
m.file.name
|
||||
or (
|
||||
"".join(
|
||||
[
|
||||
random.choice(
|
||||
"abcdefghijklmnopqrstuvwxyz1234567890")
|
||||
for _ in range(16)
|
||||
]
|
||||
)
|
||||
)
|
||||
+ m.file.ext
|
||||
)
|
||||
|
||||
return file
|
||||
|
||||
async def get_image(self, message: Message):
|
||||
file = await self.get_media(message)
|
||||
if not file:
|
||||
return False
|
||||
|
||||
if imghdr.what(file) not in ["gif", "png", "jpg", "jpeg", "tiff", "bmp"]:
|
||||
return False
|
||||
return file
|
||||
|
||||
@loader.command()
|
||||
async def reco(self, message: Message):
|
||||
"""recognize from photo <reply to photo>"""
|
||||
file = await self.get_image(message)
|
||||
if not file:
|
||||
return False
|
||||
async with self._client.conversation("@Rekognition_Bot") as conv:
|
||||
await conv.send_message(file=file) # upload step
|
||||
await conv.get_response() # ignore message
|
||||
cp = await conv.get_response() # get message
|
||||
|
||||
await utils.answer(message, cp)
|
||||
await self.client.delete_dialog("@Rekognition_Bot")
|
||||
@@ -1,34 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Searchpic.jpg
|
||||
# meta developer: @amoremods
|
||||
|
||||
from .. import loader, utils
|
||||
from telethon.tl.types import Message
|
||||
|
||||
@loader.tds
|
||||
class SearchPic(loader.Module):
|
||||
|
||||
strings = {"name": "SearchPic"}
|
||||
|
||||
@loader.unrestricted
|
||||
async def spiccmd(self, message: Message):
|
||||
"""Search picture"""
|
||||
text = utils.get_args_raw(message)
|
||||
await self.inline.form(
|
||||
message=message,
|
||||
text = f"🎑 Your pic found\n✍ Input argument: {text}",
|
||||
reply_markup=[
|
||||
[{"text": "Pic here", "url": f"https://yandex.uz/images/touch/search/?text={text}",}],
|
||||
[{"text": "Close", "action": "close"}],
|
||||
],
|
||||
**(
|
||||
{"photo": f"https://yandex.uz/images/touch/search/?text={text}"}
|
||||
),
|
||||
)
|
||||
@@ -1,94 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# scope: ffmpeg
|
||||
# requires: pydub speechrecognition python-ffmpeg
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta banner: https://github.com/AmoreForever/assets/blob/master/Speech.jpg?raw=true
|
||||
|
||||
import os
|
||||
import logging
|
||||
import speech_recognition as sr
|
||||
from pydub import AudioSegment
|
||||
from .. import loader, utils
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
recognizer = sr.Recognizer()
|
||||
|
||||
@loader.tds
|
||||
class SpeechMod(loader.Module):
|
||||
"""Simple speech recognition module."""
|
||||
|
||||
strings = {
|
||||
"name": "Speech",
|
||||
"only_voice": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Reply to a voice message!</b>",
|
||||
"downloading": "<emoji document_id=5213251580425414358>🔽</emoji> <b>Downloading...</b>",
|
||||
"recognizing": "<emoji document_id=5472199711366584503>👂</emoji> <b>Recognizing...</b>",
|
||||
"not_recognized": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Not recognized</b>",
|
||||
"request_error": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Request error occured.\n{}</b>",
|
||||
"recognized": "<emoji document_id=5267468588985363056>🚛</emoji> <b>Recognized:</b> <code>{}</code>",
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"only_voice": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Ответь на голосовое сообщение!</b>",
|
||||
"downloading": "<emoji document_id=5213251580425414358>🔽</emoji> <b>Загрузка...</b>",
|
||||
"recognizing": "<emoji document_id=5472199711366584503>👂</emoji> <b>Распознавание...</b>",
|
||||
"not_recognized": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Не распознано</b>",
|
||||
"request_error": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Произошла ошибка запроса.\n{}</b>",
|
||||
"recognized": "<emoji document_id=5267468588985363056>🚛</emoji> <b>Распознано:</b> <code>{}</code>",
|
||||
}
|
||||
|
||||
strings_uz = {
|
||||
"only_voice": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Ovozli xabarga javob bering!</b>",
|
||||
"downloading": "<emoji document_id=5213251580425414358>🔽</emoji> <b>Yuklanmoqda...</b>",
|
||||
"recognizing": "<emoji document_id=5472199711366584503>👂</emoji> <b>Eshitilmoqda...</b>",
|
||||
"not_recognized": "<emoji document_id=5877477244938489129>🚫</emoji> <b>Tanilmadi</b>",
|
||||
"request_error": "<emoji document_id=5877477244938489129>🚫</emoji> <b>So'rovda xatolik yuz berdi.\n{}</b>",
|
||||
"recognized": "<emoji document_id=5267468588985363056>🚛</emoji> <b>Text:</b> <code>{}</code>",
|
||||
}
|
||||
|
||||
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
loader.ConfigValue(
|
||||
"language",
|
||||
"ru-RU",
|
||||
lambda: "Language for recognition.",
|
||||
validator=loader.validators.RegExp(r"^[a-z]{2}-[A-Z]{2}$"),
|
||||
),
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def spech(self, message):
|
||||
"""Recognize voice message. Usage: .spech <reply to voice message>"""
|
||||
reply = await message.get_reply_message()
|
||||
if not reply or not reply.voice:
|
||||
await utils.answer(message, self.strings("only_voice"))
|
||||
return
|
||||
await utils.answer(message, self.strings("downloading"))
|
||||
voice = await message.client.download_media(reply.voice)
|
||||
wav_voice = voice.replace(voice.split(".")[-1], "wav")
|
||||
ogg_audio = AudioSegment.from_ogg(voice)
|
||||
ogg_audio.export(wav_voice, format="wav")
|
||||
audio = sr.AudioFile(wav_voice)
|
||||
with audio as source:
|
||||
try:
|
||||
audio = recognizer.record(source)
|
||||
await utils.answer(message, self.strings("recognizing"))
|
||||
recognized = recognizer.recognize_google(audio, language=self.config["language"])
|
||||
except sr.UnknownValueError:
|
||||
await utils.answer(message, self.strings("not_recognized"))
|
||||
return
|
||||
except sr.RequestError as e:
|
||||
await utils.answer(message, self.strings("request_error").format(e))
|
||||
return
|
||||
await utils.answer(message, self.strings("recognized").format(recognized))
|
||||
os.remove(voice)
|
||||
os.remove(wav_voice)
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
# meta pic: https://te.legra.ph/file/5ef64ee0466032d8a4687.png
|
||||
# meta banner: hhttps://raw.githubusercontent.com/AmoreForever/assets/master/Telegraphup.jpg
|
||||
|
||||
from .. import loader, utils
|
||||
import requests
|
||||
from telethon.tl.types import DocumentAttributeFilename
|
||||
|
||||
|
||||
@loader.tds
|
||||
class Telegraphup(loader.Module):
|
||||
"""Upload video and photo to telegraph"""
|
||||
|
||||
strings = {
|
||||
"name": "Telegraph",
|
||||
"pls_reply": "⚠️ Reply to photo or video/gif",
|
||||
}
|
||||
|
||||
@loader.sudo
|
||||
async def thupcmd(self, message):
|
||||
"""<reply photo or video>"""
|
||||
if message.is_reply:
|
||||
reply_message = await message.get_reply_message()
|
||||
data = await check_media(reply_message)
|
||||
if isinstance(data, bool):
|
||||
await message.edit(self.strings("pls_reply"))
|
||||
return
|
||||
else:
|
||||
await message.edit(self.strings("pls_reply"))
|
||||
return
|
||||
|
||||
file = await message.client.download_media(data, bytes)
|
||||
path = requests.post(
|
||||
"https://te.legra.ph/upload", files={"file": ("file", file, None)}
|
||||
).json()
|
||||
try:
|
||||
amore = "https://te.legra.ph" + path[0]["src"]
|
||||
except KeyError:
|
||||
amore = path["error"]
|
||||
await utils.answer(message, f"😸 Your file uploaded: <code>{amore}</code>")
|
||||
|
||||
|
||||
async def check_media(reply_message):
|
||||
if reply_message and reply_message.media:
|
||||
if reply_message.photo:
|
||||
data = reply_message.photo
|
||||
elif reply_message.document:
|
||||
if (
|
||||
DocumentAttributeFilename(file_name="AnimatedSticker.tgs")
|
||||
in reply_message.media.document.attributes
|
||||
):
|
||||
return False
|
||||
if reply_message.audio or reply_message.voice:
|
||||
return False
|
||||
data = reply_message.media.document
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
if not data or data is None:
|
||||
return False
|
||||
else:
|
||||
return data
|
||||
@@ -1,98 +0,0 @@
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠛⠛
|
||||
# ⣶⣦⣤⣤⣤⣤⣤⣤⣬⣭⣭⣍⣉⡙⠛⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⣋⣩⣭⣥⣤⣴⣶⣶⣶⣶⣶⣶⣶⣶⣶
|
||||
# ⣆⠀⠀⠀⢡⠁⠀⡀⠀⢸⠟⠻⣯⠙⠛⠷⣶⣬⡙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢉⣥⣶⡟⠻⣙⡉⠀⢰⡆⠀⠀⣡⠀⣧⠀⠀⠀⢨
|
||||
# ⠻⣦⠀⠀⠈⣇⣀⣧⣴⣿⣶⣶⣿⣷⠀⢀⡇⠉⠻⢶⣌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⡶⠟⠉⠀⢣⠀⣿⠷⠀⠀⠀⠀⣿⡷⢀⠇⠀⠀⢠⣿
|
||||
# ⣦⡈⢧⡀⠀⠘⢮⡙⠛⠉⠀⠄⠙⢿⣀⠞⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠈⠳⣄⠉⠓⠒⠚⠋⢀⡠⠋⠀⢀⣴⣏⣿
|
||||
# ⣿⣿⣿⣛⣦⣀⠀⠙⠓⠦⠤⣤⠔⠛⠁⠀⠀⠀⠀⠀⢀⣀⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣤⣤⣤⣀⣀⣀⣀⢙⢓⣒⡒⠚⠋⢠⣤⢶⣟⣽⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣷⣦⠀⠀⣴⣿⣷⣶⣶⣶⣾⡖⢰⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣾⣿⣿⣶⣾⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣿⣿⣿⣿⣿⣿⣿⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⡏⠀⢸⣿⣿⣿⣿⣿⣿⣿⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
# ⣿⣿⣿⣿⣿⣿⣿⣷⠀⢸⣿⣿⣿⣿⣿⣿⣿⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# https://t.me/amorescam
|
||||
|
||||
# meta developer: @amoremods
|
||||
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Universaltime.jpg
|
||||
# @Den4ikSuperOstryyPer4ik: I Love AmoreMods :)
|
||||
|
||||
|
||||
from .. import loader, utils
|
||||
import datetime
|
||||
from ..inline.types import InlineCall
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def check_time():
|
||||
offsets = [3, 5, 4, 2, 1, -7, 6, 9, 5.30, 9, 8, -8, -4]
|
||||
hrs = []
|
||||
for x in offsets:
|
||||
offset = datetime.timedelta(hours=x)
|
||||
not_tz = datetime.timezone(offset)
|
||||
time = datetime.datetime.now(not_tz)
|
||||
format_ = time.strftime("%d.%m.%y | %H:%M")
|
||||
hrs.append(format_)
|
||||
return f"<emoji document_id=4920662486778119009>🌐</emoji> <b>Universal time</b>\n\n<emoji document_id=6323139226418284334>🇷🇺</emoji> Russia ➪ {hrs[0]}\n<emoji document_id=6323430017179059570>🇺🇿</emoji> Uzbekistan ➪ {hrs[1]}\n<emoji document_id=6323289850921354919>🇺🇦</emoji> Ukraine ➪ {hrs[3]}\n<emoji document_id=6323575251498174463>🇦🇿</emoji> Azerbaijan ➪ {hrs[2]}\n<emoji document_id=6320817337033295141>🇩🇪</emoji> German ➪ {hrs[3]}\n<emoji document_id=6323589145717376403>🇬🇧</emoji> UK ➪ {hrs[4]}\n<emoji document_id=6323602387101550101>🇵🇱</emoji> Poland ➪ {hrs[3]}\n<emoji document_id=6323374027985389586>🇺🇸</emoji> USA ➪ {hrs[5]}\n<emoji document_id=6323615997852910673>🇰🇬</emoji> Kyrgyzstan ➪ {hrs[6]}\n<emoji document_id=6323135275048371614>🇰🇿</emoji> Kazakhstan ➪ {hrs[6]}\n<emoji document_id=6323555846835930376>🇮🇶</emoji> Iraq ➪ {hrs[0]}\n<emoji document_id=6323356796576597627>🇯🇵</emoji> Japan ➪ {hrs[7]}\n<emoji document_id=6323152716910561397>🇰🇷</emoji> South KR ➪ {hrs[7]}\n<emoji document_id=6323181871148566277>🇮🇳</emoji> India ➪ {hrs[8]}\n<emoji document_id=6323570711717742330>🇫🇷</emoji> France ➪ {hrs[3]}\n<emoji document_id=6323453751168337485>🇨🇳</emoji> China ➪ {hrs[9]}\n<emoji document_id=6321003171678259486>🇹🇷</emoji> Turkey ➪ {hrs[0]}\n<emoji document_id=6323602322677040561>🇨🇱</emoji> Mongolia ➪ {hrs[10]}\n<emoji document_id=6323325327351219831>🇨🇦</emoji> Canada ➪ {hrs[11]}\n<emoji document_id=6323471399188957082>🇮🇹</emoji> Italia ➪ {hrs[2]}\n<emoji document_id=6323516260122363644>🇪🇬</emoji> Egypt ➪ {hrs[3]}\n<emoji document_id=6323236391463421376>🇦🇲</emoji> Armenia ➪ {hrs[12]}\n\n<emoji document_id=5188216117272780281>🍙</emoji> #whyamore"
|
||||
|
||||
|
||||
@loader.tds
|
||||
class UniversalTimeMod(loader.Module):
|
||||
"""See the time of other countries"""
|
||||
|
||||
strings = {"name": "UnivTime"}
|
||||
|
||||
@loader.command(ru_docs="Смотреть мировое время")
|
||||
async def atimecmd(self, message):
|
||||
"""See time"""
|
||||
kk = check_time()
|
||||
await utils.answer(message, kk)
|
||||
|
||||
@loader.command(ru_docs="Смотреть мировое время в инлайн режиме")
|
||||
async def atimeicmd(self, message):
|
||||
"""See time on inline mode"""
|
||||
kk = check_time()
|
||||
await self.inline.form(
|
||||
text=kk,
|
||||
message=message,
|
||||
gif="https://te.legra.ph/file/2ab9b131ceceb9b020583.mp4",
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": "🍃 Refresh",
|
||||
"callback": self.refresh,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"text": "🔻 Close",
|
||||
"action": "close",
|
||||
}
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
async def refresh(self, call: InlineCall): # thanks @Den4ikSuperOstryyPer4ik
|
||||
kk = check_time()
|
||||
await call.edit(
|
||||
text=kk,
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": "🍃 Refresh",
|
||||
"callback": self.refresh,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"text": "🔻 Close",
|
||||
"action": "close",
|
||||
}
|
||||
]
|
||||
]
|
||||
)
|
||||
await call.answer("Refreshed ✨")
|
||||
@@ -1,214 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
|
||||
# pusechka @saint_players thanks for the idea
|
||||
|
||||
import logging
|
||||
import requests
|
||||
from telethon.tl.types import Message
|
||||
from telethon.tl.functions.channels import CreateChannelRequest, UpdateUsernameRequest
|
||||
from telethon.tl.types import InputPeerChannel
|
||||
from .. import loader, utils
|
||||
from ..inline.types import InlineCall
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@loader.tds
|
||||
class UserStealer(loader.Module):
|
||||
"""
|
||||
Username tracking module.
|
||||
"""
|
||||
|
||||
strings = {
|
||||
"name": "UsernameChecker",
|
||||
"create_channel": "📂 Create channel",
|
||||
"user_free": "⚡️ Username @{} is free, quickly take it.",
|
||||
"user_busy": "😥 Username @{} is busy. Do you want to enable tracking?",
|
||||
"yes": "🛟 Yes",
|
||||
"nope": "🧰 No",
|
||||
"free_now": "🌟 Username {} is free, do you want to create a channel?",
|
||||
"not_args": "🚫 Enter the user for check",
|
||||
"status": "🆔 Username @{} is being tracked\n🟢 Status: free",
|
||||
"status_busy": "🆔 Username @{} is being tracked\n🟡 Status: busy",
|
||||
"none": "❌ No username is being tracked.",
|
||||
"done": "🦉 Done, wait till username will be free",
|
||||
"created": "🌟 Channel created, go to username @{}",
|
||||
"tg_bug": "🐞 Telegram has bugs, if the channel is not created, try to create it manually",
|
||||
|
||||
}
|
||||
|
||||
strings_ru = {
|
||||
"create_channel": "📂 Создать канал",
|
||||
"user_free": "⚡️ Юзернейм @{} свободен, быстро забирай его.",
|
||||
"user_busy": "😥 Юзернейм @{} занят. Хотите включить отслеживание?",
|
||||
"yes": "🛟 Да",
|
||||
"nope": "🧰 Нет",
|
||||
"free_now": "🌟 Юзернейм {} свободен, хотите создать канал?",
|
||||
"not_args": "🚫 Укажи юзернейм для проверки",
|
||||
"status": "🆔 Юзернейм @{} отслеживается\n🟢 Статус: свободен",
|
||||
"status_busy": "🆔 Юзернейм @{} отслеживается\n🟡 Статус: занят",
|
||||
"none": "❌ Ни один юзернейм не отслеживается.",
|
||||
"done": "🦉 Готово, жди пока юзернейм освободится",
|
||||
"created": "🌟 Канал создан, переходи по юзернейму @{}",
|
||||
"tg_bug": "🐞 У телеграма баги, если канал не создан, попробуй создать его вручную",
|
||||
}
|
||||
|
||||
@loader.loop(interval=30, autostart=True)
|
||||
async def _steal(self):
|
||||
user = self.db.get("usernames_to_check", "username")
|
||||
if user == "none":
|
||||
return
|
||||
else:
|
||||
r = requests.get(url=f"https://t.me/{user}")
|
||||
if (
|
||||
r.text.find(
|
||||
'If you have <strong>Telegram</strong>, you can contact <a class="tgme_username_link"'
|
||||
)
|
||||
>= 0
|
||||
):
|
||||
self._markup = lambda: self.inline.generate_markup(
|
||||
[
|
||||
{"text": self.strings("create_channel"), "callback": self.create_inline, "args": (user,),},
|
||||
{"text": "Отмена", "callback": self.delete, },
|
||||
]
|
||||
)
|
||||
await self.inline.bot.send_message(
|
||||
self._client.tg_id,
|
||||
self.strings("user_free").format(user),
|
||||
disable_web_page_preview=True,
|
||||
reply_markup=self._markup()
|
||||
)
|
||||
|
||||
self.db.set("usernames_to_check", "username", "none")
|
||||
else:
|
||||
pass
|
||||
|
||||
|
||||
@loader.command()
|
||||
async def ucheckcmd(self, message: Message):
|
||||
"""> Enter the user for check (without @)"""
|
||||
args = utils.get_args_raw(message)
|
||||
r = requests.get(url=f"https://t.me/{args}")
|
||||
|
||||
if args.startswith('@'):
|
||||
args = args[1:]
|
||||
|
||||
if not args:
|
||||
return await utils.answer(message, self.strings("not_args"))
|
||||
|
||||
if (
|
||||
r.text.find(
|
||||
'If you have <strong>Telegram</strong>, you can contact <a class="tgme_username_link"'
|
||||
)
|
||||
>= 0
|
||||
):
|
||||
await self.inline.form(
|
||||
text=self.strings("free_now").format(args),
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": self.strings("yes"),
|
||||
"callback": self.create,
|
||||
"args": (args,),
|
||||
},
|
||||
{"text": self.strings("nope"), "action": "close"},
|
||||
],
|
||||
], **{'video': 'https://te.legra.ph/file/a14a9ff4071d079272171.mp4'},
|
||||
message=message,
|
||||
)
|
||||
|
||||
else:
|
||||
await self.inline.form(
|
||||
text=self.strings("user_busy").format(args),
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": self.strings("yes"),
|
||||
"callback": self.owo,
|
||||
"args": (args,),
|
||||
},
|
||||
{"text": self.strings("nope"), "action": "close"},
|
||||
],
|
||||
], **{"video": "https://te.legra.ph/file/90fbbd0deabfc5e740eb3.mp4"},
|
||||
message=message,
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def myus(self, message: Message):
|
||||
"""> Check status of the user being tracked"""
|
||||
proc = self.db.get("usernames_to_check", "username")
|
||||
if proc == 'none':
|
||||
await utils.answer(message, self.strings("none"))
|
||||
else:
|
||||
r = requests.get(url=f"https://t.me/{proc}")
|
||||
if (
|
||||
r.text.find(
|
||||
'If you have <strong>Telegram</strong>, you can contact <a class="tgme_username_link"'
|
||||
)
|
||||
>= 0
|
||||
):
|
||||
await utils.answer(message, self.strings("status").format(proc))
|
||||
|
||||
else:
|
||||
await utils.answer(message, self.strings("status_busy").format(proc))
|
||||
|
||||
async def owo(self, call: InlineCall, text: str):
|
||||
self.db.set("usernames_to_check", "username", text)
|
||||
await call.edit(self.strings("done"))
|
||||
|
||||
async def create(self, call: InlineCall, text: str):
|
||||
channel = await self.client(
|
||||
CreateChannelRequest(f"{text}", f"{text}", megagroup=False)
|
||||
)
|
||||
channel_id = channel.__dict__["chats"][0].__dict__["id"]
|
||||
channel_hash = channel.__dict__["chats"][0].__dict__["access_hash"]
|
||||
try:
|
||||
await self.client(
|
||||
UpdateUsernameRequest(
|
||||
InputPeerChannel(channel_id=channel_id,
|
||||
access_hash=channel_hash),
|
||||
text,
|
||||
)
|
||||
)
|
||||
await call.edit(self.strings("created").format(text))
|
||||
except:
|
||||
await call.edit(
|
||||
self.strings("tg_bug"),
|
||||
)
|
||||
await self.client.delete_dialog(channel_id)
|
||||
|
||||
async def create_inline(self, call: InlineCall, text: str):
|
||||
channel = await self.client(
|
||||
CreateChannelRequest(f"{text}", f"{text}", megagroup=False)
|
||||
)
|
||||
channel_id = channel.__dict__["chats"][0].__dict__["id"]
|
||||
channel_hash = channel.__dict__["chats"][0].__dict__["access_hash"]
|
||||
try:
|
||||
await self.client(
|
||||
UpdateUsernameRequest(
|
||||
InputPeerChannel(channel_id=channel_id,
|
||||
access_hash=channel_hash),
|
||||
text,
|
||||
)
|
||||
)
|
||||
await call.answer(self.strings("created").format(text))
|
||||
await call.delete()
|
||||
except:
|
||||
await call.answer(
|
||||
self.strings("tg_bug"),
|
||||
show_alert=True
|
||||
)
|
||||
await self.client.delete_dialog(channel_id)
|
||||
await call.delete()
|
||||
|
||||
async def delete(self, call: InlineCall):
|
||||
await call.delete()
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
|
||||
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
|
||||
|
||||
# 🔒 Licensed under the GNU GPLv3
|
||||
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
|
||||
# 👤 https://t.me/hikamoru
|
||||
|
||||
|
||||
# required: aiohttp
|
||||
# meta banner: https://github.com/AmoreForever/shizuassets/blob/master/wakatime.jpg?raw=true
|
||||
|
||||
# meta developer: @hikamorumods
|
||||
|
||||
import asyncio
|
||||
import aiohttp
|
||||
|
||||
from .. import utils, loader
|
||||
|
||||
|
||||
@loader.tds
|
||||
class Wakatime(loader.Module):
|
||||
"""Show your Wakatime stats"""
|
||||
|
||||
strings = {
|
||||
"name": "Wakatime",
|
||||
"set_waka": "Set your Wakatime token",
|
||||
"no_token": "🚫 <b>You don't have a token</b>",
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.config = loader.ModuleConfig(
|
||||
"WAKATIME_TOKEN",
|
||||
None,
|
||||
lambda: self.strings["set_waka"],
|
||||
)
|
||||
|
||||
@loader.command()
|
||||
async def waka(self, message):
|
||||
"""See your stat"""
|
||||
token = self.config["WAKATIME_TOKEN"]
|
||||
|
||||
if token is None:
|
||||
return await utils.answer(message, self.strings("no_token"))
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
endpoints = [
|
||||
"status_bar/today",
|
||||
"stats/all_time",
|
||||
"stats/all_time",
|
||||
"all_time_since_today",
|
||||
]
|
||||
tasks = [
|
||||
session.get(
|
||||
f"https://wakatime.com/api/v1/users/current/{endpoint}?api_key={token}"
|
||||
)
|
||||
for endpoint in endpoints
|
||||
]
|
||||
responses = await asyncio.gather(*tasks)
|
||||
results = await asyncio.gather(*[response.json() for response in responses])
|
||||
|
||||
result_t, result, result_s, result_w = results
|
||||
|
||||
all_time = result_w["data"]["text"]
|
||||
username = result["data"]["username"]
|
||||
languages = result["data"]["languages"]
|
||||
today = result_t["data"]["categories"]
|
||||
os = result["data"]["operating_systems"]
|
||||
editor = result["data"]["editors"]
|
||||
|
||||
OS = ", ".join(f"<code>{stat['name']}</code>" for stat in os if stat["text"] != "0 secs")
|
||||
EDITOR = ", ".join(f"<code>{stat['name']}</code>" for stat in editor if stat["text"] != "0 secs")
|
||||
LANG = "\n".join(f"▫️ <b>{stat['name']}</b>: <i>{stat['text']}</i>" for stat in languages if stat["text"] != "0 secs")
|
||||
TODAY = "\n".join(stat["text"] for stat in today if stat["text"] != "0 secs")
|
||||
|
||||
await utils.answer(
|
||||
message,
|
||||
f"👤 <b>Username:</b> <code>{username}</code>\n🖥 <b>OS:</b> {OS}\n🌀 <b>Editor:</b> {EDITOR}\n⏳ <b>All time</b>: <code>{all_time}</code>\n💼 <b>Today</b>: <code>{TODAY}</code>\n\n🧬 LANGUAGES\n\n{LANG}\n",
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": "🔄 Update",
|
||||
"callback": self.update_waka,
|
||||
}
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
async def update_waka(self, call):
|
||||
await call.edit("🔄 <b>Updating...</b>")
|
||||
token = self.config["WAKATIME_TOKEN"]
|
||||
if token is None:
|
||||
return await call.edit(self.strings("no_token"))
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
endpoints = [
|
||||
"status_bar/today",
|
||||
"stats/all_time",
|
||||
"stats/all_time",
|
||||
"all_time_since_today",
|
||||
]
|
||||
tasks = [
|
||||
session.get(
|
||||
f"https://wakatime.com/api/v1/users/current/{endpoint}?api_key={token}"
|
||||
)
|
||||
for endpoint in endpoints
|
||||
]
|
||||
responses = await asyncio.gather(*tasks)
|
||||
results = await asyncio.gather(*[response.json() for response in responses])
|
||||
|
||||
result_t, result, result_s, result_w = results
|
||||
|
||||
all_time = result_w["data"]["text"]
|
||||
username = result["data"]["username"]
|
||||
languages = result["data"]["languages"]
|
||||
today = result_t["data"]["categories"]
|
||||
os = result["data"]["operating_systems"]
|
||||
editor = result["data"]["editors"]
|
||||
|
||||
OS = ", ".join(f"<code>{stat['name']}</code>" for stat in os if stat["text"] != "0 secs")
|
||||
EDITOR = ", ".join(f"<code>{stat['name']}</code>" for stat in editor if stat["text"] != "0 secs")
|
||||
LANG = "\n".join(f"▫️ <b>{stat['name']}</b>: <i>{stat['text']}</i>" for stat in languages if stat["text"] != "0 secs")
|
||||
TODAY = "\n".join(stat["text"] for stat in today if stat["text"] != "0 secs")
|
||||
|
||||
await call.edit(
|
||||
f"👤 <b>Username:</b> <code>{username}</code>\n🖥 <b>OS:</b> {OS}\n🌀 <b>Editor:</b> {EDITOR}\n⏳ <b>All time</b>: <code>{all_time}</code>\n💼 <b>Today</b>: <code>{TODAY}</code>\n\n🧬 LANGUAGES\n\n{LANG}\n",
|
||||
reply_markup=[
|
||||
[
|
||||
{
|
||||
"text": "🔄 Update",
|
||||
"callback": self.update_waka,
|
||||
}
|
||||
]
|
||||
],
|
||||
)
|
||||
121
CakesTwix/Hikka-Modules/.gitignore
vendored
121
CakesTwix/Hikka-Modules/.gitignore
vendored
@@ -1,121 +0,0 @@
|
||||
# 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/
|
||||
@@ -1,65 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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,
|
||||
)
|
||||
@@ -1,540 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,104 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,443 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,337 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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),
|
||||
)
|
||||
@@ -1,211 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,674 +0,0 @@
|
||||
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>.
|
||||
@@ -1,5 +0,0 @@
|
||||
# Friendly Telegram / GeekTG Modules
|
||||
|
||||
Channel - https://t.me/cakestwix_mods
|
||||
Author - @CakesTwix
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
|
||||
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,106 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,336 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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>Избранное <3</b> :", # < == <
|
||||
"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,
|
||||
)
|
||||
@@ -1,81 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,591 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,138 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,169 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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
|
||||
@@ -1,125 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,108 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
# 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()
|
||||
@@ -1,292 +0,0 @@
|
||||
"""
|
||||
|
||||
█▄▀ █ █░█░█ █ █▄░█ █ █▀▀ █▀▀ █▀█
|
||||
█░█ █ ▀▄▀▄▀ █ █░▀█ █ █▄▄ ██▄ █▀▄
|
||||
|
||||
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)
|
||||
)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,61 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,116 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,110 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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
|
||||
],
|
||||
)
|
||||
@@ -1,73 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,145 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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)
|
||||
@@ -1,137 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,512 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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"])
|
||||
@@ -1,144 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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()
|
||||
@@ -1,311 +0,0 @@
|
||||
"""
|
||||
|
||||
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
|
||||
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
|
||||
|
||||
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
62
D4n13l3k00/FTG-Modules/.gitignore
vendored
@@ -1,62 +0,0 @@
|
||||
# ---> 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
|
||||
4
D4n13l3k00/FTG-Modules/.vscode/settings.json
vendored
4
D4n13l3k00/FTG-Modules/.vscode/settings.json
vendored
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"python.pythonPath": "C:\\Users\\D4n13l3k00\\AppData\\Local\\Programs\\Python\\Python39\\python.exe",
|
||||
"python.analysis.typeCheckingMode": "off"
|
||||
}
|
||||
@@ -1,346 +0,0 @@
|
||||
# .------.------.------.------.------.------.------.------.------.------.
|
||||
# |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",
|
||||
)
|
||||
],
|
||||
)
|
||||
@@ -1,80 +0,0 @@
|
||||
# .------.------.------.------.------.------.------.------.------.------.
|
||||
# |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"))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user