Commited backup

This commit is contained in:
2025-07-10 21:02:34 +03:00
parent 952c1001e3
commit da0b80823e
1310 changed files with 254133 additions and 41 deletions

47
.gitignore vendored
View File

@@ -1,6 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*.py[cod]
*$py.class
# C extensions
@@ -46,7 +46,7 @@ htmlcov/
nosetests.xml
coverage.xml
*.cover
*.py.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
@@ -106,24 +106,17 @@ ipython_config.py
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
#pdm.lock
#pdm.toml
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
#pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
@@ -136,7 +129,6 @@ celerybeat.pid
# Environments
.env
.envrc
.venv
env/
venv/
@@ -175,33 +167,8 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
# refer to https://docs.cursor.com/context/ignore-files
.cursorignore
.cursorindexingignore
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
.pypirc

160
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,160 @@
stages:
- before
- update
- parse
- categories
- commit
- create_mr
- backup
- diff_after_merge
variables:
BRANCH_NAME: "update-submodules_${CI_COMMIT_SHA}"
REPO_URL: "git.vsecoder.dev/root/limoka.git"
GITLAB_TOKEN: $GITLAB_TOKEN
GIT_DEPTH: 0
image: python:3.9
before_run:
stage: before
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: on_success
- when: never
script:
- pip install requests
- git config --global user.email "gitlab_admin_9dee57@example.com"
- git config --global user.name "Administrator"
- git fetch origin
- git checkout main
- git remote set-url origin "https://oauth2:${GITLAB_TOKEN}@${REPO_URL}"
- echo "Синхронизируем main с origin/main..."
- git reset --hard origin/main
- echo "Удаляем ветку ${BRANCH_NAME} из удалённого репозитория..."
- git push origin --delete ${BRANCH_NAME} || echo "Ветка ${BRANCH_NAME} не существовала или не удалось удалить"
- echo "Удаляем локальную ветку ${BRANCH_NAME}, если она существует..."
- git branch -D ${BRANCH_NAME} || echo "Локальная ветка ${BRANCH_NAME} не существовала"
- git checkout -b ${BRANCH_NAME}
- echo "Создаём новую ветку ${BRANCH_NAME}..."
- git push origin ${BRANCH_NAME} --force || echo "Ошибка при создании ветки"
update_repos:
stage: update
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: on_success
- when: never
script:
- git checkout ${BRANCH_NAME}
- echo "Cloning and update repositories..."
- python3 clone_repos.py
- git add *
- git commit -m "Added and updated repositories $(date +'%Y-%m-%d %H:%M:%S')" || echo "No changes for commit"
- git remote set-url origin "https://oauth2:${GITLAB_TOKEN}@${REPO_URL}"
- git push origin ${BRANCH_NAME} --force
parse:
stage: parse
rules:
- if: '($CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_EVENT_TYPE == "merged") || $CI_COMMIT_BRANCH == "main"'
when: on_success
- when: never
script:
- echo "Запускаем parse после мержа MR..."
- git fetch origin
- git checkout main
- git reset --hard origin/main
- python3 parse.py
- python3 -m venv venv
- source venv/bin/activate
- pip install --upgrade pip
- pip install scikit-learn tqdm
- python3 categories.py
- git add modules.json
- git commit -m "Updated modules.json after merge $(date +'%Y-%m-%d %H:%M:%S')" || echo "No changes for modules.json"
- git remote set-url origin "https://oauth2:${GITLAB_TOKEN}@${REPO_URL}"
- git push origin main
commit_changes:
stage: commit
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: on_success
- when: never
script:
- git checkout ${BRANCH_NAME}
- git add * || echo "No changes"
- git commit -m "Финальный коммит $(date +'%Y-%m-%d %H:%M:%S')" || echo "No changes for final commit"
- git remote set-url origin "https://oauth2:${GITLAB_TOKEN}@${REPO_URL}"
- git push origin ${BRANCH_NAME} --force
create_merge_request:
stage: create_mr
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: on_success
- when: never
script:
- echo "Checking branch status before MR..."
- git fetch origin
- git log ${BRANCH_NAME} -1
- git diff origin/main origin/${BRANCH_NAME} || echo "No diff between main and ${BRANCH_NAME}"
- echo "Creating Merge Request..."
- |
curl --request POST \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
--data "source_branch=${BRANCH_NAME}" \
--data "target_branch=main" \
--data "title=Update of repositories $(date +'%Y-%m-%d %H:%M:%S')" \
"https://git.vsecoder.dev/api/v4/projects/root%2Flimoka/merge_requests" \
|| echo "MR creating failure"
backup:
stage: backup
needs: ["parse"]
script:
- echo "$TELEGRAM_BOT_TOKEN"
- echo "Creating .zip file of the repository with maximum compression..."
- git archive --format=zip --output=$CI_PROJECT_DIR/repository-original.zip HEAD
- zip -9 $CI_PROJECT_DIR/repository.zip $CI_PROJECT_DIR/repository-original.zip
- rm $CI_PROJECT_DIR/repository-original.zip
- echo "File size of the created .zip file:"
- du -sh $CI_PROJECT_DIR/repository.zip
- echo "Splitting the .zip file into 8 parts..."
- split -b 49M $CI_PROJECT_DIR/repository.zip $CI_PROJECT_DIR/repository-part-
- echo "Files created after split:"
- ls $CI_PROJECT_DIR/repository-part-*
- |
COMMIT_MESSAGE="$(git log -1 --pretty=%B)"
COMMIT_DATE="$(date --date="$(git log -1 --pretty=%ci)" +'%Y-%m-%d %H:%M:%S')"
COMMIT_HASH="$(git rev-parse --short=6 HEAD)"
COMMIT_URL="https://git.vsecoder.dev/root/limoka/commit/$(git rev-parse HEAD)"
MESSAGE="Commit Date: $COMMIT_DATE, Commit Message: $COMMIT_MESSAGE, Commit Hash: [\`$COMMIT_HASH\`]($COMMIT_URL)"
echo "Sending .zip file parts to Telegram..."
FIRST_PART=true
for part in $(ls $CI_PROJECT_DIR/repository-part-* | sort); do
if $FIRST_PART; then
TELEGRAM_API_URL="https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendDocument"
echo "Отправка первого файла на Telegram: $TELEGRAM_API_URL"
curl -X POST "$TELEGRAM_API_URL" \
-F chat_id=$TELEGRAM_CHAT_ID \
-F document=@$part \
-F caption="$MESSAGE" \
-F parse_mode="Markdown"
FIRST_PART=false
else
TELEGRAM_API_URL="https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendDocument"
echo "Отправка файла на Telegram: $TELEGRAM_API_URL"
curl -X POST "$TELEGRAM_API_URL" \
-F chat_id=$TELEGRAM_CHAT_ID \
-F document=@$part
fi
done
- echo "Files sent to Telegram successfully!"
only:
- main

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,3 @@
![amoremods](https://te.legra.ph/file/8600de18766a556b2f78e.jpg)
# amoremods
My mods for userbot

View File

@@ -0,0 +1,53 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,33 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,287 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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())

View File

@@ -0,0 +1,225 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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("Не найдено!")

View File

@@ -0,0 +1,118 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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}")

View File

@@ -0,0 +1,258 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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"]},
)

View File

@@ -0,0 +1,473 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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

View File

@@ -0,0 +1,283 @@
# 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"
),
)

View File

@@ -0,0 +1,124 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,229 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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"))

View File

@@ -0,0 +1,100 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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}],
]
)

View File

@@ -0,0 +1,158 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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))

View File

@@ -0,0 +1,73 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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,
)

View File

@@ -0,0 +1,48 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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,
)

View File

@@ -0,0 +1,67 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,48 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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"))

View File

@@ -0,0 +1,37 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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>")

View File

@@ -0,0 +1,40 @@
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

View File

@@ -0,0 +1,91 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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()

View File

@@ -0,0 +1,69 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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()

View File

@@ -0,0 +1,129 @@
# ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠛⠛
# ⣶⣦⣤⣤⣤⣤⣤⣤⣬⣭⣭⣍⣉⡙⠛⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⣋⣩⣭⣥⣤⣴⣶⣶⣶⣶⣶⣶⣶⣶⣶
# ⣆⠀⠀⠀⢡⠁⠀⡀⠀⢸⠟⠻⣯⠙⠛⠷⣶⣬⡙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢉⣥⣶⡟⠻⣙⡉⠀⢰⡆⠀⠀⣡⠀⣧⠀⠀⠀⢨
# ⠻⣦⠀⠀⠈⣇⣀⣧⣴⣿⣶⣶⣿⣷⠀⢀⡇⠉⠻⢶⣌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⡶⠟⠉⠀⢣⠀⣿⠷⠀⠀⠀⠀⣿⡷⢀⠇⠀⠀⢠⣿
# ⣦⡈⢧⡀⠀⠘⢮⡙⠛⠉⠀⠄⠙⢿⣀⠞⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠈⠳⣄⠉⠓⠒⠚⠋⢀⡠⠋⠀⢀⣴⣏⣿
# ⣿⣿⣿⣛⣦⣀⠀⠙⠓⠦⠤⣤⠔⠛⠁⠀⠀⠀⠀⠀⢀⣀⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣤⣤⣤⣀⣀⣀⣀⢙⢓⣒⡒⠚⠋⢠⣤⢶⣟⣽⣿⣿
# ⣿⣿⣿⣿⣿⣿⣷⣦⠀⠀⣴⣿⣷⣶⣶⣶⣾⡖⢰⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣾⣿⣿⣶⣾⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣿⣿⣿⣿⣿⣿⣿⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⡏⠀⢸⣿⣿⣿⣿⣿⣿⣿⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⣷⠀⢸⣿⣿⣿⣿⣿⣿⣿⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# 🔒 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>")

View File

@@ -0,0 +1,83 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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,
}

View File

@@ -0,0 +1,57 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,355 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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_,
},
]
],
)

View File

@@ -0,0 +1,155 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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",
)

View File

@@ -0,0 +1,249 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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))
)

View File

@@ -0,0 +1,27 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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]}")

View File

@@ -0,0 +1,296 @@
__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"]},
)

View File

@@ -0,0 +1,31 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,62 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,88 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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

View File

@@ -0,0 +1,80 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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")

View File

@@ -0,0 +1,34 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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}"}
),
)

View File

@@ -0,0 +1,94 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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)

View File

@@ -0,0 +1,70 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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

View File

@@ -0,0 +1,98 @@
# ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⠿⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠛⠛
# ⣶⣦⣤⣤⣤⣤⣤⣤⣬⣭⣭⣍⣉⡙⠛⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠛⣋⣩⣭⣥⣤⣴⣶⣶⣶⣶⣶⣶⣶⣶⣶
# ⣆⠀⠀⠀⢡⠁⠀⡀⠀⢸⠟⠻⣯⠙⠛⠷⣶⣬⡙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢉⣥⣶⡟⠻⣙⡉⠀⢰⡆⠀⠀⣡⠀⣧⠀⠀⠀⢨
# ⠻⣦⠀⠀⠈⣇⣀⣧⣴⣿⣶⣶⣿⣷⠀⢀⡇⠉⠻⢶⣌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣡⡶⠟⠉⠀⢣⠀⣿⠷⠀⠀⠀⠀⣿⡷⢀⠇⠀⠀⢠⣿
# ⣦⡈⢧⡀⠀⠘⢮⡙⠛⠉⠀⠄⠙⢿⣀⠞⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀⠈⠳⣄⠉⠓⠒⠚⠋⢀⡠⠋⠀⢀⣴⣏⣿
# ⣿⣿⣿⣛⣦⣀⠀⠙⠓⠦⠤⣤⠔⠛⠁⠀⠀⠀⠀⠀⢀⣀⣹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣤⣤⣤⣀⣀⣀⣀⢙⢓⣒⡒⠚⠋⢠⣤⢶⣟⣽⣿⣿
# ⣿⣿⣿⣿⣿⣿⣷⣦⠀⠀⣴⣿⣷⣶⣶⣶⣾⡖⢰⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣶⣾⣿⣿⣶⣾⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⣿⠀⢀⣿⣿⣿⣿⣿⣿⣿⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⡏⠀⢸⣿⣿⣿⣿⣿⣿⣿⠁⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# ⣿⣿⣿⣿⣿⣿⣿⣷⠀⢸⣿⣿⣿⣿⣿⣿⣿⠀⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
# 🔒 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 ✨")

View File

@@ -0,0 +1,214 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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()

View File

@@ -0,0 +1,134 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 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,
}
]
],
)

View File

@@ -0,0 +1,51 @@
name: Generate Index Page
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
- name: Generate index.html
run: |
cat <<EOF > index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H:Mods</title>
<link type=text/css href="https://github.com/C0dwiz/H.Modules/raw/assets/style.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<h1>H:Mods modules</h1>
<ul class="module-list">
$(for file in *.py; do echo " <li class="module-item"><a href=\"$file\" class="module-link">$file</a></li>"; done)
</ul>
</div>
</body>
</html>
EOF
- name: Deploy to GitHub Pages
uses: JamesIves/github-pages-deploy-action@v4
with:
branch: main
folder: .

4
C0dwiz/H.Modules/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
full.py
# Ruff Format
.ruff_cache/

View File

@@ -0,0 +1,133 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: ASCIIArt
# Description: Converting images to ASCII art
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: ASCIIArt
# scope: ASCIIArt 0.0.1
# requires: pillow
# ---------------------------------------------------------------------------------
import os
import tempfile
from PIL import Image
from .. import loader, utils
@loader.tds
class ASCIIArtMod(loader.Module):
"""Converting images to ASCII art"""
strings = {
"name": "ASCIIArt",
"no_media_reply": "<b>Please reply to the image!</b>",
"loading": "<emoji document_id=5116240346656801621>❓</emoji> <b>Converting an image to ASCII...</b>",
"error": "<emoji document_id=5121063440311386962>👎</emoji> <b>Error when converting an image.</b>",
"done": "<emoji document_id=5123163417326126159>✅</emoji> <b>Here is your ASCII art:</b>",
}
strings_ru = {
"no_media_reply": "<b>Пожалуйста, ответьте на изображение!</b>",
"loading": "<emoji document_id=5116240346656801621>❓</emoji> <b>Конвертирую изображение в ASCII...</b>",
"error": "<emoji document_id=5121063440311386962>👎</emoji> <b>Ошибка при конвертации изображения.</b>",
"done": "<emoji document_id=5123163417326126159>✅</emoji> <b>Вот ваш ASCII-арт:</b>",
}
@loader.command(
ru_doc="<реплай на изображение> сделать ascii art",
en_doc="<replay on image> make ascii art",
)
async def cascii(self, message):
reply = await message.get_reply_message()
if not self._is_image(reply):
await utils.answer(message, self.strings("no_media_reply"))
return
await utils.answer(message, self.strings("loading"))
ascii_art = await self._generate_ascii_art(reply)
if ascii_art:
await self._send_ascii_file(message, ascii_art)
await message.delete()
else:
await utils.answer(message, self.strings("error"))
def _is_image(self, reply):
"""Проверка, является ли ответ изображением"""
return reply and (
reply.photo
or (reply.document and reply.file.mime_type.startswith("image/"))
)
async def _generate_ascii_art(self, reply):
"""Генерирует ASCII-арт из изображения"""
try:
image_path = await reply.download_media(tempfile.gettempdir())
if not image_path:
return None
with Image.open(image_path) as img:
img = img.convert("L")
img = img.resize(self._get_new_dimensions(img), Image.NEAREST)
chars = "@#S%?*+;:,. "
pixels = img.getdata()
ascii_str = "".join(chars[pixel // 25] for pixel in pixels)
return "\n".join(
ascii_str[i : i + img.width]
for i in range(0, len(ascii_str), img.width)
)
except Exception as e:
print(f"Error generating ASCII art: {e}")
return None
finally:
if image_path and os.path.exists(image_path):
os.remove(image_path)
def _get_new_dimensions(self, img):
"""Получаем новые размеры для изображения"""
new_width = 100
aspect_ratio = img.height / img.width
new_height = int(aspect_ratio * new_width * 0.55)
return new_width, new_height
async def _send_ascii_file(self, message, ascii_art):
"""Сохраняет ASCII-арт во временный файл и отправляет его"""
try:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", suffix=".txt", delete=False
) as tmp_file:
tmp_file_path = tmp_file.name
tmp_file.write(ascii_art)
await message.client.send_file(
message.chat_id,
tmp_file_path,
caption=self.strings("done"),
force_document=True,
reply_to=getattr(message, "reply_to_msg_id", None),
)
finally:
if tmp_file_path and os.path.exists(tmp_file_path):
os.remove(tmp_file_path)

View File

@@ -0,0 +1,65 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: AccountData
# Description: Find out the approximate date of registration of the telegram account
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api AccountData
# scope: Api AccountData 0.0.1
# ---------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class AccountData(loader.Module):
"""Find out the approximate date of registration of the telegram account"""
strings = {
"name": "AccountData",
"date_text": "<emoji document_id=5983150113483134607>⏰️</emoji> Date of registration of this account: {data}",
"date_text_ps": "<emoji document_id=6028435952299413210></emoji> The registration date is approximate, as it is almost impossible to know for sure",
"no_reply": "<emoji document_id=6030512294109122096>💬</emoji> You did not reply to the user's message",
}
strings_ru = {
"date_text": "<emoji document_id=5983150113483134607>⏰️</emoji> Дата регистрации этого аккаунта: {data}",
"date_text_ps": "<emoji document_id=6028435952299413210></emoji> Дата регистрации примерная, так как точно узнать практически невозможно",
"no_reply": "<emoji document_id=6030512294109122096>💬</emoji> Вы не ответили на сообщение пользователя",
}
async def client_ready(self, client, db):
self.hmodslib = await self.import_lib(
"https://raw.githubusercontent.com/C0dwiz/H.Modules/refs/heads/main-fix/HModsLibrary.py"
)
@loader.command(
ru_doc="Узнать примерную дату регистрации аккаунта телеграмм",
en_doc="Find out the approximate date of registration of the telegram account",
)
async def accdata(self, message):
if reply := await message.get_reply_message():
data = await self.hmodslib.get_creation_date(reply.from_id)
await utils.answer(
message,
f"{self.strings('date_text').format(data=data)}\n\n{self.strings('date_text_ps')}",
)
else:
await utils.answer(message, self.strings("no_reply"))

View File

@@ -0,0 +1,188 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: AniLibria
# Description: Searches and gives random agtme on the AniLibria database.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: AniLibria
# scope: AniLibria 0.0.1
# requires: git+https://github.com/C0dwiz/anilibria.py.git
# ---------------------------------------------------------------------------------
from ..inline.types import InlineQuery
from aiogram.types import InlineQueryResultPhoto, CallbackQuery
from anilibria import AniLibriaClient
from .. import loader
ani_client = AniLibriaClient()
@loader.tds
class AniLibriaMod(loader.Module):
"""Searches and gives random agtme on the AniLibria database."""
strings = {
"name": "AniLibria",
"announce": "<b>The announcement</b>:",
"status": "<b>Status</b>:",
"type": "<b>Type</b>:",
"genres": "<b>Genres</b>:",
"favorite": "<b>Favourites &lt;3</b>:", # &lt; == <
"season": "<b>Season</b>:",
}
strings_ru = {
"announce": "<b>Анонс</b>:",
"status": "<b>Статус</b>:",
"type": "<b>Тип</b>:",
"genres": "<b>Жанры</b>:",
"favorite": "<b>Избранное &lt;3</b>:", # &lt; == <
"season": "<b>Сезон</b>:",
}
link = "https://anilibria.tv"
@loader.command(
ru_doc="Возвращает случайный тайтл из базы",
en_doc="Returns a random title from the database",
)
async def arandom(self, message) -> None:
anime_title = await ani_client.get_random_title()
text = f"{anime_title.names.ru} \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}\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",
}
]
]
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__update}])
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await self.inline.form(
text=text,
photo=self.link + anime_title.posters.original.url,
message=message,
reply_markup=kb,
silent=True,
)
@loader.inline_handler(
ru_doc="Возвращает список найденных по названию тайтлов",
en_doc="Returns a list of titles found by name",
)
async def asearch_inline_handler(self, query: InlineQuery) -> None:
text = query.args
if not text:
return
anime_titles = await ani_client.search_titles(search=text)
inline_query = []
for anime_title in anime_titles:
title_text = (
f"{anime_title.names.ru} | {anime_title.names.en}\n"
f"{self.strings['status']} {anime_title.status.string}\n\n"
f"{self.strings['type']} {anime_title.type.full_string}\n"
f"{self.strings['season']} {anime_title.season.string} {anime_title.season.year}\n"
f"{self.strings['genres']} {' '.join(anime_title.genres)}\n\n"
f"<code>{anime_title.description}</code>\n\n"
f"{self.strings['favorite']} {anime_title.in_favorites}"
)
inline_query.append(
InlineQueryResultPhoto(
id=str(anime_title.code),
title=anime_title.names.ru,
description=anime_title.type.full_string,
caption=title_text,
thumb_url=self.link + anime_title.posters.small.url,
photo_url=self.link + anime_title.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__update(self, call: CallbackQuery) -> None:
anime_title = await ani_client.get_random_title()
text = (
f"{anime_title.names.ru} \n"
f"{self.strings['status']} {anime_title.status.string}\n\n"
f"{self.strings['type']} {anime_title.type.full_string}\n"
f"{self.strings['season']} {anime_title.season.string}\n"
f"{self.strings['genres']} {' '.join(anime_title.genres)}\n\n"
f"<code>{anime_title.description}</code>\n\n"
f"{self.strings['favorite']} {anime_title.in_favorites}"
)
kb = [
[
{
"text": "Ссылка",
"url": f"https://anilibria.tv/release/{anime_title.code}.html",
}
]
]
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__update}])
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await call.edit(
text=text,
photo=self.link + anime_title.posters.original.url,
reply_markup=kb,
)

View File

@@ -0,0 +1,81 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: AnimeQuotes
# Description: A module for sending random quotes from anime
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: AnimeQuotes
# scope: AnimeQuotes 0.0.1
# requires: requests
# ---------------------------------------------------------------------------------
import aiohttp
from .. import loader, utils
@loader.tds
class AnimeQuotesMod(loader.Module):
"""A module for sending random quotes from anime"""
strings = {
"name": "AnimeQuotes",
"quote_template": (
'<b>Quote:</b> "{quote}"\n\n'
"<b>Character:</b> {character}\n"
"<b>Anime:</b> {anime}"
),
"error": "<b>Couldn't get a quote. Try again later!</b>",
}
strings_ru = {
"quote_template": (
'<b>Цитата:</b> "{quote}"\n\n'
"<b>Персонаж:</b> {character}\n"
"<b>Аниме:</b> {anime}"
),
"error": "<b>Не удалось получить цитату. Попробуйте позже!</b>",
}
@loader.command(
ru_doc="Получить случайную цитату из аниме",
en_doc="Get a random quote from the anime",
)
async def quote(self, message):
url = "https://api.animechan.io/v1/quotes/random"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
data = await response.json()
quote_content = data["data"]["content"]
character_name = data["data"]["character"]["name"]
anime_name = data["data"]["anime"]["name"]
quote = self.strings["quote_template"].format(
quote=quote_content, character=character_name, anime=anime_name
)
await utils.answer(message, quote)
except aiohttp.ClientError:
await utils.answer(message, self.strings["error"])

View File

@@ -0,0 +1,73 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: Article
# Description: Displays your article Criminal Code of the Russian Federation
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Article
# scope: Article 0.0.1
# requires: requests
# ---------------------------------------------------------------------------------
import requests
import json
import random
from typing import Dict
from .. import loader, utils
@loader.tds
class ArticleMod(loader.Module):
"""Displays your article Criminal Code of the Russian Federation"""
strings = {
"name": "Article",
"article": "<emoji document_id=5226512880362332956>📖</emoji> <b>Your article of the Criminal Code of the Russian Federation</b>:\n\n<blockquote>Number {}\n\n{}</blockquote>",
}
strings_ru = {
"article": "<emoji document_id=5226512880362332956>📖</emoji> <b>Твоя статья УК РФ</b>:\n\n<blockquote>Номер {}\n\n{}</blockquote>",
}
@loader.command(
ru_doc="Отображается ваша статья Уголовного кодекса Российской Федерации",
en_doc="Displays your article Criminal Code of the Russian Federation",
)
async def arccmd(self, message):
if values := self._load_values():
random_key = random.choice(list(values.keys()))
random_value = values[random_key]
await utils.answer(
message, self.strings("article").format(random_key, random_value)
)
def _load_values(self) -> Dict[str, str]:
url = "https://raw.githubusercontent.com/Codwizer/ReModules/main/assets/zakon.json"
try:
response = requests.get(url)
if response.ok:
data = json.loads(response.text)
return data
except (requests.RequestException, json.JSONDecodeError):
pass
return {}

View File

@@ -0,0 +1,204 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: AutofarmCookies
# Description: Autofarm in the bot @cookies_game_bot
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: AutofarmCookies
# scope: AutofarmCookies 0.0.1
# ---------------------------------------------------------------------------------
import random
from datetime import timedelta
from telethon import functions
from .. import loader, utils
__version__ = (1, 0, 0)
@loader.tds
class AutofarmCookiesMod(loader.Module):
"""Autofarm in the bot @cookies_game_bot"""
strings = {
"name": "AutofarmCookies",
"farmon": (
"<i>The deferred task has been created, autofarming has been started, everything will start in 10 minutes"
" seconds...</i>"
),
"farmon_already": "<i>It has already been launched :)</i>",
"farmoff": "<i>The autopharm is stopped\nSelected:</i> <b>%coins% Cookies</b>",
"farm": "<i>I typed:</i> <b>%coins% Cookies</b>",
}
strings_ru = {
"farmon": (
"<i>Отложенная задача создана, автофарминг запущен, всё начнётся через 10"
" секунд...</i>"
),
"farmon_already": "<i>Уже запущено :)</i>",
"farmoff": "<i>Автофарм остановлен.\nНвброно:</i> <b>%coins% Cookies</b>",
"farm": "<i>Я набрал:</i> <b>%coins% Cookies</b>",
}
def __init__(self):
self.name = self.strings["name"]
async def client_ready(self, client, db):
self.client = client
self.db = db
self.myid = (await client.get_me()).id
self.cookies = "@cookies_game_bot"
@loader.command(
ru_doc="Запустить автофарминг",
en_doc="Launch auto-farming",
)
async def cookon(self, message):
status = self.db.get(self.name, "status", False)
if status:
return await message.edit(self.strings["farmon_already"])
self.db.set(self.name, "status", True)
await self.client.send_message(
self.cookies, "/cookie", schedule=timedelta(seconds=10)
)
await message.edit(self.strings["farmon"])
@loader.command(
ru_doc="Остановить автофарминг",
en_doc="Stop auto-farming",
)
async def cookoff(self, message):
self.db.set(self.name, "status", False)
coins = self.db.get(self.name, "coins", 0)
if coins:
self.db.set(self.name, "coins", 0)
await message.edit(self.strings["farmoff"].replace("%coins%", str(coins)))
@loader.command(
ru_doc="Вывод кол-ва коинов, добытых этим модулем",
en_doc="Output of the number of coins mined by this module",
)
async def cookies(self, message):
coins = self.db.get(self.name, "coins", 0)
await message.edit(self.strings["farm"].replace("%coins%", str(coins)))
async def watcher(self, event):
if not isinstance(event, Message): # noqa: F821
return
chat = utils.get_chat_id(event)
if chat != self.cookies:
return
status = self.db.get(self.name, "status", False)
if not status:
return
if event.raw_text == "/cookie":
return await self.client.send_message(
self.cookies, "/cookie", schedule=timedelta(hours=2)
)
if event.sender_id != self.cookies:
return
if "🙅‍♂️!" in event.raw_text:
args = [int(x) for x in event.raw_text.split() if x.isnumeric()]
randelta = random.randint(20, 60)
if len(args) == 4:
delta = timedelta(
hours=args[1], minutes=args[2], seconds=args[3] + randelta
)
elif len(args) == 3:
delta = timedelta(minutes=args[1], seconds=args[2] + randelta)
elif len(args) == 2:
delta = timedelta(seconds=args[1] + randelta)
else:
return
sch = (
await self.client(
functions.messages.GetScheduledHistoryRequest(self.cookies, 1488)
)
).messages
await self.client(
functions.messages.DeleteScheduledMessagesRequest(
self.cookies, id=[x.id for x in sch]
)
)
return await self.client.send_message(
self.cookies, "/cookie", schedule=delta
)
if "" in event.raw_text:
args = event.raw_text.split()
for x in args:
if x[0] == "+":
return self.db.set(
self.name,
"coins",
self.db.get(self.name, "coins", 0) + int(x[1:]),
)
async def message_q(
self,
text: str,
user_id: int,
mark_read: bool = False,
delete: bool = False,
):
async with self.client.conversation(user_id) as conv:
msg = await conv.send_message(text)
response = await conv.get_response()
if mark_read:
await conv.mark_read()
if delete:
await msg.delete()
await response.delete()
return response
@loader.command(
ru_doc="Показывает ваш мешок",
en_doc="Shows your bag",
)
async def me(self, message):
bot = "@cookies_game_bot"
bags = await self.message_q(
"/me",
bot,
delete=True,
)
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, bags.text)
@loader.command(
ru_doc="Помощь по модулю AutofarmCookies",
en_doc="Help with the AutofarmCookies module",
)
async def ckies(self, message):
chelp = """
🍀| <b>Помощь по командам:</b>
.cookon - Включает авто фарм.
.cookoff - Выключает авто фарм.
.farm - Показывает сколько вы нафармили.
.me - Показывает ваш ммешок"""
await utils.answer(message, chelp)

View File

@@ -0,0 +1,242 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: BirthdayTime
# Description: Counting down to your birthday
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: BirthdayTime
# scope: Api BirthdayTime 0.0.1
# ---------------------------------------------------------------------------------
import random
import asyncio
import calendar
from datetime import datetime
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.errors.rpcerrorlist import UserPrivacyRestrictedError
from .. import loader, utils
D_MSG = [
"Ждешь его?",
"Осталось немного)",
"Дни пролетят, даже не заметишь",
"Уже знаешь что хочешь получить в подарок?)",
"Сколько исполняется?",
"Жду не дождусь уже",
]
@loader.tds
class DaysToMyBirthday(loader.Module):
"""Counting down to your birthday"""
strings = {
"name": "BirthdayTime",
"date_error": "<emoji document_id=5422840512681877946>❗️</emoji> <b>Your birthdate is not specified in the config, please correct this :)</b>",
"msg": (
"<emoji document_id=5377476217698001788>🎉</emoji> <b>"
"There are {} days, {} hours, {} minutes, and {} seconds left until your birthday. \n<emoji document_id=5377442914521588226>"
"💙</emoji> {}</b>"
),
"conf": "<i>Open config...</i>",
"name_changed": "<b>Name updated!</b>",
"name_not_changed": "<b>Name was not updated.</b>",
"name_privacy_error": "<b>Unable to change name due to privacy settings.</b>",
"error": "<b>An error occurred. Please check the logs.</b>",
}
strings_ru = {
"date_error": "<emoji document_id=5422840512681877946>❗️</emoji> <b>В конфиге не указан день вашего рождения, пожалуйста, исправь это :)</b>",
"msg": (
"<emoji document_id=5377476217698001788>🎉</emoji> <b>"
"До вашего дня рождения осталось {} дней, {} часов, {} "
"минут, {} секунд. \n<emoji document_id=5377442914521588226>"
"💙</emoji> {}</b>"
),
"conf": "<i>Открываю конфиг...</i>",
"btname_yes": (
"<b><emoji document_id=6327560044845991305>😶</emoji> Хорошо, теперь я "
"буду изменять ваше имя в зависимости от количества дней до дня рождения</b>"
),
"btname_no": "<emoji document_id=6325696222313055607>😶</emoji>Хорошо, я больше не буду изменять ваше имя",
"name_changed": "<b>Имя обновлено!</b>",
"name_not_changed": "<b>Имя не было обновлено.</b>",
"name_privacy_error": "<b>Не удалось изменить имя из-за настроек приватности.</b>",
"error": "<b>Произошла ошибка. Пожалуйста, проверьте логи.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"birthday_date",
None,
lambda: "Дата вашего рождения. Указывать только день",
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"birthday_month",
None,
"Месяц вашего рождения",
validator=loader.validators.Choice(
[
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
),
),
)
self._task = None
async def client_ready(self):
if self._task:
self._task.cancel()
self._task = asyncio.create_task(self.checker())
async def checker(self):
while True:
if not self.db.get(__name__, "change_name", False):
await asyncio.sleep(60)
continue
try:
now = datetime.now()
day = self.config["birthday_date"]
monthy = self.config["birthday_month"]
month = list(calendar.month_name).index(monthy)
birthday = datetime(now.year, month, day)
if now.month > month or (now.month == month and now.day > day):
birthday = datetime(now.year + 1, month, day)
time_to_birthday = abs(birthday - now)
days = time_to_birthday.days
user = await self.client(GetFullUserRequest(self.client.hikka_me.id))
if not user or not user.users:
await asyncio.sleep(60)
continue
name = user.users[0].last_name or ""
ln = f'{self.db.get(__name__, "last_name", "")}{days} d.'
if name == ln:
await asyncio.sleep(60)
continue
else:
await self.client(UpdateProfileRequest(last_name=ln))
self.db.set(__name__, "last_name", name)
except UserPrivacyRestrictedError:
self.db.set(__name__, "change_name", False)
print("Error: Can't change name due to privacy settings.")
except Exception as e:
print(f"Error in checker: {e}")
finally:
await asyncio.sleep(60)
@loader.command(
ru_doc="Выставить таймер дней в ник (нестабильно)",
en_doc="Set the timer of days in the nickname (unstable)",
)
async def btname(self, message):
try:
user = await self.client(GetFullUserRequest(self.client.hikka_me.id))
name = user.users[0].last_name or ""
except Exception as e:
print(f"Error getting user info: {e}")
await utils.answer(message, self.strings("error"))
return
self.db.set(__name__, "last_name", name)
change_name = self.db.get(__name__, "change_name", False)
if change_name:
self.db.set(__name__, "change_name", False)
await utils.answer(message, self.strings("btname_no"))
try:
await self.client(
UpdateProfileRequest(last_name=self.db.get(__name__, "last_name"))
)
await utils.answer(message, self.strings("name_not_changed"))
except UserPrivacyRestrictedError:
await utils.answer(message, self.strings("name_privacy_error"))
except Exception as e:
print(f"Error removing name: {e}")
await utils.answer(message, self.strings("error"))
else:
self.db.set(__name__, "change_name", True)
await utils.answer(message, self.strings("btname_yes"))
@loader.command(
ru_doc="Вывести таймер",
en_doc="Display the timer",
)
async def bt(self, message):
if (
self.config["birthday_date"] is None
or self.config["birthday_month"] is None
):
await utils.answer(message, self.strings("date_error"))
msg = await self.client.send_message(message.chat_id, self.strings("conf"))
await self.allmodules.commands["config"](
await utils.answer(msg, f"{self.get_prefix()}config BirthdayTime")
)
return
try:
now = datetime.now()
day = self.config["birthday_date"]
monthy = self.config["birthday_month"]
month = list(calendar.month_name).index(monthy)
birthday = datetime(now.year, month, day)
if now.month > month or (now.month == month and now.day > day):
birthday = datetime(now.year + 1, month, day)
time_to_birthday = abs(birthday - now)
await utils.answer(
message,
self.strings("msg").format(
time_to_birthday.days,
(time_to_birthday.seconds // 3600),
(time_to_birthday.seconds // 60 % 60),
(time_to_birthday.seconds % 60),
random.choice(D_MSG),
),
)
except Exception as e:
print(f"Error in bt command: {e}")
await utils.answer(message, self.strings("error"))

1
C0dwiz/H.Modules/CNAME Normal file
View File

@@ -0,0 +1 @@
mods.codwiz.life

View File

@@ -0,0 +1,53 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: CheckSpamBan
# Description: Check spam ban for your account.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: CheckSpamBan
# scope: CheckSpamBan 0.0.1
# ---------------------------------------------------------------------------------
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class SpamBanCheckMod(loader.Module):
"""Checks spam ban for your account."""
strings = {
"name": "CheckSpamBan",
}
@loader.command(
ru_doc="Проверяет вашу учетную запись на спам-бан с помощью бота @SpamBot",
en_doc="Checks your account for spam ban via @SpamBot bot",
)
async def spambot(self, message):
async with self.client.conversation(178220800) as conv:
user_message = await conv.send_message('/start')
await user_message.delete()
spam_message = await conv.get_response()
await utils.answer(message, spam_message.text)
await spam_message.delete()

View File

@@ -0,0 +1,107 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: CryptoCurrency
# Description: Module for displaying current cryptocurrency exchange rates.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api CryptoCurrency
# scope: Api CryptoCurrency 0.0.1
# ---------------------------------------------------------------------------------
import aiohttp
from .. import loader, utils
@loader.tds
class CryptoCurrencyMod(loader.Module):
"""Module for displaying current cryptocurrency exchange rates."""
strings = {
"name": "CryptoCurrency",
"query_missing": "Please specify a cryptocurrency ticker or name.",
"coin_not_found": "Cryptocurrency '{query}' not found.",
}
strings_ru = {
"query_missing": "Пожалуйста, укажите тикер или название криптовалюты.",
"coin_not_found": "Криптовалюта '{query}' не найдена.",
}
async def fetch_json(self, url):
"""Fetch JSON data from a given URL."""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
return await response.json()
async def get_exchange_rates(self):
"""Get exchange rates for RUB and EUR based on USD."""
data = await self.fetch_json("https://open.er-api.com/v6/latest/USD")
return data["rates"]["RUB"], data["rates"]["EUR"]
async def find_coin(self, query):
"""Find a cryptocurrency by its name or symbol."""
data = await self.fetch_json(
"https://api.coinlore.net/api/tickers/?start=0&limit=100"
)
return next(
(
item
for item in data["data"]
if query.lower() in item["name"].lower()
or query.lower() in item["symbol"].lower()
),
None,
)
@loader.command(
ru_doc="Отображает текущий курс криптовалюты в рублях, долларах США и евро",
en_doc="Displays the current cryptocurrency rate in RUB, USD, and EUR",
)
async def crypto(self, message):
query = utils.get_args_raw(message)
if not query:
return await utils.answer(message, self.strings("query_missing"))
coin = await self.find_coin(query)
if not coin:
return await utils.answer(
message, self.strings("coin_not_found").format(query=query)
)
price_usd = float(coin["price_usd"])
usd_rub_rate, usd_eur_rate = await self.get_exchange_rates()
price_rub = price_usd * usd_rub_rate
price_eur = price_usd * usd_eur_rate
response = self.format_response(coin, price_usd, price_rub, price_eur)
await utils.answer(message, response)
def format_response(self, coin, price_usd, price_rub, price_eur):
"""Format the response message with cryptocurrency information."""
return (
f"💰 {coin['name']} ({coin['symbol']})\n"
f"USD: ${price_usd:.2f}\n"
f"RUB: ₽{price_rub:.2f}\n"
f"EUR: €{price_eur:.2f}\n"
)

View File

@@ -0,0 +1,81 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: EnvsSH
# Description: Module for reuploading files to envs.sh
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api EnvsSH
# scope: Api EnvsSH 0.0.1
# requires: aiohttp
# ---------------------------------------------------------------------------------
import aiohttp
from .. import loader, utils # pylint: disable=relative-beyond-top-level
@loader.tds
class EnvsMod(loader.Module):
"""Module for reuploading files to envs.sh"""
strings = {
"name": "EnvsSH",
"connection_error": "🚫 Host is unreachable for now, try again later.",
"no_reply": "⚠️ <b>You must reply to a message with media</b>",
"success": "✅ URL for <code>{}</code>:\n\n<code>{}</code>",
"error": "❌ An error occurred:\n<code>{}</code>",
"uploading": "⏳ <b>Uploading {} ({}{})...</b>",
}
strings_ru = {
"connection_error": "🚫 Хост в настоящее время недоступен, попробуйте позже.",
"no_reply": "⚠️ <b>Вы должны ответить на сообщение с медиа</b>",
"success": "✅ URL для <code>{}</code>:\n\n<code>{}</code>",
"error": "❌ Произошла ошибка:\n<code>{}</code>",
"uploading": "⏳ <b>Загрузка {} ({}{})...</b>",
}
async def client_ready(self, client, db):
self.hmodslib = await self.import_lib('https://raw.githubusercontent.com/C0dwiz/H.Modules/refs/heads/main-fix/HModsLibrary.py')
async def envcmd(self, message):
"""Reupload to envs.sh."""
reply = await message.get_reply_message()
if not reply or not reply.media:
return await utils.answer(message, self.strings["no_reply"])
size_len, size_unit = self.hmodslib.convert_size(reply.file.size)
await utils.answer(
message,
self.strings["uploading"].format(reply.file.name, size_len, size_unit),
)
path = await self.client.download_media(reply)
try:
uploaded_url = await self.hmodslib.upload_to_envs(path)
except aiohttp.ClientConnectionError:
await utils.answer(message, self.strings["connection_error"])
except aiohttp.ClientResponseError as e:
await utils.answer(message, self.strings["error"].format(str(e)))
else:
await utils.answer(
message, self.strings["success"].format(path, uploaded_url)
)

View File

@@ -0,0 +1,88 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: FakeActions
# Description: Module for simulating various actions in chat
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api FakeActions
# scope: Api FakeActions 0.0.1
# ---------------------------------------------------------------------------------
import asyncio
from .. import loader, utils
@loader.tds
class FakeActionsMod(loader.Module):
"""Module for simulating various actions in chat"""
strings = {"name": "FakeActions"}
def __init__(self):
self.config = loader.ModuleConfig(
"DEFAULT_DURATION", 5, "Default duration for actions in seconds"
)
async def ftcmd(self, message):
"""<seconds> - Simulates typing in chat for the specified number of seconds."""
await self._simulate_action_command(message, "typing")
async def ffcmd(self, message):
"""<seconds> - Simulates sending a file."""
await self._simulate_action_command(message, "document")
async def fgcmd(self, message):
"""<seconds> - Simulates recording a voice message."""
await self._simulate_action_command(message, "record-audio")
async def fvgcmd(self, message):
"""<seconds> - Simulates recording a video message."""
await self._simulate_action_command(message, "record-round")
async def fpgcmd(self, message):
"""<seconds> - Simulates playing a game."""
await self._simulate_action_command(message, "game")
async def _simulate_action_command(self, message, action):
"""General function for handling action simulation commands."""
duration = self._parse_duration(message)
if duration is None:
await utils.answer(
message,
f"Usage: {self.get_prefix()}{message.raw_text.split()[0][1:]} <seconds>",
)
return
await message.delete()
await self._simulate_action(message, action, duration)
def _parse_duration(self, message):
"""Parse the duration from the message."""
args = message.raw_text.split()
if len(args) == 2 and args[1].isdigit():
return int(args[1])
return self.config["DEFAULT_DURATION"]
async def _simulate_action(self, message, action, duration):
"""Simulate the specified action in chat."""
async with message.client.action(message.chat_id, action):
await asyncio.sleep(duration)

View File

@@ -0,0 +1,176 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: FakeWallet
# Description: Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: hikka_only
# scope: hikka_min 1.4.2
# -----------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class FakeWallet(loader.Module):
"""Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet."""
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Toncoin",
0,
lambda: self.strings("ton"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tether",
0,
lambda: self.strings("tether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Bitcoin",
0,
lambda: self.strings("btc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Etherium",
0,
lambda: self.strings("ether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Binance",
0,
lambda: self.strings("binc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tron",
0,
lambda: self.strings("tron"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"USDT",
0,
lambda: self.strings("usdt"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Gram",
0,
lambda: self.strings("gram"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Litecoin",
0,
lambda: self.strings("lite"),
validator=loader.validators.Integer(),
),
)
strings = {
"name": "FakeWallet",
"crypto": "Enter a value for your cryptovalute",
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Wallet</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Enter a value for Toncoin",
"teth": "Enter a value for Tethcoin",
"btc": "Enter a value for Bitcoin",
"ether": "Enter a value for Etherium",
"binc": "Enter a value for Binance coin",
"tron": "Enter a value for Tron",
"usdt": "Enter a value for USDT coin",
"gram": "Enter a value for Gramcoin",
"lite": "Enter a value for Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i>Attention!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji>This module is strictly prohibited from being used for the purposes of <b>scam, fraud and advertising</b>.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji>The module is provided solely for entertainment purposes, and any violation of the <b>Rules for using the module</b>, if detected, will be subject <b>to appropriate punishment</i>",
}
strings_ru = {
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Кошелёк</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Введите количество валюты для Toncoin",
"teth": "Введите количество валюты для Tethcoin",
"btc": "Введите количество валюты для Bitcoin",
"ether": "Введите количество валюты для Etherium",
"binc": "Введите количество валюты для Binance coin",
"tron": "Введите количество валюты для Tron",
"usdt": "Введите количество валюты для USDT coin",
"gram": "Введите количество валюты для Gramcoin",
"lite": "Введите количество валюты для Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i> Внимание!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji> Использование этого модуля в целях <b>скама, обмана и рекламы</b> строго запрещено.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji> Модуль предоставлен исключительно в развлекательных целях, и любое нарушение <b>Правил использования модуля</b>, если его обнаружат, будет подлежать соответствующему наказанию.</i>",
}
@loader.command(
ru_doc="Чтобы заполучить поддельный кошелек",
en_doc="To get a fake wallet",
)
@loader.command()
async def fwalletcmd(self, message):
ton = self.config["Toncoin"]
teth = self.config["Tether"]
btc = self.config["Bitcoin"]
ether = self.config["Etherium"]
binc = self.config["Binance"]
tron = self.config["Tron"]
usdt = self.config["USDT"]
gram = self.config["Gram"]
lite = self.config["Litecoin"]
await utils.answer(
message,
self.strings("wallet").format(
ton, teth, btc, ether, binc, tron, usdt, gram, lite
),
)
@loader.command(
ru_doc="Информация о FakeModule",
en_doc="Info about FakeModule",
)
@loader.command()
async def fwinfocmd(self, message):
await utils.answer(message, self.strings("info"))

View File

@@ -0,0 +1,121 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: GigaChat
# Description: Module for using GigaChat
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api GigaChat
# scope: Api GigaChat 0.0.1
# ---------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class GigaChatMod(loader.Module):
"""Module for using GigaChat"""
strings = {
"name": "GigaChat",
"api_key_missing": "Please set the API key in the module configuration.",
"query_missing": "Please enter a query after the command.",
"response_error": "Failed to get a response from GigaChat.",
"error_occurred": "An error occurred: {}",
"formatted_response": (
"<emoji document_id=6030848053177486888>❓</emoji> Query: {}\n"
"<emoji document_id=6030400221232501136>🤖</emoji> GigaChat: {}"
),
"giga_model": "List of GigaChat models:\n{}",
}
strings_ru = {
"api_key_missing": "Пожалуйста, установите API ключ в конфигурации модуля.",
"query_missing": "Пожалуйста, введите запрос после команды.",
"response_error": "Не удалось получить ответ от GigaChat.",
"error_occurred": "Произошла ошибка: {}",
"formatted_response": (
"<emoji document_id=6030848053177486888>❓</emoji> Запрос: {}\n"
"<emoji document_id=6030400221232501136>🤖</emoji> GigaChat: {}"
),
"giga_model": "Список моделей GigaChat:\n{}",
}
async def client_ready(self, client, db):
self.hmodslib = await self.import_lib(
"https://raw.githubusercontent.com/C0dwiz/H.Modules/refs/heads/main-fix/HModsLibrary.py"
)
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"GIGACHAT_API_KEY",
None,
"Введите ваш API ключ для GigaChat, Чтобы получить ключ API, перейдите сюда: https://developers.sber.ru/studio/workspaces",
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
"GIGACHAT_MODEL",
"GigaChat",
"Введите модель, ее можно получить при команде .gigamodel",
),
)
@loader.command(
ru_doc="Получите исчерпывающий ответ на свой вопрос",
en_doc="Get GigaResponse to your question",
)
async def giga(self, message):
api_key = self.config["GIGACHAT_API_KEY"]
if not api_key:
return await utils.answer(message, self.strings("api_key_missing"))
query = utils.get_args_raw(message)
if not query:
return await utils.answer(message, self.strings("query_missing"))
try:
response = await self.hmodslib.get_giga_response(api_key, query)
if response:
await utils.answer(
message, self.strings("formatted_response").format(query, response)
)
else:
await utils.answer(message, self.strings("response_error"))
except Exception as e:
await utils.answer(message, self.strings("error_occurred").format(str(e)))
@loader.command(
ru_doc="Получить список моделей",
en_doc="Get a list of models",
)
async def gigamodel(self, message):
api_key = self.config["GIGACHAT_API_KEY"]
if not api_key:
return await utils.answer(message, self.strings("api_key_missing"))
try:
response = await self.hmodslib.get_giga_models(api_key)
if response:
await utils.answer(message, self.strings("giga_model").format(response))
else:
await utils.answer(message, self.strings("response_error"))
except Exception as e:
await utils.answer(message, self.strings("error_occurred").format(str(e)))

44
C0dwiz/H.Modules/H.py Normal file
View File

@@ -0,0 +1,44 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: H
# Description: H.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: H
# scope: H 0.0.1
# ---------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class H(loader.Module):
"""H"""
strings = {"name": "H", "h": "H"}
strings_ru = {"h": "H"}
@loader.command(
ru_doc="H",
)
async def h(self, message):
"""H"""
await utils.answer(message, self.strings("h"))

307
C0dwiz/H.Modules/HAFK.py Normal file
View File

@@ -0,0 +1,307 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: HAFK
# Description: Your personal assistant while you are in AFK mode
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: HAFK
# scope: HAFK 0.0.1
# ---------------------------------------------------------------------------------
import datetime
import logging
import time
import asyncio
from telethon import types
from telethon.utils import get_peer_id
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class HAFK(loader.Module):
strings = {
"name": "HAFK",
"afk_on": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK mode is on!</b>",
"afk_on_reason": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK mode is on!</b>\n\n<b>Reason:</b> <i>{}</i>",
"afk_here_on": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK mode is on in this chat!</b>",
"afk_here_on_reason": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK mode is on in this chat!</b>\n\n<b>Reason:</b> <i>{}</i>",
"afk_off": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK mode is off!</b>",
"afk_off_time": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK mode is off!</b>\n\n<b>You were AFK for:</b> {}",
"afk_off_here_time": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK mode is off in this chat!</b>\n\n<b>You were AFK for:</b> {}",
"already_afk": "<emoji document_id=5465665476971471368>❌</emoji> <b>You are already in AFK mode!</b>",
"already_afk_here": "<emoji document_id=5465665476971471368>❌</emoji> <b>You are already in AFK mode in this chat!</b>",
"not_afk": "<emoji document_id=5330365133745038003>😐</emoji> <b>AFK mode is already off.</b>",
"not_afk_here": "<emoji document_id=5330365133745038003>😐</emoji> <b>AFK mode is already off in this chat.</b>",
"afk_message": "<emoji document_id=5330130448142049118>🫤</emoji> <b>I'm currently not accepting messages!</b>\n<b>Reason:</b> <i>{}</i>\n\n<i>Inactive mode has been on for:</i> {}",
"afk_message_reason": "<emoji document_id=5330130448142049118>🫤</emoji> <b>I'm currently not accepting messages!</b>\n<b>Reason:</b> <i>{}</i>\n\n<i>Inactive mode has been on for:</i> {}",
"afk_set_failed": "<b>Failed to set AFK status. Check logs.</b>",
"added_excluded_chat": "<b>Chat {} added to excluded chats.</b>",
"removed_excluded_chat": "<b>Chat {} removed from excluded chats.</b>",
"excluded_chats_list": "<b>Excluded chats:</b>\n{}",
"no_excluded_chats": "<b>No chats are excluded.</b>",
"invalid_chat_id": "<b>Invalid chat ID.</b>",
"already_excluded": "<b>Chat {} is already excluded.</b>",
"not_excluded": "<b>Chat {} is not excluded.</b>",
}
strings_ru = {
"afk_on": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK-режим включен!</b>",
"afk_on_reason": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK-режим включен!</b>\n\n<b>Причина:</b> <i>{}</i>",
"afk_here_on": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK-режим включен в этом чате!</b>",
"afk_here_on_reason": "<emoji document_id=5357107687484038897>🫶</emoji> <b>AFK-режим включен в этом чате!</b>\n\n<b>Причина:</b> <i>{}</i>",
"afk_off": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK-режим отключен!</b>",
"afk_off_time": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK-режим отключен!</b>\n\n<b>Вы были AFK:</b> {}",
"afk_off_here_time": "<emoji document_id=5472234792659458002>🤌</emoji> <b>AFK-режим отключен в этом чате!</b>\n\n<b>Вы были AFK:</b> {}",
"already_afk": "<emoji document_id=5465665476971471368>❌</emoji> <b>Вы уже находитесь в AFK-режиме!</b>",
"already_afk_here": "<emoji document_id=5465665476971471368>❌</emoji> <b>Вы уже находитесь в AFK-режиме в этом чате!</b>",
"not_afk": "<emoji document_id=5330365133745038003>😐</emoji> <b>AFK-режим уже отключён.</b>",
"not_afk_here": "<emoji document_id=5330365133745038003>😐</emoji> <b>AFK-режим уже отключен в этом чате.</b>",
"afk_message": "<emoji document_id=5330130448142049118>🫤</emoji> <b>На данный момент я не принимаю сообщения!</b>\n<b>Причина:</b> <i>{}</i>\n\n<i>С момента включения режима неактивности:</i> {}",
"afk_message_reason": "<emoji document_id=5330130448142049118>🫤</emoji> <b>На данный момент я не принимаю сообщения!</b>\n<b>Причина:</b> <i>{}</i>\n\n<i>С момента включения режима неактивности:</i> {}",
"afk_set_failed": "<b>Не удалось установить AFK-статус. Проверьте логи.</b>",
"added_excluded_chat": "<b>Чат {} добавлен в список исключений.</b>",
"removed_excluded_chat": "<b>Чат {} удален из списка исключений.</b>",
"excluded_chats_list": "<b>Список исключенных чатов:</b>\n{}",
"no_excluded_chats": "<b>Нет исключенных чатов.</b>",
"invalid_chat_id": "<b>Неверный ID чата.</b>",
"already_excluded": "<b>Чат {} уже исключен.</b>",
"not_excluded": "<b>Чат {} не исключен.</b>",
}
DEFAULT_AFK_TIMEOUT = 60
DEFAULT_DELETE_TIMEOUT = 5
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"excluded_chats",
[],
lambda: "List of chat IDs where AFK mode will not be activated",
validator=loader.validators.Series(
validator=loader.validators.Integer()
),
)
)
async def client_ready(self, client, db):
self.client = client
self.db = db
self._me = await client.get_me()
self._ratelimit_cache = {}
self.global_afk = self.db.get(__name__, "afk", False)
self.global_afk_reason = self.db.get(__name__, "afk_reason", None)
self.global_gone_time = self.db.get(__name__, "gone_afk", None)
logger.debug(
f"Initial global AFK state: afk={self.global_afk}, reason={self.global_afk_reason}, gone_time={self.global_gone_time}"
)
@loader.command(
ru_doc="[reason / none] Установить режим AFK",
en_doc="[reason / none] Set AFK mode globally",
)
async def afk(self, message):
await self._afk_toggle(message, global_afk=True)
@loader.command(
ru_doc="[reason / none] Установить режим AFK только в этом чате.",
en_doc="[reason / none] Set AFK mode in current chat only.",
)
async def afkhere(self, message):
await self._afk_toggle(message, global_afk=False)
async def _afk_toggle(self, message, global_afk: bool):
chat_id = utils.get_chat_id(message)
db_key = "afk" if global_afk else f"afk_here_{chat_id}"
already_afk_string = "already_afk" if global_afk else "already_afk_here"
afk_on_string = "afk_on" if global_afk else "afk_here_on"
afk_on_reason_string = "afk_on_reason" if global_afk else "afk_here_on_reason"
if self._is_afk_enabled(chat_id, global_afk):
await utils.answer(message, self.strings(already_afk_string, message))
return
reason = utils.get_args_raw(message) or None
success = self._set_afk(
True, reason=reason, chat_id=chat_id if not global_afk else None
)
if not success:
await utils.answer(message, self.strings("afk_set_failed", message))
return
await utils.answer(
message,
self.strings(afk_on_reason_string, message).format(reason)
if reason
else self.strings(afk_on_string, message),
)
@loader.command(
ru_doc="Выйти из режима AFK",
en_doc="Exit AFK mode",
)
async def unafk(self, message):
await self._unafk_toggle(message, global_afk=True)
@loader.command(
ru_doc="Выйти из режима AFK в этом чате",
en_doc="Exit AFK mode in this chat",
)
async def unafkhere(self, message):
await self._unafk_toggle(message, global_afk=False)
async def _unafk_toggle(self, message, global_afk: bool):
chat_id = utils.get_chat_id(message)
not_afk_string = "not_afk" if global_afk else "not_afk_here"
afk_off_time_string = "afk_off_time" if global_afk else "afk_off_here_time"
if not self._is_afk_enabled(chat_id, global_afk):
await utils.answer(message, self.strings(not_afk_string, message))
return
total_gone_time = self._calculate_total_afk_time(
datetime.datetime.now().replace(microsecond=0),
chat_id=chat_id if not global_afk else None,
)
self._set_afk(False, chat_id=chat_id if not global_afk else None)
await self.allmodules.log("unafk" if global_afk else "unafkhere")
await utils.answer(
message, self.strings(afk_off_time_string, message).format(total_gone_time)
)
async def watcher(self, message):
if not isinstance(message, types.Message):
return
chat_id = get_peer_id(message.peer_id)
user_id = getattr(message.to_id, "user_id", None)
is_mentioned = message.mentioned or user_id == self._me.id
is_private = isinstance(message.to_id, types.PeerUser)
if not (is_mentioned or is_private) or chat_id in self.config["excluded_chats"]:
return
reason = None
gone_time = None
if self._is_afk_enabled(chat_id, False):
reason = self.db.get(__name__, f"afk_here_{chat_id}_reason", None)
gone_time = self.db.get(__name__, f"gone_afk_here_{chat_id}", None)
elif self.global_afk:
reason = self.global_afk_reason
gone_time = self.global_gone_time
else:
return
if gone_time is None:
logger.warning(f"No 'gone' time found for chat {chat_id}. Cannot send AFK.")
return
afk_message = await self._send_afk_message(message, reason, gone_time)
if afk_message:
await self._delete_message(afk_message, self.DEFAULT_DELETE_TIMEOUT)
def _set_afk(self, value: bool, reason: str = None, chat_id: int = None) -> bool:
try:
key_prefix = f"afk_here_{chat_id}" if chat_id else "afk"
self.db.set(__name__, key_prefix, value)
self.db.set(__name__, f"{key_prefix}_reason", reason)
gone_key = f"gone_{key_prefix}"
gone_time = time.time() if value else None
self.db.set(__name__, gone_key, gone_time)
logger.debug(f"AFK status updated. {gone_key} set to {gone_time}")
if chat_id is None:
self.global_afk = value
self.global_afk_reason = reason
self.global_gone_time = gone_time
logger.debug("Updated global AFK vars")
return True
except Exception as e:
logger.exception(f"Error setting AFK status: {e}")
return False
def _calculate_total_afk_time(
self, now: datetime.datetime, chat_id: int = None
) -> datetime.timedelta:
key_prefix = f"afk_here_{chat_id}" if chat_id else "afk"
gone_time = self.db.get(__name__, f"gone_{key_prefix}")
if gone_time is None:
return datetime.timedelta(seconds=0)
try:
gone = datetime.datetime.fromtimestamp(gone_time).replace(microsecond=0)
return now - gone
except Exception as e:
logger.error(f"Error calculating AFK time: {e}")
return datetime.timedelta(seconds=0)
async def _send_afk_message(self, message, reason, gone_time):
user = await utils.get_user(message)
if user.is_self or user.bot or user.verified:
logger.debug("User is self, bot, or verified. Not sending AFK message.")
return None
now = datetime.datetime.now().replace(microsecond=0)
try:
gone = datetime.datetime.fromtimestamp(gone_time).replace(microsecond=0)
except (TypeError, ValueError) as e:
logger.error(f"Error converting timestamp: {e}")
return None
time_string = str(now - gone)
ret = (
self.strings("afk_message_reason", message).format(reason, time_string)
if reason
else self.strings("afk_message", message).format(time_string)
)
try:
reply = await utils.answer(message, ret, reply_to=message)
return reply
except Exception as e:
logger.exception(f"Error sending AFK message: {e}")
return None
def _is_afk_enabled(self, chat_id: int = None, global_afk: bool = False) -> bool:
return (
self.global_afk
if global_afk
else self.db.get(__name__, f"afk_here_{chat_id}", False)
)
async def _delete_message(self, message, delay):
await asyncio.sleep(delay)
try:
await self.client.delete_messages(message.chat_id, message.id)
except Exception as e:
logger.exception(f"Error deleting message: {e}")

View File

@@ -0,0 +1,335 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: HModsLibrary
# Description: Library required for most H:Mods modules.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: HModsLibrary
# scope: HModsLibrary 0.0.1
# ---------------------------------------------------------------------------------
import logging
import re
import aiohttp
import random
import asyncio
import os
from bs4 import BeautifulSoup
from gigachat import GigaChat
from typing import Optional, Dict, Any
from .. import loader, utils
logger = logging.getLogger(__name__)
__version__ = (0, 0, 2)
class HModsLib(loader.Library):
"""Library required for most H:Mods modules."""
developer = "@hikka_mods"
version = __version__
async def parse_time(self, time_str):
time_units = {"d": 86400, "h": 3600, "m": 60, "s": 1}
if not re.fullmatch(r"(\d+[dhms])+", time_str):
return None
seconds = 0
matches = re.findall(r"(\d+)([dhms])", time_str)
for amount, unit in matches:
seconds += int(amount) * time_units[unit]
return seconds if seconds > 0 else None
@staticmethod
def convert_size(size):
"""Convert file size to human-readable format."""
power = 2**10
n = 0
units = {0: "B", 1: "KB", 2: "MB", 3: "GB", 4: "TB"}
while size > power:
size /= power
n += 1
return round(size, 2), units[n]
async def upload_to_envs(self, path):
"""Upload file to envs.sh and return the URL."""
url = "https://envs.sh"
async with aiohttp.ClientSession() as session:
async with session.post(url, data={"file": open(path, "rb")}) as response:
if response.status != 200:
os.remove(path)
raise aiohttp.ClientResponseError(
request_info=response.request_info,
history=response.history,
status=response.status,
message=await response.text(),
headers=response.headers,
)
result = await response.text()
os.remove(path)
return result
async def get_creation_date(tg_id: int) -> str:
url = "https://restore-access.indream.app/regdate"
headers = {
"accept": "*/*",
"content-type": "application/x-www-form-urlencoded",
"user-agent": "Nicegram/92 CFNetwork/1390 Darwin/22.0.0",
"x-api-key": "e758fb28-79be-4d1c-af6b-066633ded128",
"accept-language": "en-US,en;q=0.9",
}
data = {"telegramId": tg_id}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=data) as response:
if response.status == 200:
json_response = await response.json()
return json_response["data"]["date"]
else:
return "Ошибка получения данных"
async def get_giga_response(self, api_key, query):
"""Gets a response from GigaChat with the specified query."""
async with GigaChat(
credentials=api_key,
scope="GIGACHAT_API_PERS",
model=self.config["GIGACHAT_MODEL"],
verify_ssl_certs=False,
) as giga:
response = giga.chat(query)
if response.choices:
return response.choices[0].message.content
return None
async def get_giga_models(self, api_key):
"""Gets a response from GigaChat with the specified query."""
async with GigaChat(
credentials=api_key, scope="GIGACHAT_API_PERS", verify_ssl_certs=False
) as giga:
response = giga.get_models()
if response:
return (
[model.id_ for model in response.data]
if hasattr(response, "data")
else []
)
return None
async def get_random_image():
random_site = random.randint(1, 3389)
url = f"https://www.memify.ru/memes/{random_site}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
content = await response.text()
soup = BeautifulSoup(content, "html.parser")
items = soup.find_all("div", {"class": "infinite-item card"})
random_item = random.choice(items)
second_a = random_item.find_all("a")[1]
img = second_a.get("href")
return img
async def virustotal_request(
self,
session: aiohttp.ClientSession,
url: str,
headers: Dict[str, str],
method: str = "GET",
data: Optional[Dict[str, Any]] = None,
files: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
"""
Generic function to make requests to the VirusTotal API.
"""
try:
if files:
form = aiohttp.FormData()
for k, v in files.items():
form.add_field(k, v)
async with session.request(
method, url, headers=headers, data=form
) as response:
logger.debug(f"Response status: {response.status}")
logger.debug(f"Response body: {await response.text()}")
if response.status == 200:
return await response.json()
else:
logger.error(
f"VirusTotal API request failed with status: {response.status}, reason: {response.reason}"
)
return None
else:
async with session.request(
method, url, headers=headers, json=data
) as response:
logger.debug(f"Response status: {response.status}")
logger.debug(f"Response body: {await response.text()}")
if response.status == 200:
return await response.json()
else:
logger.error(
f"VirusTotal API request failed with status: {response.status}, reason: {response.reason}"
)
return None
except aiohttp.ClientError as e:
logger.exception(f"AIOHTTP Client error: {e}")
return None
except Exception as e:
logger.exception(f"An unexpected error occurred: {e}")
return None
async def get_upload_url(self, api_key: str) -> Optional[str]:
"""
Retrieves a special upload URL for large files.
"""
headers = {"x-apikey": api_key, "accept": "application/json"}
url = "https://www.virustotal.com/api/v3/files/upload_url"
async with aiohttp.ClientSession() as session:
response = await self.virustotal_request(session, url, headers)
if response and "data" in response and isinstance(response["data"], str):
return response["data"]
else:
logger.error(f"Failed to retrieve upload URL: {response}")
return None
async def scan_file_virustotal(
self, file_path: str, api_key: str, is_large_file: bool = False
) -> Optional[Dict[str, Any]]:
"""
Uploads a file to VirusTotal and retrieves the analysis results. Handles files larger than 32MB.
"""
headers = {"x-apikey": api_key}
url = "https://www.virustotal.com/api/v3/files"
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as file:
files = {"file": file}
if is_large_file:
upload_url = await self.get_upload_url(api_key)
if not upload_url:
logger.error("Failed to get upload URL for large file.")
return None
url = upload_url
upload_response = await self.virustotal_request(
session, url, headers, method="POST", files=files
)
if (
upload_response
and "data" in upload_response
and "id" in upload_response["data"]
):
analysis_id = upload_response["data"]["id"]
analysis_url = (
f"https://www.virustotal.com/api/v3/analyses/{analysis_id}"
)
for attempt in range(20):
analysis_response = await self.virustotal_request(
session, analysis_url, headers
)
logger.debug(
f"Analysis response (attempt {attempt + 1}): {analysis_response}"
)
if (
analysis_response
and "data" in analysis_response
and "attributes" in analysis_response["data"]
and analysis_response["data"]["attributes"].get(
"status"
)
== "completed"
):
return analysis_response
await asyncio.sleep(10)
logger.warning(
f"Analysis not completed after multiple retries for ID: {analysis_id}"
)
return None
else:
logger.error(
f"File upload or analysis request failed: {upload_response}"
)
return None
except FileNotFoundError:
logger.error(f"File not found: {file_path}")
return None
except Exception as e:
logger.exception(f"An error occurred during file scanning: {e}")
return None
def format_analysis_results(self, analysis_results: Dict[str, Any]) -> str:
"""
Formats the analysis results into a user-friendly message, including specific detections.
"""
if (
not analysis_results
or "data" not in analysis_results
or "attributes" not in analysis_results["data"]
or "stats" not in analysis_results["data"]["attributes"]
or "results" not in analysis_results["data"]["attributes"]
):
logger.warning(
f"Unexpected structure in analysis_results: {analysis_results}"
)
return self.strings("error")
stats = analysis_results["data"]["attributes"]["stats"]
harmless = stats.get("harmless", 0)
malicious = stats.get("malicious", 0)
suspicious = stats.get("suspicious", 0)
undetected = stats.get("undetected", 0)
total_scans = harmless + malicious + suspicious + undetected
analysis_id = analysis_results["data"]["id"]
url = f"https://www.virustotal.com/gui/file-analysis/{analysis_id}"
text = (
f"<b>📊 VirusTotal Scan Results</b>\n\n"
f"🦠 <b>Detections:</b> {malicious} / {total_scans}\n"
f"🟢 <b>Harmless:</b> {harmless}\n"
f"⚠️ <b>Suspicious:</b> {suspicious}\n"
f"❓ <b>Undetected:</b> {undetected}\n\n"
)
if malicious > 0:
text += "<b>⚠️ Detections by engine:</b>\n"
results = analysis_results["data"]["attributes"]["results"]
for engine, result in results.items():
if result["category"] == "malicious":
engine_name = engine.replace("_", " ").title()
text += f" • <b>{engine_name}:</b> {result['result']}\n"
text += "\n"
return {"text": text, "url": url}

View File

@@ -0,0 +1,80 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: InlineButton
# Description: Create inline button
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: InlineButton
# scope: InlineButton 0.0.1
# ---------------------------------------------------------------------------------
from ..inline.types import InlineQuery
from .. import loader, utils
@loader.tds
class InlineButtonMod(loader.Module):
"""Create inline button"""
strings = {
"name": "InlineButton",
"titles": "Create a message with the Inline Button",
"error_title": "Error",
"error_description": "Invalid input format. Please provide exactly three comma-separated values.",
"error_message": "Make sure your input is formatted as: message, name, url.",
}
strings_ru = {
"titles": "Создай сообщение с Inline Кнопкой",
"error_title": "Ошибка",
"error_description": "Неверный формат ввода. Пожалуйста, укажите ровно три значения, разделенных запятыми.",
"error_message": "Убедитесь, что ваш ввод имеет следующий формат: сообщение, имя, url.",
}
@loader.command(
ru_doc="Создать inline кнопку\nНапример: @username_bot crinl Текст сообщения, Текст кнопки, Ссылка в кнопке",
en_doc="Create an inline button\nexample: @username_bot crinl Message text, Button text, Link in the button",
)
async def crinl_inline_handler(self, query: InlineQuery):
args = utils.get_args_raw(query.query)
if args:
args_list = [arg.strip() for arg in args.split(",")]
if len(args_list) == 3:
message, name, url = args_list
return {
"title": self.strings("titles"),
"description": f"{message}, {name}, {url}",
"message": message,
"reply_markup": [{
"text": name,
"url": url
}]
}
return {
"title": self.strings("error_title"),
"description": self.strings("error_description"),
"message": self.strings("error_message"),
}

View File

@@ -0,0 +1,74 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: InlineCoin
# Description: Mini game heads or tails.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: InlineCoin
# scope: InlineCoin 0.0.1
# ---------------------------------------------------------------------------------
import random
from ..inline.types import InlineQuery
from .. import loader
@loader.tds
class CoinSexMod(loader.Module):
"""Mini game heads or tails"""
strings = {
"name": "InlineCoin",
"titles": "Heads or tails?",
"description": "Let's find out!",
"heads": "🌚 An eagle fell out!",
"tails": "🌝 Tails fell out!",
"edge": "🙀 Miraculously, the coin remained on the edge!",
}
strings_ru = {
"titles": "Орёл или решка?",
"description": "Давай узнаем!",
"heads": "🌚 Выпал орёл!",
"tails": "🌝 Выпала решка!",
"edge": "🙀 Чудо, монетка осталась на ребре!",
}
def get_coin_flip_result(self) -> dict:
results = [self.strings("heads"), self.strings("tails")]
if random.random() < 0.1:
return self.strings("edge")
else:
return random.choice(results)
@loader.command(
ru_doc="Подбросит монетку ",
en_doc="Flip a coin",
)
async def coin_inline_handler(self, query: InlineQuery):
result = self.get_coin_flip_result()
return {
"title": self.strings("titles"),
"description": self.strings("description"),
"message": f"<b>{result}</b>",
"thumb": "https://github.com/Codwizer/ReModules/blob/main/assets/images.png",
}

View File

@@ -0,0 +1,213 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: InlineHelper
# Description: Basic management of the UB in case only the inline works
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: InlineHelper
# scope: InlineHelper 0.0.1
# ---------------------------------------------------------------------------------
import sys
import os
import asyncio
import logging
from ..inline.types import InlineQuery
from .. import loader, utils, main
@loader.tds
class InlineHelperMod(loader.Module):
"""Basic management of the UB in case only the inline works"""
strings = {
"name": "InlineHelper",
"call_restart": "Restarting...",
"call_update": "Updating...",
"res_prefix": "Successfully reset prefix to default",
"restart_inline_handler_title": "Restart Userbot",
"restart_inline_handler_description": "Restart your userbot via inline",
"restart_inline_handler_message": "Press the button below to restart your userbot",
"restart_inline_handler_reply_text": "Restart",
"update_inline_handler_title": "Update Userbot",
"update_inline_handler_description": "Update your userbot via inline",
"update_inline_handler_message": "Press the button below to update your userbot",
"update_inline_handler_reply_text": "Update",
"terminal_inline_handler_title": "Command Executed!",
"terminal_inline_handler_description": "Command executed successfully",
"terminal_inline_handler_message": "Command {text} executed successfully in terminal",
"modules_inline_handler_title": "Modules",
"modules_inline_handler_description": "List all installed modules",
"modules_inline_handler_result": "☘️ Installed modules:\n",
"resetprefix_inline_handler_title": "Reset Prefix",
"resetprefix_inline_handler_description": "Reset your prefix back to default",
"resetprefix_inline_handler_message": "Are you sure you want to reset your prefix to default dot?",
"resetprefix_inline_handler_reply_text_yes": "Yes",
"resetprefix_inline_handler_reply_text_no": "No",
}
strings_ru = {
"call_restart": "Перезагружаю...",
"call_update": "Обновляю...",
"res_prefix": "Префикс успешно сброшен по умолчанию",
"restart_inline_handler_title": "Перезагрузить юзербота",
"restart_inline_handler_description": "Перезагрузить юзербота через инлайн",
"restart_inline_handler_message": "<b>Нажмите на кнопку ниже для рестарта юзербота</b>",
"restart_inline_handler_reply_text": "Перезапуск",
"update_inline_handler_title": "Обновить юзербота",
"update_inline_handler_description": "Обновить юзербота через инлайн",
"update_inline_handler_message": "<b>Нажмите на кнопку ниже для обновления юзербота</b>",
"update_inline_handler_reply_text": "Обновить",
"terminal_inline_handler_title": "Команда выполнена!",
"terminal_inline_handler_description": "Команда завершена.",
"terminal_inline_handler_message": "Команда <code>{text}</code> была успешно выполнена в терминале",
"modules_inline_handler_title": "Модули",
"modules_inline_handler_description": "Вывести список установленных моудей",
"modules_inline_handler_result": "☘️ Все установленные модули:\n",
"resetprefix_inline_handler_title": "Сбросить префикс",
"resetprefix_inline_handler_description": "Сбросить префикс по умолчанию",
"resetprefix_inline_handler_message": "Вы действительно хотите сбросить ваш префикс и установить стандартную точку?",
"resetprefix_inline_handler_reply_text_yes": "Да",
"resetprefix_inline_handler_reply_text_no": "Нет",
}
async def client_ready(self, client, db):
self.client = client
self.db = db
async def restart(self, call):
"""Restart callback"""
logging.error("InlineHelper: restarting userbot...")
await call.edit(self.strings("call_restart"))
await sys.exit(0)
async def update(self, call):
"""Update callback"""
logging.error("InlineHelper: updating userbot...")
os.system(f"cd {utils.get_base_dir()} && cd .. && git reset --hard HEAD")
os.system("git pull")
await call.edit(self.strings("call_update"))
await sys.exit(0)
async def reset_prefix(self, call):
"""Reset prefix"""
self.db.set(main.__name__, "command_prefix", ".")
await call.edit(self.strings("res_prefix"))
@loader.inline_handler(
ru_doc="Перезагрузить юзербота",
en_doc="Reboot the userbot",
)
async def restart_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("restart_inline_handler_title"),
"description": self.strings("restart_inline_handler_description"),
"message": self.strings("restart_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("restart_inline_handler_reply_text"),
"callback": self.restart,
}
],
}
@loader.inline_handler(
ru_doc="Обновить юзербота",
en_doc="Update the userbot",
)
async def update_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("update_inline_handler_title"),
"description": self.strings("update_inline_handler_description"),
"message": self.strings("update_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("update_inline_handler_reply_text"),
"callback": self.update,
}
],
}
@loader.inline_handler(
ru_doc="Выполнить команду в терминале (лучше сразу подготовить команду и просто вставить)",
en_doc="Execute the command in the terminal (it is better to prepare the command immediately and just paste it)",
)
async def terminal_inline_handler(self, _: InlineQuery):
text = _.args
await asyncio.create_subprocess_shell(
f"{text}",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=utils.get_base_dir(),
)
return {
"title": self.strings("terminal_inline_handler_title"),
"description": self.strings("terminal_inline_handler_description"),
"message": self.strings("terminal_inline_handler_message").format(
text=text
),
}
@loader.inline_handler(
ru_doc="Вывести список установленных модулей через инлайн",
en_doc="Display a list of installed modules via the inline",
)
async def modules_inline_handler(self, _: InlineQuery):
result = self.strings("modules_inline_handler_result")
for mod in self.allmodules.modules:
try:
name = mod.strings["name"]
except KeyError:
name = mod.__clas__.__name__
result += f"{name}\n"
return {
"title": self.strings("modules_inline_handler_title"),
"description": self.strings("modules_inline_handler_description"),
"message": result,
}
@loader.inline_handler(
ru_doc="Сбросить префикс (осторожнее, сбрасывает ваш префикс на . )",
en_doc="Reset the prefix (be careful, resets your prefix to . )",
)
async def resetprefix_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("resetprefix_inline_handler_title"),
"description": self.strings("resetprefix_inline_handler_description"),
"message": self.strings("resetprefix_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("resetprefix_inline_handler_reply_text_yes"),
"callback": self.reset_prefix,
},
{
"text": self.strings("resetprefix_inline_handler_reply_text_no"),
"action": "close",
},
],
}

View File

@@ -0,0 +1,88 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: IrisSimpleMod
# Description: Module for basic interaction with Iris.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: IrisSimpleMod
# scope: IrisSimpleMod 1.0.1
# ---------------------------------------------------------------------------------
from .. import loader, utils
__version__ = (1, 0, 1)
@loader.tds
class IrisSimpleMod(loader.Module):
"""Модуль для базового взаимодействия с Ирисом"""
strings = {"name": "IrisSimpleMod"}
@loader.command(
ru_doc="Проверить мешок"
)
async def bag(self, message):
"""Check bag"""
async with self.client.conversation(5443619563) as conv:
usermessage = await conv.send_message('мешок')
await usermessage.delete()
bagmessage = await conv.get_response()
await utils.answer(message, 'Ваш мешок:\n' + bagmessage.text)
await bagmessage.delete()
@loader.command(
ru_doc="Зафармить ирис-коины"
)
async def farm(self, message):
"""Farm iris-coins"""
async with self.client.conversation(5443619563) as conv:
usermessage = await conv.send_message('ферма')
await usermessage.delete()
farmmessage = await conv.get_response()
await utils.answer(message, farmmessage.text)
await farmmessage.delete()
@loader.command(
ru_doc="Вывести анкету"
)
async def irisstats(self, message):
"""Display user stats"""
async with self.client.conversation(5443619563) as conv:
usermessage = await conv.send_message('анкета')
await usermessage.delete()
statsmessage = await conv.get_response()
await utils.answer(message, statsmessage.text)
await statsmessage.delete()
@loader.command(
ru_doc="Вывести статистику ботов"
)
async def irisping(self, message):
"""Display bot stats"""
async with self.client.conversation(5443619563) as conv:
usermessage = await conv.send_message('🌺 Семейство ирисовых')
await usermessage.delete()
pingmessage = await conv.get_response()
await utils.answer(message, pingmessage.text)
await pingmessage.delete()

View File

@@ -0,0 +1,100 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: KBSwapper
# Description: KBSwapper is a module for changing the keyboard layout
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: KBSwapper
# scope: KBSwapper 0.0.1
# ---------------------------------------------------------------------------------
import string
from .. import loader, utils
EN_TO_RU = str.maketrans(
"qwertyuiop[]asdfghjkl;'zxcvbnm,./`" + 'QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~',
"йцукенгшщзхъфывапролджэячсмитьбю.ё" + "ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё",
)
RU_TO_EN = str.maketrans(
"йцукенгшщзхъфывапролджэячсмитьбю.ё" + "ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё",
"qwertyuiop[]asdfghjkl;'zxcvbnm,./`" + 'QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~',
)
@loader.tds
class KBSwapperMod(loader.Module):
"""KBSwapper is a module for changing the keyboard layout"""
strings = {
"name": "KBSwapper",
"no_reply": "<emoji document_id=5774077015388852135>❌</emoji> <b>Please reply to a message.</b>",
"no_text": "<emoji document_id=5774077015388852135>❌</emoji> <b>The replied message does not contain text.</b>",
"original_message": "<emoji document_id=5260450573768990626>➡️</emoji> <b>Original message:</b>\n<code>{original}</code>",
"fixed_message": "<emoji document_id=5774022692642492953>✅</emoji> <b>Fixed message:</b>\n<code>{fixed}</code>",
"error": "<emoji document_id=5774077015388852135>❌</emoji> <b>An error occurred while processing the message.</b>",
}
strings_ru = {
"no_reply": "<emoji document_id=5774077015388852135>❌</emoji> <b>Пожалуйста, ответьте на сообщение.</b>",
"no_text": "<emoji document_id=5774077015388852135>❌</emoji> <b>Отвеченное сообщение не содержит текста.</b>",
"original_message": "<emoji document_id=5260450573768990626>➡️</emoji> <b>Оригинальное сообщение:</b>\n<code>{original}</code>",
"fixed_message": "<emoji document_id=5774022692642492953>✅</emoji> <b>Исправленное сообщение:</b>\n<code>{fixed}</code>",
"error": "<emoji document_id=5774077015388852135>❌</emoji> <b>Произошла ошибка при обработке сообщения.</b>",
}
@loader.command(
ru_doc="При ответе на своё сообщение меняет раскладку путем редактирования, на чужое — в отдельном сообщении.",
en_doc="Change keyboard layout for the replied message.",
)
async def swap(self, message):
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, self.strings("no_reply"))
return
original_text = reply.text
if not original_text:
await utils.answer(message, self.strings("no_text"))
return
try:
first_char = original_text[0].lower()
if first_char in string.ascii_lowercase:
fixed_text = original_text.translate(EN_TO_RU)
elif first_char in "йцукенгшщзхъфывапролджэячсмитьбю.ё":
fixed_text = original_text.translate(RU_TO_EN)
else:
fixed_text = original_text
if message.sender_id == reply.sender_id:
await reply.edit(fixed_text)
else:
await utils.answer(
message,
f"{self.strings('original_message').format(original=original_text)}\n"
f"{self.strings('fixed_message').format(fixed=fixed_text)}",
)
except Exception as e:
print(f"Error during swap: {e}")
await utils.answer(message, self.strings("error"))

20
C0dwiz/H.Modules/LICENSE Normal file
View File

@@ -0,0 +1,20 @@
Proprietary License Agreement
Copyright (c) 2024-29 CodWiz
Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
5. By using the Software, you agree to be bound by the terms and conditions of this license.
For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
Sergei
08.10.2024

107
C0dwiz/H.Modules/Memes.py Normal file
View File

@@ -0,0 +1,107 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: Meme
# Description: Random memes
# Author: @hikka_mods
# Commands:
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Meme
# scope: Meme 0.0.1
# ---------------------------------------------------------------------------------
from bs4 import BeautifulSoup
import aiohttp
import random
from .. import loader
@loader.tds
class MemesMod(loader.Module):
"""Random memes"""
strings = {
"name": "Memes",
"done": "☄️ Catch the meme",
"still": "🔄 Update",
"dell": "❌ Close",
}
strings_ru = {
"done": "☄️ Лови мем",
"still": "🔄 Обновить",
"dell": "❌ Закрыть",
}
async def client_ready(self, client, db):
self.hmodslib = await self.import_lib('https://raw.githubusercontent.com/C0dwiz/H.Modules/refs/heads/main-fix/HModsLibrary.py')
@loader.command(
ru_doc="",
en_doc="",
)
async def memescmd(self, message):
img = await self.hmodslib.get_random_image()
await self.inline.form(
text=self.strings("done"),
photo=img,
message=message,
reply_markup=[
[
{
"text": self.strings("still"),
"callback": self.ladno,
}
],
[
{
"text": self.strings("dell"),
"callback": self.dell,
}
],
],
silent=True,
)
async def ladno(self, call):
img = await self.hmodslib.get_random_image()
await call.edit(
text=self.strings("done"),
photo=img,
reply_markup=[
[
{
"text": self.strings("still"),
"callback": self.ladno,
}
],
[
{
"text": self.strings("dell"),
"callback": self.dell,
}
],
],
)
async def dell(self, call):
"""Callback button"""
await call.delete()

File diff suppressed because it is too large Load Diff

202
C0dwiz/H.Modules/Music.py Normal file
View File

@@ -0,0 +1,202 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: Music
# Description: Searches for music using Telegram music bots.
# Author: @hikka_mods
# meta developer: @hikka_mods
# scope: Music
# scope: Music 0.0.2
# ---------------------------------------------------------------------------------
# Thanks to @murpizz for the search code yandex
import logging
from telethon.errors.rpcerrorlist import (
BotMethodInvalidError,
FloodWaitError,
MessageNotModifiedError,
)
from telethon.tl.types import Message
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class MusicMod(loader.Module):
strings = {
"name": "Music",
"no_query": "<emoji document_id=5337117114392127164>🤷‍♂</emoji> <b>Provide a search query.</b>",
"searching": "<emoji document_id=4918235297679934237>⌨️</emoji> <b>Searching...</b>",
"found": "<emoji document_id=5336965905773504919>🗣</emoji> <b>Possible match:</b>",
"not_found": "<emoji document_id=5228947933545635555>😫</emoji> <b>Track not found: <code>{}</code>.</b>",
"invalid_service": "<emoji document_id=5462295343642956603>🚫</emoji> <b>Invalid service. (yandex, vk)</b>",
"usage": "<b>Usage:</b> <code>.music [yandex|vk] [track name]</code>",
"error": "<emoji document_id=5228947933545635555>⚠️</emoji> <b>Error:</b> <code>{}</code>",
"no_results": "<emoji document_id=5228947933545635555>😫</emoji> <b>No results: <code>{}</code>.</b>",
"flood_wait": "<emoji document_id=5462295343642956603>⏳</emoji> <b>Wait {}s (Telegram limits).</b>",
"bot_error": "<emoji document_id=5228947933545635555>🤖</emoji> <b>Bot error: <code>{}</code></b>",
"no_audio": "<emoji document_id=5228947933545635555>🎵</emoji> <b>No audio.</b>",
"generic_result": "<emoji document_id=5336965905773504919></emoji> <b>Non-media result. Check the bot's chat.</b>",
"yafind_searching": "<emoji document_id=5258396243666681152>🔎</emoji> <b>Searching Yandex.Music...</b>",
"yafind_not_found": "<emoji document_id=5843952899184398024>🚫</emoji> <b>Track not found on Yandex.Music.</b>",
"yafind_error": "<emoji document_id=5843952899184398024>🚫</emoji> <b>Error (Yandex): {}</b>",
}
strings_ru = {
"name": "Music",
"no_query": "<emoji document_id=5337117114392127164>🤷‍♂</emoji> <b>Укажите запрос.</b>",
"searching": "<emoji document_id=4918235297679934237>⌨️</emoji> <b>Поиск...</b>",
"found": "<emoji document_id=5336965905773504919>🗣</emoji> <b>Возможно, это оно:</b>",
"not_found": "<emoji document_id=5228947933545635555>😫</emoji> <b>Трек не найден: <code>{}</code>.</b>",
"invalid_service": "<emoji document_id=5462295343642956603>🚫</emoji> <b>Неверный сервис. (yandex, vk)</b>",
"usage": "<b>Использование:</b> <code>.music [yandex|vk] [название трека]</code>",
"error": "<emoji document_id=5228947933545635555>⚠️</emoji> <b>Ошибка:</b> <code>{}</code>",
"no_results": "<emoji document_id=5228947933545635555>😫</emoji> <b>Нет результатов: <code>{}</code>.</b>",
"flood_wait": "<emoji document_id=5462295343642956603>⏳</emoji> <b>Подождите {}с (лимиты Telegram).</b>",
"bot_error": "<emoji document_id=5228947933545635555>🤖</emoji> <b>Ошибка бота: <code>{}</code></b>",
"no_audio": "<emoji document_id=5228947933545635555>🎵</emoji> <b>Нет аудио.</b>",
"generic_result": "<emoji document_id=5336965905773504919></emoji> <b>Немедийный результат. Проверьте чат с ботом.</b>",
"yafind_searching": "<emoji document_id=5258396243666681152>🔎</emoji> <b>Поиск в Яндекс.Музыке...</b>",
"yafind_not_found": "<emoji document_id=5843952899184398024>🚫</emoji> <b>Трек не найден в Яндекс.Музыке.</b>",
"yafind_error": "<emoji document_id=5843952899184398024>🚫</emoji> <b>Ошибка (Яндекс): {}</b>",
}
def __init__(self):
self.murglar_bot = "@murglar_bot"
self.vk_bot = "@vkmusic_bot"
@loader.command(
ru_doc="Найти трек в Yandex Music или VK: `.music yandex {название}` или `.music vk {название}`",
en_doc="Find a track in Yandex Music or VK: `.music yandex {name}` or `.music vk {name}`",
)
async def music(self, message):
args = utils.get_args(message)
if not args:
if reply := await message.get_reply_message():
await self._yafind(message, reply.raw_text.strip())
else:
await utils.answer(message, self.strings("usage", message))
return
service, query = args[0].lower(), " ".join(args[1:])
if service == "yandex":
await self._yafind(message, query)
elif service == "vk":
await self._vkfind(message, query)
else:
await utils.answer(message, self.strings("invalid_service", message))
async def _yafind(self, message: Message, query: str):
if not query:
return await utils.answer(message, self.strings("no_query", message))
await utils.answer(message, self.strings("yafind_searching", message))
try:
results = await message.client.inline_query(
self.murglar_bot, f"s:ynd {query}"
)
if not results:
return await utils.answer(
message, self.strings("yafind_not_found", message)
)
await results[0].click(
entity=message.chat_id,
hide_via=True,
reply_to=message.reply_to_msg_id if message.reply_to_msg_id else None,
)
await message.delete()
except Exception as e:
logger.exception("Yandex search error:")
await utils.answer(message, self.strings("yafind_error", message).format(e))
async def _vkfind(self, message, query: str):
if not query:
return await utils.answer(message, self.strings("no_query", message))
await utils.answer(message, self.strings("searching", message))
try:
music = await message.client.inline_query(self.vk_bot, query)
if not music or len(music) <= 1:
return await utils.answer(
message, self.strings("not_found", message).format(query)
)
for i in range(1, len(music), 2):
try:
result = music[i].result
if hasattr(result, "audio") and result.audio:
await message.client.send_file(
message.to_id,
result.audio,
caption=self.strings("found", message),
reply_to=utils.get_topic(message)
if message.reply_to_msg_id
else None,
)
await message.delete()
return
if hasattr(result, "document") and result.document:
await message.client.send_file(
message.to_id,
result.document,
caption=self.strings("found", message),
reply_to=utils.get_topic(message)
if message.reply_to_msg_id
else None,
)
await message.delete()
return
logger.warning(f"No audio/document in result {i}")
await utils.answer(message, self.strings("no_audio", message))
await message.delete()
return
except MessageNotModifiedError:
logger.warning("MessageNotModifiedError, skipping.")
except Exception as e:
logger.error(f"Send error: {e}")
await utils.answer(
message, self.strings("not_found", message).format(query)
)
except BotMethodInvalidError as e:
logger.error(f"VK bot error: {e}")
await utils.answer(message, self.strings("bot_error", message).format(e))
except FloodWaitError as e:
logger.warning(f"Flood wait: {e.seconds}s")
await utils.answer(
message, self.strings("flood_wait", message).format(e.seconds)
)
except Exception as e:
logger.exception("VK search error:")
await utils.answer(message, self.strings("error", message).format(e))

View File

@@ -0,0 +1,94 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: PastebinAPI
# Description: fills in the code on pastebin
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: PastebinAPI
# scope: PastebinAPI 0.0.1
# requires: aiohttp
# ---------------------------------------------------------------------------------
import aiohttp
from .. import loader, utils
@loader.tds
class PastebinAPIMod(loader.Module):
"""PastebinAPI"""
strings = {
"name": "PastebinAPI",
"no_reply": (
"<emoji document_id=5462882007451185227>🚫</emoji> You didn't specify the text"
),
"no_key": "<emoji document_id=5843952899184398024>🚫</emoji> The key was not found",
"done": "Your link with the code\n<emoji document_id=5985571061993837069>➡️</emoji> <code>{response_text}</code>",
}
strings_ru = {
"no_reply": (
"<emoji document_id=5462882007451185227>🚫</emoji> Вы не указали текст"
),
"no_key": "<emoji document_id=5843952899184398024>🚫</emoji> Ключ не найден",
"done": "Ваша ссылка с кодом\n<emoji document_id=5985571061993837069>➡️</emoji> <code>{response_text}</code>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"pastebin",
None,
lambda: "link to get api https://pastebin.com/doc_api#1",
validator=loader.validators.Hidden(),
)
)
@loader.command(
ru_doc="Заливает код в Pastebin",
en_doc="Uploads the code to Pastebin",
)
async def past(self, message):
text = utils.get_args(message)
if self.config["pastebin"] is None:
await utils.answer(message, self.strings("no_key"))
return
if not text:
await utils.answer(message, self.strings("no_reply"))
return
async with aiohttp.ClientSession() as Session:
async with Session.post(
url="https://pastebin.com/api/api_post.php",
data={
"api_dev_key": self.config["pastebin"],
"api_paste_code": text,
"api_option": "paste",
},
) as response:
response_text = await response.text()
await utils.answer(
message, self.strings("done").format(response_text=response_text)
)

View File

@@ -0,0 +1,91 @@
<div align="center">
<img src="https://github.com/Codwizer/ReModules/blob/main/assets/Vector.png" alt="hikka_mods" width="600">
</div>
<h1 align="center">H:Mods - Hikka Modules</h1>
<p align="center">
Enhance your <a href="https://github.com/hikariatama/Hikka">Hikka</a> experience with a curated collection of community modules.
</p>
<p align="center">
<a href="https://t.me/hikka_mods">
<img src="https://img.shields.io/badge/Join%20the-Telegram%20Channel-blue?style=flat-square&logo=telegram" alt="Telegram Channel">
</a>
</p>
---
## ✨ Installation Guide
### 1. Direct Installation
To install a module directly from the repository, use the following command:
```bash
.dlm https://raw.githubusercontent.com/C0dwiz/H.Modules/main/<module_name>.py
```
**Example:** To install example_module.py, use:
```bash
.dlm https://raw.githubusercontent.com/C0dwiz/H.Modules/main/example_module.py
```
### 2. Repository Installation (Recommended)
For easier module management and updates, install the entire repository.
**Step 1: Add the Repository**
```bash
.addrepo https://github.com/C0dwiz/H.Modules/raw/main
```
**Step 2: Install Modules from the Repository**
```bash
.dlm <module_name>
```
**Example:** After adding the repository, to install example_module, use:
```bash
.dlm example_module
```
---
## 📜 License
This project is licensed under a **Proprietary License**. By using this software, you agree to the terms and conditions outlined below.
> **You are granted permission to use the Software for personal and non-commercial purposes, subject to the following conditions:**
1. Modification or alteration of the Software is strictly prohibited without explicit written permission from the author.
2. Redistribution of the Software, in original or modified form, is strictly prohibited without explicit written permission from the author.
3. The Software is provided "as is", without any warranty, express or implied.
4. The copyright notice and this permission notice must be included in all copies or substantial portions of the Software.
5. By using the Software, you agree to be bound by the terms and conditions of this license.
**Contact:** For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
<details>
<summary>Show Full License Details</summary>
> <i>All files of this repository are under <b>Proprietary License.</b></i><br>
> <b>Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:</b>
1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
3. The Software is provided "as is", without warranty of any kind, express or implied.
4. The copyright notice and this permission notice must be included in all copies or substantial portions of the Software.
5. By using the Software, you agree to be bound by the terms and conditions of this license.
For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
</details>
---
<p align="center">
<img src="https://raw.githubusercontent.com/trinib/trinib/82213791fa9ff58d3ca768ddd6de2489ec23ffca/images/footer.svg" width="100%">
</p>

View File

@@ -0,0 +1,78 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: VowelReplacer
# Description: Replaces vowel letters with ё
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: VowelReplacer
# scope: VowelReplacer 0.0.1
# ---------------------------------------------------------------------------------
from telethon.tl.types import Message
from .. import loader, utils
@loader.tds
class VowelReplacer(loader.Module):
"""Replaces vowel letters with ё"""
strings = {
"name": "Vowel Replacer",
"on": "✅ Vowel substitution for ё has been successfully enabled.",
"off": "🚫 Vowel substitution for ё is disabled.",
}
strings_ru = {
"on": "✅ Замена гласных на ё успешно включена.",
"off": "🚫 Замена гласных на ё отключена.",
}
async def client_ready(self, client, db):
self.db = db
self._client = client
self.enabled = self.db.get("vowel_replacer", "enabled", False)
@loader.command(
ru_doc="Включить или отключить замену гласных на ё.",
en_doc="Enable or disable vowel substitution for ё.",
)
async def vowelreplace(self, message):
self.enabled = not self.enabled
self.db.set("vowel_replacer", "enabled", self.enabled)
if self.enabled:
response = self.strings("on")
else:
response = self.strings("off")
await utils.answer(message, response)
async def watcher(self, message: Message):
"""Автоматическая замена гласных на ё при получении собственного сообщения."""
if self.enabled and message.out:
vowels = "аеёиоуыэюяАЕЁИОУЫЭЮЯ"
message_text = message.text
replaced_text = "".join(
"ё" if char in vowels else char for char in message_text
)
await message.edit(replaced_text)

View File

@@ -0,0 +1,149 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: SMArchiver
# Description: unloads all messages from Favorites
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: SMArchiver
# scope: SMArchiver 0.0.1
# requires: zipfile
# ---------------------------------------------------------------------------------
import zipfile
import os
from datetime import datetime
from .. import loader, utils
@loader.tds
class SMArchiver(loader.Module):
"""unloads all messages from Favorites"""
strings = {
"name": "SMArchiver",
"archive_created": "🎉 Archive with messages has been successfully created: {filename}",
"no_messages": "⚠️ There are no messages in Saved Messages.",
"error": "❌ An error occurred: {error}",
"processing": "🛠️ Processing messages... Please wait.\n\nP.S: Be careful, if you have a lot of messages, you may get flooding, and if you have a lot of heavy files, the download will be slower than usual.",
}
strings_ru = {
"archive_created": "🎉 Архив с сообщениями успешно создан: {filename}",
"no_messages": "⚠️ В Сохраненных сообщениях нет сообщений.",
"error": "❌ Произошла ошибка: {error}",
"processing": "🛠️ Обработка сообщений... Пожалуйста, подождите.\n\nP.S: Будьте осторожны, если у вас много сообщений, вы можете получить флуд, а если у вас много тяжелых файлов, загрузка будет медленнее обычного.",
}
@loader.command(
ru_doc="выгружает все сообщения из Избранного / Saved Messages и собирает их в одном архиве.",
en_doc="downloads all messages from Favorites / Saved Messages and collects them in one archive.",
)
async def smdump(self, message):
await utils.answer(message, self.strings["processing"])
saved_messages = await message.client.get_messages("me", limit=None)
if not saved_messages:
await utils.answer(message, self.strings["no_messages"])
return
archive_path = self.create_archive(saved_messages)
try:
await message.client.send_file(
message.chat_id,
archive_path,
caption=self.strings["archive_created"].format(
filename=os.path.basename(archive_path)
),
)
except Exception as e:
await utils.answer(message, self.strings["error"].format(error=str(e)))
finally:
self.cleanup(archive_path)
def create_archive(self, saved_messages):
current_month = datetime.now().strftime("%B %Y")
archive_path = "saved_messages.zip"
with zipfile.ZipFile(archive_path, "w") as archive:
self.initialize_archive_structure(archive, current_month)
for msg in saved_messages:
await self.add_message_to_archive(msg, archive, current_month)
return archive_path
def initialize_archive_structure(self, archive, current_month):
month_folder = f"{current_month}/"
archive.writestr(month_folder, "")
message_folders = {
"Text Messages": f"{month_folder}Text Messages/",
"Voice Messages": f"{month_folder}Voice Messages/",
"Video Messages": f"{month_folder}Video Messages/",
"Videos": f"{month_folder}Videos/",
"Audios": f"{month_folder}Audios/",
"GIFs": f"{month_folder}GIFs/",
"Files": f"{month_folder}Files/",
}
for folder in message_folders.values():
archive.writestr(folder, "")
async def add_message_to_archive(self, msg, archive, current_month):
"""Обрабатывает отдельное сообщение и добавляет его в архив."""
if msg.message:
await self.add_text_message_to_archive(msg, archive, current_month)
if msg.media:
await self.add_media_to_archive(msg, archive, current_month)
async def add_text_message_to_archive(self, msg, archive, current_month):
timestamp = datetime.fromtimestamp(msg.date.timestamp()).strftime(
"%Y%m%d_%H%M%S"
)
safe_name = f"message_{timestamp}.txt"
archive.writestr(
os.path.join(f"{current_month}/Text Messages/", safe_name), msg.message
)
async def add_media_to_archive(self, msg, archive, current_month):
media_file = await msg.client.download_media(msg.media)
if media_file:
mime_type = (
msg.media.document.mime_type if hasattr(msg.media, "document") else None
)
folder = self.get_media_folder(mime_type, current_month)
archive.write(
media_file, os.path.join(folder, os.path.basename(media_file))
)
def get_media_folder(self, mime_type, current_month):
if mime_type:
if mime_type.startswith("audio/"):
return f"{current_month}/Audios/"
elif mime_type.startswith("video/"):
return f"{current_month}/Videos/"
elif mime_type.startswith("image/gif"):
return f"{current_month}/GIFs/"
return f"{current_month}/Files/"
def cleanup(self, archive_path):
if os.path.exists(archive_path):
os.remove(archive_path)

View File

@@ -0,0 +1,103 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: SafetyMod
# Description: generate random password
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api SafetyMod
# scope: Api SafetyMod 0.0.1
# ---------------------------------------------------------------------------------
import random
import string
from .. import loader, utils
def generate_password(
length: int, letters: bool = True, numbers: bool = True, symbols: bool = True
) -> str:
"""Generates a random password with customizable options.
Args:
length: The desired length of the password.
letters: Include lowercase and uppercase letters (default: True).
numbers: Include digits (default: True).
symbols: Include common symbols (default: True).
Returns:
A randomly generated password string.
Raises:
ValueError: If all character sets are disabled (letters, numbers, symbols).
"""
character_sets = []
if letters:
character_sets.append(string.ascii_letters)
if numbers:
character_sets.append(string.digits)
if symbols:
character_sets.append(string.punctuation)
if not character_sets:
raise ValueError("At least one of letters, numbers, or symbols must be True")
combined_characters = "".join(character_sets)
password = "".join(random.choice(combined_characters) for _ in range(length))
return password
@loader.tds
class SafetyMod(loader.Module):
"""generate random password"""
strings = {
"name": "Safety",
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Here is your secure password:</b> <code>{}</code>",
}
strings_ru = {
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Вот ваш безопасный пароль:</b> <code>{}</code>"
}
@loader.command(
ru_doc="Случайный пароль\n-n - цифры\n-s - символы \n -l - буквы",
en_doc="Random password\n-n - numbers\n-s - symbols \n -l - letters",
)
async def password(self, message):
"""random password\n-n - numbers\n-s - symbols \n -l - letters"""
text = message.text.split()
length = 10
letters = True
numbers = False
symbols = False
for i in text:
if i.startswith("password"):
length = int(i.split("password")[1])
elif i == "-n":
numbers = True
elif i == "-s":
symbols = True
elif i == "-l":
letters = True
password = generate_password(
length=length, letters=letters, numbers=numbers, symbols=symbols
)
await utils.answer(message, self.strings("pass").format(password))

View File

@@ -0,0 +1,358 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: TaskManager
# Description: Manages tasks with Telegram commands and inline keyboards.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: TaskManager
# scope: TaskManager 0.0.1
# ---------------------------------------------------------------------------------
import datetime
import json
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from .. import loader, utils
logger = logging.getLogger(__name__)
@dataclass
class Task:
"""Represents a task."""
description: str
due_date: Optional[datetime.datetime] = None
completed: bool = False
created_at: datetime.datetime = field(default_factory=datetime.datetime.now)
class TaskManager:
"""Manages tasks, storing them in a JSON file."""
def __init__(self, data_file: str):
self.data_file = data_file
self.tasks: Dict[int, List[Task]] = {}
self.load_data()
def load_data(self):
"""Loads task data from the JSON file."""
if os.path.exists(self.data_file):
try:
with open(self.data_file, "r") as f:
data = json.load(f)
self.tasks = {
int(user_id): [
Task(
description=task["description"],
due_date=datetime.datetime.fromisoformat(
task["due_date"]
)
if task["due_date"]
else None,
completed=task["completed"],
created_at=datetime.datetime.fromisoformat(
task["created_at"]
),
)
for task in task_list
]
for user_id, task_list in data.items()
}
except (FileNotFoundError, json.JSONDecodeError) as e:
logger.warning(f"Failed to load task data: {e}. Starting empty.")
self.tasks = {}
else:
self.tasks = {}
logger.info("Task data file not found. Starting empty.")
def save_data(self):
"""Saves task data to the JSON file."""
try:
with open(self.data_file, "w") as f:
data = {
user_id: [
{
"description": task.description,
"due_date": task.due_date.isoformat()
if task.due_date
else None,
"completed": task.completed,
"created_at": task.created_at.isoformat(),
}
for task in task_list
]
for user_id, task_list in self.tasks.items()
}
json.dump(data, f, indent=4, default=str)
except IOError as e:
logger.error(f"Failed to save task data: {e}")
def add_task(self, user_id: int, task: Task):
self.tasks.setdefault(user_id, []).append(task)
self.save_data()
def remove_task(self, user_id: int, index: int):
if user_id in self.tasks and 0 <= index < len(self.tasks[user_id]):
del self.tasks[user_id][index]
self.save_data()
else:
logger.warning(f"Invalid index for removal: {index}, user: {user_id}")
def complete_task(self, user_id: int, index: int):
if user_id in self.tasks and 0 <= index < len(self.tasks[user_id]):
self.tasks[user_id][index].completed = True
self.save_data()
else:
logger.warning(f"Invalid index for completion: {index}, user: {user_id}")
def get_tasks(self, user_id: int) -> List[Task]:
return self.tasks.get(user_id, [])
def clear_tasks(self, user_id: int):
if user_id in self.tasks:
self.tasks[user_id] = []
self.save_data()
else:
logger.info(f"No tasks to clear for user: {user_id}")
def get_task(self, user_id: int, index: int) -> Optional[Task]:
return (
self.tasks[user_id][index]
if user_id in self.tasks and 0 <= index < len(self.tasks[user_id])
else None
)
@loader.tds
class TaskManagerModule(loader.Module):
"""Manages tasks with Telegram commands and inline keyboards."""
strings = {
"name": "TaskManager",
"task_added": "<emoji document_id=5776375003280838798>✅</emoji> Task added.",
"task_removed": "<emoji document_id=5776375003280838798>✅</emoji> Task removed.",
"task_completed": "<emoji document_id=5776375003280838798>✅</emoji> Task completed.",
"task_not_found": "<emoji document_id=5778527486270770928>❌</emoji> Task not found.",
"no_tasks": "<emoji document_id=5956561916573782596>📄</emoji> No active tasks.",
"task_list": "<emoji document_id=5956561916573782596>📄</emoji> Your tasks:\n{}",
"invalid_index": "<emoji document_id=5778527486270770928>❌</emoji> Invalid index. Provide valid integer.",
"description_required": "<emoji document_id=5879813604068298387>❗️</emoji> Provide task description.",
"clear_confirmation": "⚠️ Delete all tasks?",
"tasks_cleared": "✅ All tasks deleted.",
"due_date_format": "<emoji document_id=5778527486270770928>❌</emoji> Invalid date. Use YYYY-MM-DD HH:MM.",
"task_info": "<emoji document_id=6028435952299413210></emoji> Task: {description}\n<emoji document_id=5967412305338568701>📅</emoji> Due: {due_date}\n<emoji document_id=5825794181183836432>✔️</emoji> Completed: {completed}\n<emoji document_id=5936170807716745162>🎛</emoji> Created: {created_at}",
"confirm_clear": "Confirm",
"cancel_clear": "Cancel",
"clear_cancelled": "❌ Deletion cancelled.",
"index_required": "⚠️ Provide task index.",
"clear_confirmation_text": "Are you sure you want to clear all tasks?",
"confirm": "Confirm",
"cancel": "Cancel",
}
strings_ru = {
"task_added": "<emoji document_id=5776375003280838798>✅</emoji> Задача добавлена.",
"task_removed": "<emoji document_id=5776375003280838798>✅</emoji> Задача удалена.",
"task_completed": "<emoji document_id=5776375003280838798>✅</emoji> Задача выполнена.",
"task_not_found": "<emoji document_id=5778527486270770928>❌</emoji> Задача не найдена.",
"no_tasks": "<emoji document_id=5956561916573782596>📄</emoji> Нет активных задач.",
"task_list": "<emoji document_id=5956561916573782596>📄</emoji> Ваши задачи:\n{}",
"invalid_index": "<emoji document_id=5778527486270770928>❌</emoji> Неверный индекс. Укажите целое число.",
"description_required": "<emoji document_id=5879813604068298387>❗️</emoji> Укажите описание задачи.",
"clear_confirmation": "⚠️ Удалить все задачи?",
"tasks_cleared": "Все задачи удалены.",
"due_date_format": "<emoji document_id=5778527486270770928>❌</emoji> Неверный формат даты. Используйте ГГГГ-ММ-ДД ЧЧ:ММ.",
"task_info": "<emoji document_id=6028435952299413210></emoji> Задача: {description}\n<emoji document_id=5967412305338568701>📅</emoji> Срок: {due_date}\n<emoji document_id=5825794181183836432>✔️</emoji> Выполнена: {completed}\n<emoji document_id=5936170807716745162>🎛</emoji> Создана: {created_at}",
"confirm_clear": "Подтвердить",
"cancel_clear": "Отменить",
"clear_cancelled": "❌ Удаление отменено.",
"index_required": "⚠️ Укажите индекс задачи.",
"clear_confirmation_text": "Вы уверены, что хотите удалить все задачи?",
"confirm": "Подтвердить",
"cancel": "Отменить",
}
def __init__(self):
self.task_manager: Optional[TaskManager] = None
async def client_ready(self, client, db):
self.task_manager = TaskManager(os.path.join(os.getcwd(), "tasks.json"))
@loader.command(
ru_doc="Добавить задачу:\n.taskadd <описание> | <дата (необязательно)>",
en_doc="Add task:\n.taskadd <description> | <date (opt)>",
)
async def taskadd(self, message):
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("description_required"))
return
try:
description, due_date_str = (
args.split("|", 1) if "|" in args else (args, None)
)
description = description.strip()
due_date_str = due_date_str.strip() if due_date_str else None
due_date = (
datetime.datetime.fromisoformat(due_date_str) if due_date_str else None
)
except ValueError:
await utils.answer(message, self.strings("due_date_format"))
return
except Exception as e:
logger.error(f"Error adding task: {e}")
await utils.answer(message, f"<emoji document_id=5778527486270770928>❌</emoji> Error: {e}")
return
task = Task(description=description, due_date=due_date)
self.task_manager.add_task(message.sender_id, task)
await utils.answer(message, self.strings("task_added"))
@loader.command(
ru_doc="[index] - удалить задачу",
en_doc="[index] - remove task"
)
async def taskremove(self, message):
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("index_required"))
return
try:
index = int(args) - 1
except ValueError:
await utils.answer(message, self.strings("invalid_index"))
return
if self.task_manager.get_task(message.sender_id, index) is None:
await utils.answer(message, self.strings("task_not_found"))
return
self.task_manager.remove_task(message.sender_id, index)
await utils.answer(message, self.strings("task_removed"))
@loader.command(
ru_doc="[index] - Завершите задачу",
en_doc="[index] - Complete task"
)
async def taskcomplete(self, message):
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("index_required"))
return
try:
index = int(args) - 1
except ValueError:
await utils.answer(message, self.strings("invalid_index"))
return
if self.task_manager.get_task(message.sender_id, index) is None:
await utils.answer(message, self.strings("task_not_found"))
return
self.task_manager.complete_task(message.sender_id, index)
await utils.answer(message, self.strings("task_completed"))
@loader.command(
ru_doc="Список задач",
en_doc="List tasks"
)
async def tasklist(self, message):
tasks = self.task_manager.get_tasks(message.sender_id)
if not tasks:
await utils.answer(message, self.strings("no_tasks"))
return
task_list_str = "\n".join(
[
f" {i + 1}. {'<emoji document_id=5776375003280838798>✅</emoji>' if task.completed else '<emoji document_id=5778527486270770928>❌</emoji>'} {task.description} (Due: {task.due_date.strftime('%Y-%m-%d %H:%M') if task.due_date else 'None'})"
for i, task in enumerate(tasks)
]
)
await utils.answer(message, self.strings("task_list").format(task_list_str))
@loader.command(
ru_doc="[index] - Посмотреть информацию о задаче",
en_doc="[index] - Show task info",
)
async def taskinfo(self, message):
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("index_required"))
return
try:
index = int(args) - 1
except ValueError:
await utils.answer(message, self.strings("invalid_index"))
return
task = self.task_manager.get_task(message.sender_id, index)
if not task:
await utils.answer(message, self.strings("task_not_found"))
return
due_date_str = (
task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "None"
)
created_at_str = task.created_at.strftime("%Y-%m-%d %H:%M")
await utils.answer(
message,
self.strings("task_info").format(
description=task.description,
due_date=due_date_str,
completed="Yes" if task.completed else "No",
created_at=created_at_str,
),
)
@loader.command(
ru_doc="Удалить все задачи",
en_doc="Clear all tasks"
)
async def taskclear(self, message):
await self.inline.form(
text=self.strings("clear_confirmation_text"),
message=message,
reply_markup=[
[
{"text": self.strings("confirm"), "callback": self.clear_confirm},
{"text": self.strings("cancel"), "callback": self.clear_cancel},
]
],
silent=True,
)
async def clear_confirm(self, call):
"""Callback for confirming task clearing."""
self.task_manager.clear_tasks(call.from_user.id)
await call.edit(self.strings("tasks_cleared"))
async def clear_cancel(self, call):
"""Callback for canceling task clearing."""
await call.edit(self.strings("clear_cancelled"))

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