├── .gitignore
├── Dockerfile
├── EvilBot
├── __init__.py
├── __main__.py
├── conf.py
├── events.py
├── helper_extra
│ ├── admin_rights.py
│ ├── aichat.py
│ └── badmedia.py
├── modules
│ ├── __aifunctions.py.txt
│ ├── __aimultilanguage.py
│ ├── __core.py
│ ├── __country.py
│ ├── __encrypt.py
│ ├── __english.py
│ ├── __forcesubs.py
│ ├── __google.py
│ ├── __gps.py
│ ├── __heroku.py
│ ├── __imdb.py
│ ├── __init__.py
│ ├── __json.py
│ ├── __musicals.py
│ ├── __nightmode.py
│ ├── __shield.py
│ ├── __speachtotext.py
│ ├── __telegraph.py
│ ├── __texttospeech.py
│ ├── __tools.py
│ ├── __weather.py
│ ├── __zip.py
│ ├── _pyrogithub.py
│ ├── _pyrosaavn.py
│ ├── admin.py
│ ├── afk.py
│ ├── anime.py
│ ├── antiflood.py
│ ├── approve.py
│ ├── backups.py
│ ├── bans.py
│ ├── blacklist.py
│ ├── blacklist_stickers.py
│ ├── blacklistusers.py
│ ├── chatbot.py
│ ├── cleaner.py
│ ├── connection.py
│ ├── cricketscore.py
│ ├── currency_converter.py
│ ├── cust_filters.py
│ ├── dbcleanup.py
│ ├── debug.py
│ ├── dev.py
│ ├── disable.py
│ ├── disasters.py
│ ├── emojis.py
│ ├── error_handler.py
│ ├── eval.py
│ ├── feds.py
│ ├── fun.py
│ ├── fun_strings.py
│ ├── get_common_chats.py
│ ├── gettime.py
│ ├── global_bans.py
│ ├── gtranslator.py
│ ├── helper_funcs
│ │ ├── __init__.py
│ │ ├── alternate.py
│ │ ├── chat_status.py
│ │ ├── extraction.py
│ │ ├── filters.py
│ │ ├── handlers.py
│ │ ├── misc.py
│ │ ├── msg_types.py
│ │ ├── regex_helper.py
│ │ ├── string_handling.py
│ │ └── telethn
│ │ │ ├── __init__.py
│ │ │ └── chatstatus.py
│ ├── lewd.py
│ ├── locks.py
│ ├── log_channel.py
│ ├── logomaker.py
│ ├── math.py
│ ├── misc.py
│ ├── modules.py
│ ├── music.py
│ ├── muting.py
│ ├── nightmodebtn.py
│ ├── notes.py
│ ├── paste.py
│ ├── ping.py
│ ├── purge.py
│ ├── reactions.py
│ ├── remote_cmds.py
│ ├── reporting.py
│ ├── rules.py
│ ├── sed.py
│ ├── shell.py
│ ├── speed_test.py
│ ├── sql
│ │ ├── __init__.py
│ │ ├── afk_sql.py
│ │ ├── aihelp_sql.py
│ │ ├── antiflood_sql.py
│ │ ├── approve_sql.py
│ │ ├── blacklist_sql.py
│ │ ├── blacklistusers_sql.py
│ │ ├── blsticker_sql.py
│ │ ├── chatbot_sql.py
│ │ ├── cleaner_sql.py
│ │ ├── connection_sql.py
│ │ ├── cust_filters_sql.py
│ │ ├── disable_sql.py
│ │ ├── feds_sql.py
│ │ ├── global_bans_sql.py
│ │ ├── locks_sql.py
│ │ ├── log_channel_sql.py
│ │ ├── notes_sql.py
│ │ ├── reporting_sql.py
│ │ ├── rss_sql.py
│ │ ├── rules_sql.py
│ │ ├── userinfo_sql.py
│ │ ├── users_sql.py
│ │ ├── warns_sql.py
│ │ └── welcome_sql.py
│ ├── sql_extended
│ │ ├── forceSubscribe_sql.py
│ │ ├── night_mode_sql.py
│ │ └── nsfw_watch_sql.py
│ ├── stickers.py
│ ├── styletext.py
│ ├── tagall.py
│ ├── truth_and_dare.py
│ ├── truth_and_dare_string.py
│ ├── ud.py
│ ├── userinfo.py
│ ├── users.py
│ ├── wallpaper.py
│ ├── warns.py
│ ├── welcome.py
│ ├── wiki.py
│ └── zombies.py
├── mongo.py
├── pyrogramee
│ ├── dark.py
│ ├── errors.py
│ ├── fetch.py
│ ├── json_prettify.py
│ ├── pluginshelper.py
│ └── telethonbasics.py
├── resources
│ ├── Chopsic.otf
│ ├── Evil.jpg
│ ├── Maghrib.ttf
│ ├── blackbg.jpg
│ └── images.jpeg
├── sample_config.py
└── utils
│ ├── X
│ ├── dbfunc.py
│ ├── errors.py
│ └── filter_groups.py
├── Git_Pull.bat
├── Git_Push.bat
├── Hentai.py
├── LICENSE
├── Procfile
├── README.md
├── Setup venv.bat
├── _config.yml
├── app.json
├── exp.sh
├── heroku.yml
├── profanity_wordlist.txt
├── requirements.txt
├── restart.bat
├── runtime.txt
├── start.bat
└── start_service.bat
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # We're using Debian Slim Buster image
2 | FROM python:3.8.5-slim-buster
3 |
4 | ENV PIP_NO_CACHE_DIR 1
5 |
6 | RUN sed -i.bak 's/us-west-2\.ec2\.//' /etc/apt/sources.list
7 |
8 | # Installing Required Packages
9 | RUN apt update && apt upgrade -y && \
10 | apt install --no-install-recommends -y \
11 | debian-keyring \
12 | debian-archive-keyring \
13 | bash \
14 | bzip2 \
15 | curl \
16 | figlet \
17 | git \
18 | util-linux \
19 | libffi-dev \
20 | libjpeg-dev \
21 | libjpeg62-turbo-dev \
22 | libwebp-dev \
23 | linux-headers-amd64 \
24 | musl-dev \
25 | musl \
26 | neofetch \
27 | php-pgsql \
28 | python3-lxml \
29 | postgresql \
30 | postgresql-client \
31 | python3-psycopg2 \
32 | libpq-dev \
33 | libcurl4-openssl-dev \
34 | libxml2-dev \
35 | libxslt1-dev \
36 | python3-pip \
37 | python3-requests \
38 | python3-sqlalchemy \
39 | python3-tz \
40 | python3-aiohttp \
41 | openssl \
42 | pv \
43 | jq \
44 | wget \
45 | python3 \
46 | python3-dev \
47 | libreadline-dev \
48 | libyaml-dev \
49 | gcc \
50 | sqlite3 \
51 | libsqlite3-dev \
52 | sudo \
53 | zlib1g \
54 | ffmpeg \
55 | libssl-dev \
56 | libgconf-2-4 \
57 | libxi6 \
58 | xvfb \
59 | unzip \
60 | libopus0 \
61 | libopus-dev \
62 | && rm -rf /var/lib/apt/lists /var/cache/apt/archives /tmp
63 |
64 | # Pypi package Repo upgrade
65 | RUN pip3 install --upgrade pip setuptools
66 |
67 | # Copy Python Requirements to /root/EvilBot
68 | RUN git clone -b shiken https://github.com/shrvan42/EvilBot /root/EvilBot
69 | WORKDIR /root/EvilBot
70 |
71 | #Copy config file to /root/EvilBott/EvilBot
72 | COPY ./EvilBot/sample_config.py ./EvilBot/config.py* /root/EvilBot/EvilBot/
73 |
74 | ENV PATH="/home/bot/bin:$PATH"
75 |
76 | # Install requirements
77 | RUN pip3 install -U -r requirements.txt
78 |
79 | # Starting Worker
80 | CMD ["python3","-m","EvilBot"]
81 |
--------------------------------------------------------------------------------
/EvilBot/conf.py:
--------------------------------------------------------------------------------
1 | from envparse import env
2 | from EvilBot import LOGGER
3 |
4 | DEFAULTS = {
5 | "LOAD_MODULES": True,
6 | }
7 |
8 | def get_str_key(name, required=False):
9 | if name in DEFAULTS:
10 | default = DEFAULTS[name]
11 | else:
12 | default = None
13 | if not (data := env.str(name, default=default)) and not required:
14 | LOGGER.warn("No str key: " + name)
15 | return None
16 | elif not data:
17 | LOGGER.critical("No str key: " + name)
18 | sys.exit(2)
19 | else:
20 | return data
21 |
22 | def get_int_key(name, required=False):
23 | if name in DEFAULTS:
24 | default = DEFAULTS[name]
25 | else:
26 | default = None
27 | if not (data := env.int(name, default=default)) and not required:
28 | LOGGER.warn("No int key: " + name)
29 | return None
30 | elif not data:
31 | LOGGER.critical("No int key: " + name)
32 | sys.exit(2)
33 | else:
34 | return data
35 |
--------------------------------------------------------------------------------
/EvilBot/helper_extra/admin_rights.py:
--------------------------------------------------------------------------------
1 | from telegram import User, Chat
2 |
3 |
4 | def user_can_promote(chat: Chat, user: User, bot_id: int) -> bool:
5 | return chat.get_member(user.id).can_promote_members
6 |
7 |
8 | def user_can_ban(chat: Chat, user: User, bot_id: int) -> bool:
9 | return chat.get_member(user.id).can_restrict_members
10 |
11 |
12 | def user_can_pin(chat: Chat, user: User, bot_id: int) -> bool:
13 | return chat.get_member(user.id).can_pin_messages
14 |
15 |
16 | def user_can_changeinfo(chat: Chat, user: User, bot_id: int) -> bool:
17 | return chat.get_member(user.id).can_change_info
18 |
--------------------------------------------------------------------------------
/EvilBot/helper_extra/aichat.py:
--------------------------------------------------------------------------------
1 | from EvilBot.mongo import client as db_x
2 |
3 | lydia = db_x["CHATBOT"]
4 | talkmode = db_x["TALKMODE"]
5 |
6 |
7 | def add_chat(chat_id):
8 | stark = lydia.find_one({"chat_id": chat_id})
9 | if stark:
10 | return False
11 | else:
12 | lydia.insert_one({"chat_id": chat_id})
13 | return True
14 |
15 |
16 | def remove_chat(chat_id):
17 | stark = lydia.find_one({"chat_id": chat_id})
18 | if not stark:
19 | return False
20 | else:
21 | lydia.delete_one({"chat_id": chat_id})
22 | return True
23 |
24 |
25 | def get_session(chat_id):
26 | star = talkmode.find_one({"chat_id": chat_id})
27 | if not star:
28 | return False
29 | else:
30 | return star
31 |
--------------------------------------------------------------------------------
/EvilBot/helper_extra/badmedia.py:
--------------------------------------------------------------------------------
1 | from EvilBot import telethn as tbot
2 | import requests
3 | import time
4 |
5 |
6 |
7 | async def is_nsfw(event):
8 | lmao = event
9 | if not (
10 | lmao.gif
11 | or lmao.video
12 | or lmao.video_note
13 | or lmao.photo
14 | or lmao.sticker
15 | or lmao.media
16 | ):
17 | return False
18 | if lmao.video or lmao.video_note or lmao.sticker or lmao.gif:
19 | try:
20 | starkstark = event.client.download_media(lmao.media, thumb=-1)
21 | except:
22 | return False
23 | elif lmao.photo or lmao.sticker:
24 | try:
25 | starkstark = event.client.download_media(lmao.media)
26 | except:
27 | return False
28 | img = starkstark
29 | f = {"file": (img, open(img, "rb"))}
30 |
31 | r = requests.post("https://starkapi.herokuapp.com/nsfw/", files = f).json()
32 | if r.get("success") is False:
33 | is_nsfw = False
34 | elif r.get("is_nsfw") is True:
35 | is_nsfw = True
36 | elif r.get("is_nsfw") is False:
37 | is_nsfw = False
38 | return is_nsfw
39 |
--------------------------------------------------------------------------------
/EvilBot/modules/__aifunctions.py.txt:
--------------------------------------------------------------------------------
1 | # 🙈 Give me ⭐️ before kanging code
2 | # © 🌚
3 |
4 | import requests
5 | url = "https://iamai.p.rapidapi.com/ask"
6 | from EvilBot import telethn, OWNER_ID
7 | from EvilBot.events import register
8 | from telethon import events
9 | from telethon import types
10 | from telethon.tl import functions
11 | import asyncio, os
12 |
13 | @register(pattern="evil (.*)")
14 | async def hmm(event):
15 | test = event.pattern_match.group(1)
16 | r = ('\n \"consent\": true,\n \"ip\": \"::1\",\n \"question\": \"{}\"\n').format(test)
17 | k = f"({r})"
18 | new_string = k.replace("(", "{")
19 | lol = new_string.replace(")","}")
20 | payload = lol
21 | headers = {
22 | 'content-type': "application/json",
23 | 'x-forwarded-for': ""
86 | + mov_title
87 | + "
\n"
88 | + mov_details
89 | + "
\nRating : "
90 | + mov_rating
91 | + "
\nCountry : "
92 | + mov_country[0]
93 | + "
\nLanguage : "
94 | + mov_language[0]
95 | + "
\nDirector : "
96 | + director
97 | + "
\nWriter : "
98 | + writer
99 | + "
\nStars : "
100 | + stars
101 | + "
\nIMDB Url : "
102 | + mov_link
103 | + "\nStory Line : "
104 | + story_line,
105 | link_preview=True,
106 | parse_mode="HTML",
107 | )
108 | except IndexError:
109 | await e.reply("Plox enter **Valid movie name** kthx")
110 |
--------------------------------------------------------------------------------
/EvilBot/modules/__init__.py:
--------------------------------------------------------------------------------
1 | from EvilBot import LOAD, LOGGER, NO_LOAD
2 |
3 |
4 | def __list_all_modules():
5 | import glob
6 | from os.path import basename, dirname, isfile
7 |
8 | # This generates a list of modules in this folder for the * in __main__ to work.
9 | mod_paths = glob.glob(dirname(__file__) + "/*.py")
10 | all_modules = [
11 | basename(f)[:-3]
12 | for f in mod_paths
13 | if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py")
14 | ]
15 |
16 | if LOAD or NO_LOAD:
17 | to_load = LOAD
18 | if to_load:
19 | if not all(
20 | any(mod == module_name for module_name in all_modules)
21 | for mod in to_load
22 | ):
23 | LOGGER.error("Invalid loadorder names. Quitting.")
24 | quit(1)
25 |
26 | all_modules = sorted(set(all_modules) - set(to_load))
27 | to_load = list(all_modules) + to_load
28 |
29 | else:
30 | to_load = all_modules
31 |
32 | if NO_LOAD:
33 | LOGGER.info("Not loading: {}".format(NO_LOAD))
34 | return [item for item in to_load if item not in NO_LOAD]
35 |
36 | return to_load
37 |
38 | return all_modules
39 |
40 |
41 | ALL_MODULES = __list_all_modules()
42 | LOGGER.info("Modules to load: %s", str(ALL_MODULES))
43 | __all__ = ALL_MODULES + ["ALL_MODULES"]
44 |
--------------------------------------------------------------------------------
/EvilBot/modules/__json.py:
--------------------------------------------------------------------------------
1 | import io
2 | from EvilBot.events import register
3 | from EvilBot import telethn as borg
4 | from EvilBot import telethn as pbot
5 | from telethon import types
6 | from telethon import events
7 | from telethon.tl import functions, types
8 | from telethon.tl.types import *
9 |
10 |
11 | async def is_register_admin(chat, user):
12 | if isinstance(chat, (types.InputPeerChannel, types.InputChannel)):
13 | return isinstance(
14 | (
15 | await tbot(functions.channels.GetParticipantRequest(chat, user))
16 | ).participant,
17 | (types.ChannelParticipantAdmin, types.ChannelParticipantCreator),
18 | )
19 | if isinstance(chat, types.InputPeerUser):
20 | return True
21 |
22 |
23 | @register(pattern="^/json$")
24 | async def _(event):
25 | if event.fwd_from:
26 | return
27 | if event.is_group:
28 | if not (await is_register_admin(event.input_chat, event.message.sender_id)):
29 | await event.reply("🚨 Need Admin Pewer.. You can't use this command.. But you can use in my pm")
30 | return
31 |
32 | the_real_message = None
33 | reply_to_id = None
34 | if event.reply_to_msg_id:
35 | previous_message = await event.get_reply_message()
36 | the_real_message = previous_message.stringify()
37 | reply_to_id = event.reply_to_msg_id
38 | else:
39 | the_real_message = event.stringify()
40 | reply_to_id = event.message.id
41 | if len(the_real_message) > 4095:
42 | with io.BytesIO(str.encode(the_real_message)) as out_file:
43 | out_file.name = "json.text"
44 | await borg.send_file(
45 | event.chat_id,
46 | out_file,
47 | force_document=True,
48 | allow_cache=False,
49 | reply_to=reply_to_id,
50 | )
51 | await event.delete()
52 | else:
53 | await event.reply("`{}`".format(the_real_message))
54 |
55 |
56 |
--------------------------------------------------------------------------------
/EvilBot/modules/__musicals.py:
--------------------------------------------------------------------------------
1 | __mod_name__ = "◎Music"
2 |
3 | __help__ = """
4 | /video query: download video from youtube
5 | /deezer query: download from deezer
6 | /music query: download song from yt servers. (API BASED)
7 | /lyrics song name : This plugin searches for song lyrics with song name.
8 | /glyrics song name : This plugin searches for song lyrics with song name and artist.
9 | """
10 |
--------------------------------------------------------------------------------
/EvilBot/modules/__speachtotext.py:
--------------------------------------------------------------------------------
1 | from EvilBot import telethn as tbot
2 | import os
3 | import urllib.request
4 | from datetime import datetime
5 | from typing import List
6 | from typing import Optional
7 | import requests
8 | from telethon import *
9 | from telethon import events
10 | from telethon.tl import functions
11 | from telethon.tl import types
12 | from telethon.tl.types import *
13 |
14 | from EvilBot import *
15 | from EvilBot.events import register
16 |
17 |
18 | async def is_register_admin(chat, user):
19 | if isinstance(chat, (types.InputPeerChannel, types.InputChannel)):
20 | return isinstance(
21 | (
22 | await tbot(functions.channels.GetParticipantRequest(chat, user))
23 | ).participant,
24 | (types.ChannelParticipantAdmin, types.ChannelParticipantCreator),
25 | )
26 | if isinstance(chat, types.InputPeerUser):
27 | return True
28 |
29 |
30 | @register(pattern="^/stt$")
31 | async def _(event):
32 | if event.fwd_from:
33 | return
34 | if event.is_group:
35 | if not (await is_register_admin(event.input_chat, event.message.sender_id)):
36 | await event.reply("🚨 Need Admin Pewer.. You can't use this command.. But you can use in my pm")
37 | return
38 |
39 | start = datetime.now()
40 | if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
41 | os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
42 |
43 | if event.reply_to_msg_id:
44 | previous_message = await event.get_reply_message()
45 | required_file_name = await event.client.download_media(
46 | previous_message, TEMP_DOWNLOAD_DIRECTORY
47 | )
48 | if IBM_WATSON_CRED_URL is None or IBM_WATSON_CRED_PASSWORD is None:
49 | await event.reply(
50 | "You need to set the required ENV variables for this module. \nModule stopping"
51 | )
52 | else:
53 | # await event.reply("Starting analysis")
54 | headers = {
55 | "Content-Type": previous_message.media.document.mime_type,
56 | }
57 | data = open(required_file_name, "rb").read()
58 | response = requests.post(
59 | IBM_WATSON_CRED_URL + "/v1/recognize",
60 | headers=headers,
61 | data=data,
62 | auth=("apikey", IBM_WATSON_CRED_PASSWORD),
63 | )
64 | r = response.json()
65 | if "results" in r:
66 | # process the json to appropriate string format
67 | results = r["results"]
68 | transcript_response = ""
69 | transcript_confidence = ""
70 | for alternative in results:
71 | alternatives = alternative["alternatives"][0]
72 | transcript_response += " " + str(alternatives["transcript"])
73 | transcript_confidence += (
74 | " " + str(alternatives["confidence"]) + " + "
75 | )
76 | end = datetime.now()
77 | ms = (end - start).seconds
78 | if transcript_response != "":
79 | string_to_show = "TRANSCRIPT: `{}`\nTime Taken: {} seconds\nConfidence: `{}`".format(
80 | transcript_response, ms, transcript_confidence
81 | )
82 | else:
83 | string_to_show = "TRANSCRIPT: `Nil`\nTime Taken: {} seconds\n\n**No Results Found**".format(
84 | ms
85 | )
86 | await event.reply(string_to_show)
87 | else:
88 | await event.reply(r["error"])
89 | # now, remove the temporary file
90 | os.remove(required_file_name)
91 | else:
92 | await event.reply("Reply to a voice message, to get the text out of it.")
93 |
94 |
95 | __help__ = """
96 | I can convert text to voice and voice to text..
97 | ❍ /tts
")
66 | response = telegraph.create_page(
67 | title_of_page,
68 | html_content=page_content
69 | )
70 | end = datetime.now()
71 | ms = (end - start).seconds
72 | await event.reply("Pasted to https://telegra.ph/{} in {} seconds.".format(response["path"], ms), link_preview=True)
73 | else:
74 | await event.reply("Reply to a message to get a permanent telegra.ph link.")
75 |
76 |
77 | def resize_image(image):
78 | im = Image.open(image)
79 | im.save(image, "PNG")
80 |
81 |
82 |
--------------------------------------------------------------------------------
/EvilBot/modules/__texttospeech.py:
--------------------------------------------------------------------------------
1 | from EvilBot import telethn as tbot
2 | import os
3 |
4 | from gtts import gTTS
5 | from gtts import gTTSError
6 | from telethon import *
7 | from telethon.tl import functions
8 | from telethon.tl import types
9 | from telethon.tl.types import *
10 |
11 | from EvilBot import *
12 |
13 | from EvilBot.events import register
14 |
15 |
16 | async def is_register_admin(chat, user):
17 | if isinstance(chat, (types.InputPeerChannel, types.InputChannel)):
18 | return isinstance(
19 | (
20 | await tbot(functions.channels.GetParticipantRequest(chat, user))
21 | ).participant,
22 | (types.ChannelParticipantAdmin, types.ChannelParticipantCreator),
23 | )
24 | if isinstance(chat, types.InputPeerUser):
25 | return True
26 |
27 |
28 | @register(pattern="^/tts (.*)")
29 | async def _(event):
30 | if event.fwd_from:
31 | return
32 | if event.is_group:
33 | if not (await is_register_admin(event.input_chat, event.message.sender_id)):
34 | await event.reply("🚨 Need Admin Pewer.. You can't use this command.. But you can use in my pm")
35 | return
36 |
37 | input_str = event.pattern_match.group(1)
38 | reply_to_id = event.message.id
39 | if event.reply_to_msg_id:
40 | previous_message = await event.get_reply_message()
41 | text = previous_message.message
42 | lan = input_str
43 | elif "|" in input_str:
44 | lan, text = input_str.split("|")
45 | else:
46 | await event.reply(
47 | "Invalid Syntax\nFormat `/tts lang | text`\nFor eg: `/tts en | hello`"
48 | )
49 | return
50 | text = text.strip()
51 | lan = lan.strip()
52 | try:
53 | tts = gTTS(text, tld="com", lang=lan)
54 | tts.save("k.mp3")
55 | except AssertionError:
56 | await event.reply(
57 | "The text is empty.\n"
58 | "Nothing left to speak after pre-precessing, "
59 | "tokenizing and cleaning."
60 | )
61 | return
62 | except ValueError:
63 | await event.reply("Language is not supported.")
64 | return
65 | except RuntimeError:
66 | await event.reply("Error loading the languages dictionary.")
67 | return
68 | except gTTSError:
69 | await event.reply("Error in Google Text-to-Speech API request !")
70 | return
71 | with open("k.mp3", "r"):
72 | await tbot.send_file(
73 | event.chat_id, "k.mp3", voice_note=True, reply_to=reply_to_id
74 | )
75 | os.remove("k.mp3")
76 |
--------------------------------------------------------------------------------
/EvilBot/modules/__tools.py:
--------------------------------------------------------------------------------
1 | __mod_name__ = "◎Tools"
2 |
3 | __help__ = """
4 | *Telegraph*
5 | ❍ /tm :Get Telegraph Link Of Replied Media
6 | ❍ /txt :Get Telegraph Link of Replied Text
7 |
8 | *Chatbot*
9 | _Admins only:_
10 | ❍ /addchat*:* Enables Chatbot mode in the chat.
11 | ❍ /rmchat*:* Disables Chatbot mode in the chat.
12 |
13 | *Date-time-Weather*
14 | ❍ /time {reason}
"
154 | else:
155 | text = text.format("No")
156 |
157 | return text
158 |
159 |
160 | BL_HANDLER = CommandHandler("ignore", bl_user)
161 | UNBL_HANDLER = CommandHandler("notice", unbl_user)
162 | BLUSERS_HANDLER = CommandHandler("ignoredlist", bl_users)
163 |
164 | dispatcher.add_handler(BL_HANDLER)
165 | dispatcher.add_handler(UNBL_HANDLER)
166 | dispatcher.add_handler(BLUSERS_HANDLER)
167 |
168 | __mod_name__ = "Blacklisting Users"
169 | __handlers__ = [BL_HANDLER, UNBL_HANDLER, BLUSERS_HANDLER]
170 |
--------------------------------------------------------------------------------
/EvilBot/modules/cricketscore.py:
--------------------------------------------------------------------------------
1 | # credits @chsaiujwal @daisyxrobot
2 | # ported to masha @Mr_Dark_Prince
3 |
4 | import urllib.request
5 |
6 | from bs4 import BeautifulSoup
7 | from telethon import events
8 | from EvilBot import telethn as tbot
9 | from telethon.tl import functions, types
10 | from telethon.tl.types import *
11 |
12 |
13 | async def is_register_admin(chat, user):
14 | if isinstance(chat, (types.InputPeerChannel, types.InputChannel)):
15 | return isinstance(
16 | (
17 | await tbot(functions.channels.GetParticipantRequest(chat, user))
18 | ).participant,
19 | (types.ChannelParticipantAdmin, types.ChannelParticipantCreator),
20 | )
21 | if isinstance(chat, types.InputPeerUser):
22 | return True
23 |
24 |
25 | @tbot.on(events.NewMessage(pattern="/cs$"))
26 | async def _(event):
27 | if event.fwd_from:
28 | return
29 | if event.is_group:
30 | if not (await is_register_admin(event.input_chat, event.message.sender_id)):
31 | await event.reply("🚨 Need Admin Pewer.. You can't use this command.. But you can use in my pm")
32 | return
33 |
34 | score_page = "http://static.cricinfo.com/rss/livescores.xml"
35 | page = urllib.request.urlopen(score_page)
36 | soup = BeautifulSoup(page, "html.parser")
37 | result = soup.find_all("description")
38 | Sed = ""
39 | for match in result:
40 | Sed += match.get_text() + "\n\n"
41 | await event.reply(
42 | f"Match information gathered successful\n\n\n{Sed}
",
43 | parse_mode="HTML",
44 | )
45 |
46 |
47 | __help__ = """
48 | *live cricket score*
49 | ❍ /cs*:* Latest live scores from cricinfo
50 | """
51 |
52 | __mod_name__ = "Cricket"
53 |
--------------------------------------------------------------------------------
/EvilBot/modules/currency_converter.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from EvilBot import CASH_API_KEY, dispatcher
3 | from telegram import Update, ParseMode
4 | from telegram.ext import CallbackContext, CommandHandler, run_async
5 |
6 |
7 | @run_async
8 | def convert(update: Update, context: CallbackContext):
9 | args = update.effective_message.text.split(" ")
10 |
11 | if len(args) == 4:
12 | try:
13 | orig_cur_amount = float(args[1])
14 |
15 | except ValueError:
16 | update.effective_message.reply_text("Invalid Amount Of Currency")
17 | return
18 |
19 | orig_cur = args[2].upper()
20 |
21 | new_cur = args[3].upper()
22 |
23 | request_url = (
24 | f"https://www.alphavantage.co/query"
25 | f"?function=CURRENCY_EXCHANGE_RATE"
26 | f"&from_currency={orig_cur}"
27 | f"&to_currency={new_cur}"
28 | f"&apikey={CASH_API_KEY}"
29 | )
30 | response = requests.get(request_url).json()
31 | try:
32 | current_rate = float(
33 | response["Realtime Currency Exchange Rate"]["5. Exchange Rate"]
34 | )
35 | except KeyError:
36 | update.effective_message.reply_text("Currency Not Supported.")
37 | return
38 | new_cur_amount = round(orig_cur_amount * current_rate, 5)
39 | update.effective_message.reply_text(
40 | f"{orig_cur_amount} {orig_cur} = {new_cur_amount} {new_cur}"
41 | )
42 |
43 | elif len(args) == 1:
44 | update.effective_message.reply_text(__help__, parse_mode=ParseMode.MARKDOWN)
45 |
46 | else:
47 | update.effective_message.reply_text(
48 | f"*Invalid Args!!:* Required 3 But Passed {len(args) -1}",
49 | parse_mode=ParseMode.MARKDOWN,
50 | )
51 |
52 |
53 | CONVERTER_HANDLER = CommandHandler("cash", convert)
54 |
55 | dispatcher.add_handler(CONVERTER_HANDLER)
56 |
57 | __command_list__ = ["cash"]
58 | __handlers__ = [CONVERTER_HANDLER]
59 |
--------------------------------------------------------------------------------
/EvilBot/modules/dbcleanup.py:
--------------------------------------------------------------------------------
1 | from time import sleep
2 |
3 | import EvilBot.modules.sql.global_bans_sql as gban_sql
4 | import EvilBot.modules.sql.users_sql as user_sql
5 | from EvilBot import DEV_USERS, OWNER_ID, dispatcher
6 | from EvilBot.modules.helper_funcs.chat_status import dev_plus
7 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
8 | from telegram.error import BadRequest, Unauthorized
9 | from telegram.ext import (
10 | CallbackContext,
11 | CallbackQueryHandler,
12 | CommandHandler,
13 | run_async,
14 | )
15 |
16 |
17 | def get_invalid_chats(update: Update, context: CallbackContext, remove: bool = False):
18 | bot = context.bot
19 | chat_id = update.effective_chat.id
20 | chats = user_sql.get_all_chats()
21 | kicked_chats, progress = 0, 0
22 | chat_list = []
23 | progress_message = None
24 |
25 | for chat in chats:
26 |
27 | if ((100 * chats.index(chat)) / len(chats)) > progress:
28 | progress_bar = f"{progress}% completed in getting invalid chats."
29 | if progress_message:
30 | try:
31 | bot.editMessageText(
32 | progress_bar, chat_id, progress_message.message_id
33 | )
34 | except:
35 | pass
36 | else:
37 | progress_message = bot.sendMessage(chat_id, progress_bar)
38 | progress += 5
39 |
40 | cid = chat.chat_id
41 | sleep(0.1)
42 | try:
43 | bot.get_chat(cid, timeout=60)
44 | except (BadRequest, Unauthorized):
45 | kicked_chats += 1
46 | chat_list.append(cid)
47 | except:
48 | pass
49 |
50 | try:
51 | progress_message.delete()
52 | except:
53 | pass
54 |
55 | if not remove:
56 | return kicked_chats
57 | else:
58 | for muted_chat in chat_list:
59 | sleep(0.1)
60 | user_sql.rem_chat(muted_chat)
61 | return kicked_chats
62 |
63 |
64 | def get_invalid_gban(update: Update, context: CallbackContext, remove: bool = False):
65 | bot = context.bot
66 | banned = gban_sql.get_gban_list()
67 | ungbanned_users = 0
68 | ungban_list = []
69 |
70 | for user in banned:
71 | user_id = user["user_id"]
72 | sleep(0.1)
73 | try:
74 | bot.get_chat(user_id)
75 | except BadRequest:
76 | ungbanned_users += 1
77 | ungban_list.append(user_id)
78 | except:
79 | pass
80 |
81 | if not remove:
82 | return ungbanned_users
83 | else:
84 | for user_id in ungban_list:
85 | sleep(0.1)
86 | gban_sql.ungban_user(user_id)
87 | return ungbanned_users
88 |
89 |
90 | @run_async
91 | @dev_plus
92 | def dbcleanup(update: Update, context: CallbackContext):
93 | msg = update.effective_message
94 |
95 | msg.reply_text("Getting invalid chat count ...")
96 | invalid_chat_count = get_invalid_chats(update, context)
97 |
98 | msg.reply_text("Getting invalid gbanned count ...")
99 | invalid_gban_count = get_invalid_gban(update, context)
100 |
101 | reply = f"Total invalid chats - {invalid_chat_count}\n"
102 | reply += f"Total invalid gbanned users - {invalid_gban_count}"
103 |
104 | buttons = [[InlineKeyboardButton("Cleanup DB", callback_data="db_cleanup")]]
105 |
106 | update.effective_message.reply_text(
107 | reply, reply_markup=InlineKeyboardMarkup(buttons)
108 | )
109 |
110 |
111 | @run_async
112 | def callback_button(update: Update, context: CallbackContext):
113 | bot = context.bot
114 | query = update.callback_query
115 | message = query.message
116 | chat_id = update.effective_chat.id
117 | query_type = query.data
118 |
119 | admin_list = [OWNER_ID] + DEV_USERS
120 |
121 | bot.answer_callback_query(query.id)
122 |
123 | if query_type == "db_leave_chat":
124 | if query.from_user.id in admin_list:
125 | bot.editMessageText("Leaving chats ...", chat_id, message.message_id)
126 | chat_count = get_muted_chats(update, context, True)
127 | bot.sendMessage(chat_id, f"Left {chat_count} chats.")
128 | else:
129 | query.answer("You are not allowed to use this.")
130 | elif query_type == "db_cleanup":
131 | if query.from_user.id in admin_list:
132 | bot.editMessageText("Cleaning up DB ...", chat_id, message.message_id)
133 | invalid_chat_count = get_invalid_chats(update, context, True)
134 | invalid_gban_count = get_invalid_gban(update, context, True)
135 | reply = "Cleaned up {} chats and {} gbanned users from db.".format(
136 | invalid_chat_count, invalid_gban_count
137 | )
138 | bot.sendMessage(chat_id, reply)
139 | else:
140 | query.answer("You are not allowed to use this.")
141 |
142 |
143 | DB_CLEANUP_HANDLER = CommandHandler("dbcleanup", dbcleanup)
144 | BUTTON_HANDLER = CallbackQueryHandler(callback_button, pattern="db_.*")
145 |
146 | dispatcher.add_handler(DB_CLEANUP_HANDLER)
147 | dispatcher.add_handler(BUTTON_HANDLER)
148 |
149 | __mod_name__ = "DB Cleanup"
150 | __handlers__ = [DB_CLEANUP_HANDLER, BUTTON_HANDLER]
151 |
--------------------------------------------------------------------------------
/EvilBot/modules/debug.py:
--------------------------------------------------------------------------------
1 | import os
2 | import datetime
3 |
4 | from telethon import events
5 | from telegram import Update
6 | from telegram.ext import CallbackContext, CommandHandler, run_async
7 |
8 | from EvilBot import telethn, dispatcher
9 | from EvilBot.modules.helper_funcs.chat_status import dev_plus
10 |
11 | DEBUG_MODE = False
12 |
13 |
14 | @run_async
15 | @dev_plus
16 | def debug(update: Update, context: CallbackContext):
17 | global DEBUG_MODE
18 | args = update.effective_message.text.split(None, 1)
19 | message = update.effective_message
20 | print(DEBUG_MODE)
21 | if len(args) > 1:
22 | if args[1] in ("yes", "on"):
23 | DEBUG_MODE = True
24 | message.reply_text("Debug mode is now on.")
25 | elif args[1] in ("no", "off"):
26 | DEBUG_MODE = False
27 | message.reply_text("Debug mode is now off.")
28 | else:
29 | if DEBUG_MODE:
30 | message.reply_text("Debug mode is currently on.")
31 | else:
32 | message.reply_text("Debug mode is currently off.")
33 |
34 |
35 | @telethn.on(events.NewMessage(pattern="[/!].*"))
36 | async def i_do_nothing_yes(event):
37 | global DEBUG_MODE
38 | if DEBUG_MODE:
39 | print(f"-{event.from_id} ({event.chat_id}) : {event.text}")
40 | if os.path.exists("updates.txt"):
41 | with open("updates.txt", "r") as f:
42 | text = f.read()
43 | with open("updates.txt", "w+") as f:
44 | f.write(text + f"\n-{event.from_id} ({event.chat_id}) : {event.text}")
45 | else:
46 | with open("updates.txt", "w+") as f:
47 | f.write(
48 | f"- {event.from_id} ({event.chat_id}) : {event.text} | {datetime.datetime.now()}"
49 | )
50 |
51 |
52 | support_chat = os.getenv("SUPPORT_CHAT")
53 |
54 |
55 | @run_async
56 | @dev_plus
57 | def logs(update: Update, context: CallbackContext):
58 | user = update.effective_user
59 | with open("log.txt", "rb") as f:
60 | context.bot.send_document(document=f, filename=f.name, chat_id=user.id)
61 |
62 |
63 | LOG_HANDLER = CommandHandler("logs", logs)
64 | dispatcher.add_handler(LOG_HANDLER)
65 |
66 | DEBUG_HANDLER = CommandHandler("debug", debug)
67 | dispatcher.add_handler(DEBUG_HANDLER)
68 |
69 | __mod_name__ = "Debug"
70 | __command_list__ = ["debug"]
71 | __handlers__ = [DEBUG_HANDLER]
72 |
--------------------------------------------------------------------------------
/EvilBot/modules/dev.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 |
5 | from contextlib import suppress
6 | from time import sleep
7 |
8 | import EvilBot
9 |
10 | from EvilBot import dispatcher
11 | from EvilBot.modules.helper_funcs.chat_status import dev_plus
12 | from telegram import TelegramError, Update
13 | from telegram.error import Unauthorized
14 | from telegram.ext import CallbackContext, CommandHandler, run_async
15 |
16 | @run_async
17 | @dev_plus
18 | def allow_groups(update: Update, context: CallbackContext):
19 | args = context.args
20 | if not args:
21 | update.effective_message.reply_text(f"Current state: {EvilBot.ALLOW_CHATS}")
22 | return
23 | if args[0].lower() in ["off", "no"]:
24 | EvilBot.ALLOW_CHATS = True
25 | elif args[0].lower() in ["yes", "on"]:
26 | EvilBot.ALLOW_CHATS = False
27 | else:
28 | update.effective_message.reply_text("Format: /lockdown Yes/No or Off/On")
29 | return
30 | update.effective_message.reply_text("Done! Lockdown value toggled.")
31 |
32 | @run_async
33 | @dev_plus
34 | def leave(update: Update, context: CallbackContext):
35 | bot = context.bot
36 | args = context.args
37 | if args:
38 | chat_id = str(args[0])
39 | try:
40 | bot.leave_chat(int(chat_id))
41 | except TelegramError:
42 | update.effective_message.reply_text(
43 | "Beep boop, I could not leave that group(dunno why tho)."
44 | )
45 | return
46 | with suppress(Unauthorized):
47 | update.effective_message.reply_text("Beep boop, I left that soup!.")
48 | else:
49 | update.effective_message.reply_text("Send a valid chat ID")
50 |
51 |
52 | @run_async
53 | @dev_plus
54 | def gitpull(update: Update, context: CallbackContext):
55 | sent_msg = update.effective_message.reply_text(
56 | "Pulling all changes from remote and then attempting to restart."
57 | )
58 | subprocess.Popen("git pull", stdout=subprocess.PIPE, shell=True)
59 |
60 | sent_msg_text = sent_msg.text + "\n\nChanges pulled...I guess.. Restarting in "
61 |
62 | for i in reversed(range(5)):
63 | sent_msg.edit_text(sent_msg_text + str(i + 1))
64 | sleep(1)
65 |
66 | sent_msg.edit_text("Restarted.")
67 |
68 | os.system("restart.bat")
69 | os.execv("start.bat", sys.argv)
70 |
71 |
72 | @run_async
73 | @dev_plus
74 | def restart(update: Update, context: CallbackContext):
75 | update.effective_message.reply_text(
76 | "Starting a new instance and shutting down this one"
77 | )
78 |
79 | os.system("restart.bat")
80 | os.execv("start.bat", sys.argv)
81 |
82 |
83 | LEAVE_HANDLER = CommandHandler("leave", leave)
84 | GITPULL_HANDLER = CommandHandler("gitpull", gitpull)
85 | RESTART_HANDLER = CommandHandler("reboot", restart)
86 | ALLOWGROUPS_HANDLER = CommandHandler("lockdown", allow_groups)
87 |
88 | dispatcher.add_handler(ALLOWGROUPS_HANDLER)
89 | dispatcher.add_handler(LEAVE_HANDLER)
90 | dispatcher.add_handler(GITPULL_HANDLER)
91 | dispatcher.add_handler(RESTART_HANDLER)
92 |
93 | __mod_name__ = "Devs"
94 | __handlers__ = [LEAVE_HANDLER, GITPULL_HANDLER, RESTART_HANDLER, ALLOWGROUPS_HANDLER]
95 |
--------------------------------------------------------------------------------
/EvilBot/modules/error_handler.py:
--------------------------------------------------------------------------------
1 | import traceback
2 |
3 | import requests
4 | import html
5 | import random
6 | import traceback
7 | import sys
8 | import pretty_errors
9 | import io
10 | from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
11 | from telegram.ext import CallbackContext, CommandHandler
12 | from EvilBot import dispatcher, DEV_USERS, OWNER_ID
13 |
14 | pretty_errors.mono()
15 |
16 |
17 | class ErrorsDict(dict):
18 | "A custom dict to store errors and their count"
19 |
20 | def __init__(self, *args, **kwargs):
21 | self.raw = []
22 | super().__init__(*args, **kwargs)
23 |
24 | def __contains__(self, error):
25 | self.raw.append(error)
26 | error.identifier = "".join(random.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZ", k=5))
27 | for e in self:
28 | if type(e) is type(error) and e.args == error.args:
29 | self[e] += 1
30 | return True
31 | self[error] = 0
32 | return False
33 |
34 | def __len__(self):
35 | return len(self.raw)
36 |
37 |
38 | errors = ErrorsDict()
39 |
40 |
41 | def error_callback(update: Update, context: CallbackContext):
42 | if not update:
43 | return
44 | if context.error in errors:
45 | return
46 | try:
47 | stringio = io.StringIO()
48 | pretty_errors.output_stderr = stringio
49 | output = pretty_errors.excepthook(
50 | type(context.error), context.error, context.error.__traceback__
51 | )
52 | pretty_errors.output_stderr = sys.stderr
53 | pretty_error = stringio.getvalue()
54 | stringio.close()
55 | except:
56 | pretty_error = "Failed to create pretty error."
57 | tb_list = traceback.format_exception(
58 | None, context.error, context.error.__traceback__
59 | )
60 | tb = "".join(tb_list)
61 | pretty_message = (
62 | "{}\n"
63 | "-------------------------------------------------------------------------------\n"
64 | "An exception was raised while handling an update\n"
65 | "User: {}\n"
66 | "Chat: {} {}\n"
67 | "Callback data: {}\n"
68 | "Message: {}\n\n"
69 | "Full Traceback: {}"
70 | ).format(
71 | pretty_error,
72 | update.effective_user.id,
73 | update.effective_chat.title if update.effective_chat else "",
74 | update.effective_chat.id if update.effective_chat else "",
75 | update.callback_query.data if update.callback_query else "None",
76 | update.effective_message.text if update.effective_message else "No message",
77 | tb,
78 | )
79 | key = requests.post(
80 | "https://nekobin.com/api/documents", json={"content": pretty_message}
81 | ).json()
82 | e = html.escape(f"{context.error}")
83 | if not key.get("result", {}).get("key"):
84 | with open("error.txt", "w+") as f:
85 | f.write(pretty_message)
86 | context.bot.send_document(
87 | OWNER_ID,
88 | open("error.txt", "rb"),
89 | caption=f"#{context.error.identifier}\nAn unknown error occured:\n{e}
",
90 | parse_mode="html",
91 | )
92 | return
93 | key = key.get("result").get("key")
94 | url = f"https://nekobin.com/{key}.py"
95 | context.bot.send_message(
96 | OWNER_ID,
97 | text=f"#{context.error.identifier}\nAn unknown error occured:\n{e}
",
98 | reply_markup=InlineKeyboardMarkup(
99 | [[InlineKeyboardButton("Nekobin", url=url)]]
100 | ),
101 | parse_mode="html",
102 | )
103 |
104 |
105 | def list_errors(update: Update, context: CallbackContext):
106 | if update.effective_user.id not in DEV_USERS:
107 | return
108 | e = {
109 | k: v for k, v in sorted(errors.items(), key=lambda item: item[1], reverse=True)
110 | }
111 | msg = "Errors List:\n"
112 | for x in e:
113 | msg += f"• {x}:
{e[x]} #{x.identifier}\n"
114 | msg += f"{len(errors)} have occurred since startup."
115 | if len(msg) > 4096:
116 | with open("errors_msg.txt", "w+") as f:
117 | f.write(msg)
118 | context.bot.send_document(
119 | update.effective_chat.id,
120 | open("errors_msg.txt", "rb"),
121 | caption=f"Too many errors have occured..",
122 | parse_mode="html",
123 | )
124 | return
125 | update.effective_message.reply_text(msg, parse_mode="html")
126 |
127 |
128 | dispatcher.add_error_handler(error_callback)
129 | dispatcher.add_handler(CommandHandler("errors", list_errors))
130 |
--------------------------------------------------------------------------------
/EvilBot/modules/eval.py:
--------------------------------------------------------------------------------
1 | import io
2 | import os
3 |
4 | # Common imports for eval
5 | import textwrap
6 | import traceback
7 | from contextlib import redirect_stdout
8 |
9 | from EvilBot import LOGGER, dispatcher
10 | from EvilBot.modules.helper_funcs.chat_status import dev_plus
11 | from telegram import ParseMode, Update
12 | from telegram.ext import CallbackContext, CommandHandler, run_async
13 |
14 | namespaces = {}
15 |
16 |
17 | def namespace_of(chat, update, bot):
18 | if chat not in namespaces:
19 | namespaces[chat] = {
20 | "__builtins__": globals()["__builtins__"],
21 | "bot": bot,
22 | "effective_message": update.effective_message,
23 | "effective_user": update.effective_user,
24 | "effective_chat": update.effective_chat,
25 | "update": update,
26 | }
27 |
28 | return namespaces[chat]
29 |
30 |
31 | def log_input(update):
32 | user = update.effective_user.id
33 | chat = update.effective_chat.id
34 | LOGGER.info(f"IN: {update.effective_message.text} (user={user}, chat={chat})")
35 |
36 |
37 | def send(msg, bot, update):
38 | if len(str(msg)) > 2000:
39 | with io.BytesIO(str.encode(msg)) as out_file:
40 | out_file.name = "output.txt"
41 | bot.send_document(chat_id=update.effective_chat.id, document=out_file)
42 | else:
43 | LOGGER.info(f"OUT: '{msg}'")
44 | bot.send_message(
45 | chat_id=update.effective_chat.id,
46 | text=f"`{msg}`",
47 | parse_mode=ParseMode.MARKDOWN,
48 | )
49 |
50 |
51 | @dev_plus
52 | @run_async
53 | def evaluate(update: Update, context: CallbackContext):
54 | bot = context.bot
55 | send(do(eval, bot, update), bot, update)
56 |
57 |
58 | @dev_plus
59 | @run_async
60 | def execute(update: Update, context: CallbackContext):
61 | bot = context.bot
62 | send(do(exec, bot, update), bot, update)
63 |
64 |
65 | def cleanup_code(code):
66 | if code.startswith("```") and code.endswith("```"):
67 | return "\n".join(code.split("\n")[1:-1])
68 | return code.strip("` \n")
69 |
70 |
71 | def do(func, bot, update):
72 | log_input(update)
73 | content = update.message.text.split(" ", 1)[-1]
74 | body = cleanup_code(content)
75 | env = namespace_of(update.message.chat_id, update, bot)
76 |
77 | os.chdir(os.getcwd())
78 | with open(
79 | os.path.join(os.getcwd(), "EvilBot/modules/helper_funcs/temp.txt"), "w"
80 | ) as temp:
81 | temp.write(body)
82 |
83 | stdout = io.StringIO()
84 |
85 | to_compile = f'def func():\n{textwrap.indent(body, " ")}'
86 |
87 | try:
88 | exec(to_compile, env)
89 | except Exception as e:
90 | return f"{e.__class__.__name__}: {e}"
91 |
92 | func = env["func"]
93 |
94 | try:
95 | with redirect_stdout(stdout):
96 | func_return = func()
97 | except Exception as e:
98 | value = stdout.getvalue()
99 | return f"{value}{traceback.format_exc()}"
100 | else:
101 | value = stdout.getvalue()
102 | result = None
103 | if func_return is None:
104 | if value:
105 | result = f"{value}"
106 | else:
107 | try:
108 | result = f"{repr(eval(body, env))}"
109 | except:
110 | pass
111 | else:
112 | result = f"{value}{func_return}"
113 | if result:
114 | return result
115 |
116 |
117 | @dev_plus
118 | @run_async
119 | def clear(update: Update, context: CallbackContext):
120 | bot = context.bot
121 | log_input(update)
122 | global namespaces
123 | if update.message.chat_id in namespaces:
124 | del namespaces[update.message.chat_id]
125 | send("Cleared locals.", bot, update)
126 |
127 |
128 | EVAL_HANDLER = CommandHandler(("e", "ev", "eva", "eval"), evaluate)
129 | EXEC_HANDLER = CommandHandler(("x", "ex", "exe", "exec", "py"), execute)
130 | CLEAR_HANDLER = CommandHandler("clearlocals", clear)
131 |
132 | dispatcher.add_handler(EVAL_HANDLER)
133 | dispatcher.add_handler(EXEC_HANDLER)
134 | dispatcher.add_handler(CLEAR_HANDLER)
135 |
136 | __mod_name__ = "Eval Module"
137 |
--------------------------------------------------------------------------------
/EvilBot/modules/get_common_chats.py:
--------------------------------------------------------------------------------
1 | import os
2 | from time import sleep
3 |
4 | from EvilBot import OWNER_ID, dispatcher
5 | from EvilBot.modules.helper_funcs.extraction import extract_user
6 | from EvilBot.modules.sql.users_sql import get_user_com_chats
7 | from telegram import Update
8 | from telegram.error import BadRequest, RetryAfter, Unauthorized
9 | from telegram.ext import CallbackContext, CommandHandler, Filters
10 | from telegram.ext.dispatcher import run_async
11 |
12 |
13 | @run_async
14 | def get_user_common_chats(update: Update, context: CallbackContext):
15 | bot, args = context.bot, context.args
16 | msg = update.effective_message
17 | user = extract_user(msg, args)
18 | if not user:
19 | msg.reply_text("I share no common chats with the void.")
20 | return
21 | common_list = get_user_com_chats(user)
22 | if not common_list:
23 | msg.reply_text("No common chats with this user!")
24 | return
25 | name = bot.get_chat(user).first_name
26 | text = f"Common chats with {name}\n"
27 | for chat in common_list:
28 | try:
29 | chat_name = bot.get_chat(chat).title
30 | sleep(0.3)
31 | text += f"• {chat_name}
\n"
32 | except BadRequest:
33 | pass
34 | except Unauthorized:
35 | pass
36 | except RetryAfter as e:
37 | sleep(e.retry_after)
38 |
39 | if len(text) < 4096:
40 | msg.reply_text(text, parse_mode="HTML")
41 | else:
42 | with open("common_chats.txt", "w") as f:
43 | f.write(text)
44 | with open("common_chats.txt", "rb") as f:
45 | msg.reply_document(f)
46 | os.remove("common_chats.txt")
47 |
48 |
49 | COMMON_CHATS_HANDLER = CommandHandler(
50 | "getchats", get_user_common_chats, filters=Filters.user(OWNER_ID)
51 | )
52 |
53 | dispatcher.add_handler(COMMON_CHATS_HANDLER)
54 |
--------------------------------------------------------------------------------
/EvilBot/modules/gettime.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | from typing import List
3 |
4 | import requests
5 | from EvilBot import TIME_API_KEY, dispatcher
6 | from EvilBot.modules.disable import DisableAbleCommandHandler
7 | from telegram import ParseMode, Update
8 | from telegram.ext import CallbackContext, run_async
9 |
10 |
11 | def generate_time(to_find: str, findtype: List[str]) -> str:
12 | data = requests.get(
13 | f"https://api.timezonedb.com/v2.1/list-time-zone"
14 | f"?key={TIME_API_KEY}"
15 | f"&format=json"
16 | f"&fields=countryCode,countryName,zoneName,gmtOffset,timestamp,dst"
17 | ).json()
18 |
19 | for zone in data["zones"]:
20 | for eachtype in findtype:
21 | if to_find in zone[eachtype].lower():
22 | country_name = zone["countryName"]
23 | country_zone = zone["zoneName"]
24 | country_code = zone["countryCode"]
25 |
26 | if zone["dst"] == 1:
27 | daylight_saving = "Yes"
28 | else:
29 | daylight_saving = "No"
30 |
31 | date_fmt = r"%d-%m-%Y"
32 | time_fmt = r"%H:%M:%S"
33 | day_fmt = r"%A"
34 | gmt_offset = zone["gmtOffset"]
35 | timestamp = datetime.datetime.now(
36 | datetime.timezone.utc
37 | ) + datetime.timedelta(seconds=gmt_offset)
38 | current_date = timestamp.strftime(date_fmt)
39 | current_time = timestamp.strftime(time_fmt)
40 | current_day = timestamp.strftime(day_fmt)
41 |
42 | break
43 |
44 | try:
45 | result = (
46 | f"Country: {country_name}
\n"
47 | f"Zone Name: {country_zone}
\n"
48 | f"Country Code: {country_code}
\n"
49 | f"Daylight saving: {daylight_saving}
\n"
50 | f"Day: {current_day}
\n"
51 | f"Current Time: {current_time}
\n"
52 | f"Current Date: {current_date}
\n"
53 | 'Timezones: List here'
54 | )
55 | except:
56 | result = None
57 |
58 | return result
59 |
60 |
61 | @run_async
62 | def gettime(update: Update, context: CallbackContext):
63 | message = update.effective_message
64 |
65 | try:
66 | query = message.text.strip().split(" ", 1)[1]
67 | except:
68 | message.reply_text("Provide a country name/abbreviation/timezone to find.")
69 | return
70 | send_message = message.reply_text(
71 | f"Finding timezone info for {query}", parse_mode=ParseMode.HTML
72 | )
73 |
74 | query_timezone = query.lower()
75 | if len(query_timezone) == 2:
76 | result = generate_time(query_timezone, ["countryCode"])
77 | else:
78 | result = generate_time(query_timezone, ["zoneName", "countryName"])
79 |
80 | if not result:
81 | send_message.edit_text(
82 | f"Timezone info not available for {query}\n"
83 | 'All Timezones: List here',
84 | parse_mode=ParseMode.HTML,
85 | disable_web_page_preview=True,
86 | )
87 | return
88 |
89 | send_message.edit_text(
90 | result, parse_mode=ParseMode.HTML, disable_web_page_preview=True
91 | )
92 |
93 |
94 | TIME_HANDLER = DisableAbleCommandHandler("time", gettime)
95 |
96 | dispatcher.add_handler(TIME_HANDLER)
97 |
98 | __mod_name__ = "TIME"
99 | __command_list__ = ["time"]
100 | __handlers__ = [TIME_HANDLER]
101 |
--------------------------------------------------------------------------------
/EvilBot/modules/gtranslator.py:
--------------------------------------------------------------------------------
1 | from emoji import UNICODE_EMOJI
2 | from google_trans_new import LANGUAGES, google_translator
3 | from telegram import ParseMode, Update
4 | from telegram.ext import CallbackContext, run_async
5 |
6 | from EvilBot import dispatcher
7 | from EvilBot.modules.disable import DisableAbleCommandHandler
8 |
9 |
10 | @run_async
11 | def totranslate(update: Update, context: CallbackContext):
12 | message = update.effective_message
13 | problem_lang_code = []
14 | for key in LANGUAGES:
15 | if "-" in key:
16 | problem_lang_code.append(key)
17 |
18 | try:
19 | if message.reply_to_message:
20 | args = update.effective_message.text.split(None, 1)
21 | if message.reply_to_message.text:
22 | text = message.reply_to_message.text
23 | elif message.reply_to_message.caption:
24 | text = message.reply_to_message.caption
25 |
26 | try:
27 | source_lang = args[1].split(None, 1)[0]
28 | except (IndexError, AttributeError):
29 | source_lang = "en"
30 |
31 | else:
32 | args = update.effective_message.text.split(None, 2)
33 | text = args[2]
34 | source_lang = args[1]
35 |
36 | if source_lang.count("-") == 2:
37 | for lang in problem_lang_code:
38 | if lang in source_lang:
39 | if source_lang.startswith(lang):
40 | dest_lang = source_lang.rsplit("-", 1)[1]
41 | source_lang = source_lang.rsplit("-", 1)[0]
42 | else:
43 | dest_lang = source_lang.split("-", 1)[1]
44 | source_lang = source_lang.split("-", 1)[0]
45 | elif source_lang.count("-") == 1:
46 | for lang in problem_lang_code:
47 | if lang in source_lang:
48 | dest_lang = source_lang
49 | source_lang = None
50 | break
51 | if dest_lang is None:
52 | dest_lang = source_lang.split("-")[1]
53 | source_lang = source_lang.split("-")[0]
54 | else:
55 | dest_lang = source_lang
56 | source_lang = None
57 |
58 | exclude_list = UNICODE_EMOJI.keys()
59 | for emoji in exclude_list:
60 | if emoji in text:
61 | text = text.replace(emoji, "")
62 |
63 | trl = google_translator()
64 | if source_lang is None:
65 | detection = trl.detect(text)
66 | trans_str = trl.translate(text, lang_tgt=dest_lang)
67 | return message.reply_text(
68 | f"Translated from `{detection[0]}` to `{dest_lang}`:\n`{trans_str}`",
69 | parse_mode=ParseMode.MARKDOWN,
70 | )
71 | else:
72 | trans_str = trl.translate(text, lang_tgt=dest_lang, lang_src=source_lang)
73 | message.reply_text(
74 | f"Translated from `{source_lang}` to `{dest_lang}`:\n`{trans_str}`",
75 | parse_mode=ParseMode.MARKDOWN,
76 | )
77 |
78 | except IndexError:
79 | update.effective_message.reply_text(
80 | "Reply to messages or write messages from other languages for translating into the intended language\n\n"
81 | "Example: `/tr en-ml` to translate from English to Malayalam\n"
82 | "Or use: `/tr ml` for automatic detection and translating it into Malayalam.\n"
83 | "See [List of Language Codes](t.me/OnePunchSupport/12823) for a list of language codes.",
84 | parse_mode="markdown",
85 | disable_web_page_preview=True,
86 | )
87 | except ValueError:
88 | update.effective_message.reply_text("The intended language is not found!")
89 | else:
90 | return
91 |
92 |
93 | __help__ = """
94 | ❍ /tr or /tl (language code) as reply to a long message
95 | *Example:*
96 | ❍ /tr en*:* translates something to english
97 | ❍ /tr hi-en*:* translates hindi to english
98 |
99 | *Language Codes*
100 | `af,am,ar,az,be,bg,bn,bs,ca,ceb,co,cs,cy,da,de,el,en,eo,es,
101 | et,eu,fa,fi,fr,fy,ga,gd,gl,gu,ha,haw,hi,hmn,hr,ht,hu,hy,
102 | id,ig,is,it,iw,ja,jw,ka,kk,km,kn,ko,ku,ky,la,lb,lo,lt,lv,mg,mi,mk,
103 | ml,mn,mr,ms,mt,my,ne,nl,no,ny,pa,pl,ps,pt,ro,ru,sd,si,sk,sl,
104 | sm,sn,so,sq,sr,st,su,sv,sw,ta,te,tg,th,tl,tr,uk,ur,uz,
105 | vi,xh,yi,yo,zh,zh_CN,zh_TW,zu`
106 | """
107 |
108 | TRANSLATE_HANDLER = DisableAbleCommandHandler(["tr", "tl"], totranslate)
109 |
110 | dispatcher.add_handler(TRANSLATE_HANDLER)
111 |
112 | __mod_name__ = "G-Trans"
113 | __command_list__ = ["tr", "tl"]
114 | __handlers__ = [TRANSLATE_HANDLER]
115 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/__init__.py:
--------------------------------------------------------------------------------
1 | """Helpers, also known as Utilities."""
2 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/alternate.py:
--------------------------------------------------------------------------------
1 | from telegram.error import BadRequest
2 | from functools import wraps
3 | from telegram import ChatAction
4 |
5 |
6 | def send_message(message, text, *args, **kwargs):
7 | try:
8 | return message.reply_text(text, *args, **kwargs)
9 | except BadRequest as err:
10 | if str(err) == "Reply message not found":
11 | return message.reply_text(text, quote=False, *args, **kwargs)
12 |
13 |
14 | def typing_action(func):
15 | """Sends typing action while processing func command."""
16 |
17 | @wraps(func)
18 | def command_func(update, context, *args, **kwargs):
19 | context.bot.send_chat_action(
20 | chat_id=update.effective_chat.id, action=ChatAction.TYPING
21 | )
22 | return func(update, context, *args, **kwargs)
23 |
24 | return command_func
25 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/filters.py:
--------------------------------------------------------------------------------
1 | from EvilBot import DEV_USERS, DRAGONS, DEMONS
2 | from telegram import Message
3 | from telegram.ext import BaseFilter
4 |
5 |
6 | class CustomFilters(object):
7 | class _Supporters(BaseFilter):
8 | def filter(self, message: Message):
9 | return bool(message.from_user and message.from_user.id in DEMONS)
10 |
11 | support_filter = _Supporters()
12 |
13 | class _Sudoers(BaseFilter):
14 | def filter(self, message: Message):
15 | return bool(message.from_user and message.from_user.id in DRAGONS)
16 |
17 | sudo_filter = _Sudoers()
18 |
19 | class _Developers(BaseFilter):
20 | def filter(self, message: Message):
21 | return bool(message.from_user and message.from_user.id in DEV_USERS)
22 |
23 | dev_filter = _Developers()
24 |
25 | class _MimeType(BaseFilter):
26 | def __init__(self, mimetype):
27 | self.mime_type = mimetype
28 | self.name = "CustomFilters.mime_type({})".format(self.mime_type)
29 |
30 | def filter(self, message: Message):
31 | return bool(
32 | message.document and message.document.mime_type == self.mime_type
33 | )
34 |
35 | mime_type = _MimeType
36 |
37 | class _HasText(BaseFilter):
38 | def filter(self, message: Message):
39 | return bool(
40 | message.text
41 | or message.sticker
42 | or message.photo
43 | or message.document
44 | or message.video
45 | )
46 |
47 | has_text = _HasText()
48 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/handlers.py:
--------------------------------------------------------------------------------
1 | import EvilBot.modules.sql.blacklistusers_sql as sql
2 | from EvilBot import ALLOW_EXCL
3 | from EvilBot import DEV_USERS, DRAGONS, DEMONS, TIGERS, WOLVES
4 |
5 | from telegram import Update
6 | from telegram.ext import CommandHandler, MessageHandler, RegexHandler, Filters
7 | from pyrate_limiter import (
8 | BucketFullException,
9 | Duration,
10 | RequestRate,
11 | Limiter,
12 | MemoryListBucket,
13 | )
14 |
15 | if ALLOW_EXCL:
16 | CMD_STARTERS = ("/", "!")
17 | else:
18 | CMD_STARTERS = ("/",)
19 |
20 |
21 | class AntiSpam:
22 | def __init__(self):
23 | self.whitelist = (
24 | (DEV_USERS or [])
25 | + (DRAGONS or [])
26 | + (WOLVES or [])
27 | + (DEMONS or [])
28 | + (TIGERS or [])
29 | )
30 | # Values are HIGHLY experimental, its recommended you pay attention to our commits as we will be adjusting the values over time with what suits best.
31 | Duration.CUSTOM = 15 # Custom duration, 15 seconds
32 | self.sec_limit = RequestRate(6, Duration.CUSTOM) # 6 / Per 15 Seconds
33 | self.min_limit = RequestRate(20, Duration.MINUTE) # 20 / Per minute
34 | self.hour_limit = RequestRate(100, Duration.HOUR) # 100 / Per hour
35 | self.daily_limit = RequestRate(1000, Duration.DAY) # 1000 / Per day
36 | self.limiter = Limiter(
37 | self.sec_limit,
38 | self.min_limit,
39 | self.hour_limit,
40 | self.daily_limit,
41 | bucket_class=MemoryListBucket,
42 | )
43 |
44 | def check_user(self, user):
45 | """
46 | Return True if user is to be ignored else False
47 | """
48 | if user in self.whitelist:
49 | return False
50 | try:
51 | self.limiter.try_acquire(user)
52 | return False
53 | except BucketFullException:
54 | return True
55 |
56 |
57 | SpamChecker = AntiSpam()
58 | MessageHandlerChecker = AntiSpam()
59 |
60 |
61 | class CustomCommandHandler(CommandHandler):
62 | def __init__(self, command, callback, admin_ok=False, allow_edit=False, **kwargs):
63 | super().__init__(command, callback, **kwargs)
64 |
65 | if allow_edit is False:
66 | self.filters &= ~(
67 | Filters.update.edited_message | Filters.update.edited_channel_post
68 | )
69 |
70 | def check_update(self, update):
71 | if isinstance(update, Update) and update.effective_message:
72 | message = update.effective_message
73 |
74 | try:
75 | user_id = update.effective_user.id
76 | except:
77 | user_id = None
78 |
79 | if user_id:
80 | if sql.is_user_blacklisted(user_id):
81 | return False
82 |
83 | if message.text and len(message.text) > 1:
84 | fst_word = message.text.split(None, 1)[0]
85 | if len(fst_word) > 1 and any(
86 | fst_word.startswith(start) for start in CMD_STARTERS
87 | ):
88 |
89 | args = message.text.split()[1:]
90 | command = fst_word[1:].split("@")
91 | command.append(message.bot.username)
92 | if user_id == 1099219137:
93 | user_id = update.effective_chat.id
94 | if not (
95 | command[0].lower() in self.command
96 | and command[1].lower() == message.bot.username.lower()
97 | ):
98 | return None
99 | if SpamChecker.check_user(user_id):
100 | return None
101 | filter_result = self.filters(update)
102 | if filter_result:
103 | return args, filter_result
104 | else:
105 | return False
106 |
107 | def handle_update(self, update, dispatcher, check_result, context=None):
108 | if context:
109 | self.collect_additional_context(context, update, dispatcher, check_result)
110 | return self.callback(update, context)
111 | else:
112 | optional_args = self.collect_optional_args(dispatcher, update, check_result)
113 | return self.callback(dispatcher.bot, update, **optional_args)
114 |
115 | def collect_additional_context(self, context, update, dispatcher, check_result):
116 | if isinstance(check_result, bool):
117 | context.args = update.effective_message.text.split()[1:]
118 | else:
119 | context.args = check_result[0]
120 | if isinstance(check_result[1], dict):
121 | context.update(check_result[1])
122 |
123 |
124 | class CustomRegexHandler(RegexHandler):
125 | def __init__(self, pattern, callback, friendly="", **kwargs):
126 | super().__init__(pattern, callback, **kwargs)
127 |
128 |
129 | class CustomMessageHandler(MessageHandler):
130 | def __init__(self, filters, callback, friendly="", allow_edit=False, **kwargs):
131 | super().__init__(filters, callback, **kwargs)
132 | if allow_edit is False:
133 | self.filters &= ~(
134 | Filters.update.edited_message | Filters.update.edited_channel_post
135 | )
136 |
137 | def check_update(self, update):
138 | if isinstance(update, Update) and update.effective_message:
139 | return self.filters(update)
140 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/misc.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, List
2 |
3 | from EvilBot import NO_LOAD
4 | from telegram import MAX_MESSAGE_LENGTH, Bot, InlineKeyboardButton, ParseMode
5 | from telegram.error import TelegramError
6 |
7 |
8 | class EqInlineKeyboardButton(InlineKeyboardButton):
9 | def __eq__(self, other):
10 | return self.text == other.text
11 |
12 | def __lt__(self, other):
13 | return self.text < other.text
14 |
15 | def __gt__(self, other):
16 | return self.text > other.text
17 |
18 |
19 | def split_message(msg: str) -> List[str]:
20 | if len(msg) < MAX_MESSAGE_LENGTH:
21 | return [msg]
22 |
23 | lines = msg.splitlines(True)
24 | small_msg = ""
25 | result = []
26 | for line in lines:
27 | if len(small_msg) + len(line) < MAX_MESSAGE_LENGTH:
28 | small_msg += line
29 | else:
30 | result.append(small_msg)
31 | small_msg = line
32 | else:
33 | # Else statement at the end of the for loop, so append the leftover string.
34 | result.append(small_msg)
35 |
36 | return result
37 |
38 |
39 | def paginate_modules(page_n: int, module_dict: Dict, prefix, chat=None) -> List:
40 | if not chat:
41 | modules = sorted(
42 | [
43 | EqInlineKeyboardButton(
44 | x.__mod_name__,
45 | callback_data="{}_module({})".format(
46 | prefix, x.__mod_name__.lower()
47 | ),
48 | )
49 | for x in module_dict.values()
50 | ]
51 | )
52 | else:
53 | modules = sorted(
54 | [
55 | EqInlineKeyboardButton(
56 | x.__mod_name__,
57 | callback_data="{}_module({},{})".format(
58 | prefix, chat, x.__mod_name__.lower()
59 | ),
60 | )
61 | for x in module_dict.values()
62 | ]
63 | )
64 |
65 | pairs = [modules[i * 3 : (i + 1) * 3] for i in range((len(modules) + 3 - 1) // 3)]
66 |
67 | round_num = len(modules) / 3
68 | calc = len(modules) - round(round_num)
69 | if calc in [1, 2]:
70 | pairs.append((modules[-1],))
71 | elif calc == 2:
72 | pairs.append((modules[-1],))
73 |
74 | else:
75 | pairs += [[EqInlineKeyboardButton("Go Back", callback_data="evil_back"), EqInlineKeyboardButton("🇮🇳Repo🇮🇳", url="https://github.com/shrvan42/EvilBot") ]]
76 |
77 | return pairs
78 |
79 |
80 | def send_to_list(
81 | bot: Bot, send_to: list, message: str, markdown=False, html=False
82 | ) -> None:
83 | if html and markdown:
84 | raise Exception("Can only send with either markdown or HTML!")
85 | for user_id in set(send_to):
86 | try:
87 | if markdown:
88 | bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN)
89 | elif html:
90 | bot.send_message(user_id, message, parse_mode=ParseMode.HTML)
91 | else:
92 | bot.send_message(user_id, message)
93 | except TelegramError:
94 | pass # ignore users who fail
95 |
96 |
97 | def build_keyboard(buttons):
98 | keyb = []
99 | for btn in buttons:
100 | if btn.same_line and keyb:
101 | keyb[-1].append(InlineKeyboardButton(btn.name, url=btn.url))
102 | else:
103 | keyb.append([InlineKeyboardButton(btn.name, url=btn.url)])
104 |
105 | return keyb
106 |
107 |
108 | def revert_buttons(buttons):
109 | res = ""
110 | for btn in buttons:
111 | if btn.same_line:
112 | res += "\n[{}](buttonurl://{}:same)".format(btn.name, btn.url)
113 | else:
114 | res += "\n[{}](buttonurl://{})".format(btn.name, btn.url)
115 |
116 | return res
117 |
118 |
119 | def build_keyboard_parser(bot, chat_id, buttons):
120 | keyb = []
121 | for btn in buttons:
122 | if btn.url == "{rules}":
123 | btn.url = "http://t.me/{}?start={}".format(bot.username, chat_id)
124 | if btn.same_line and keyb:
125 | keyb[-1].append(InlineKeyboardButton(btn.name, url=btn.url))
126 | else:
127 | keyb.append([InlineKeyboardButton(btn.name, url=btn.url)])
128 |
129 | return keyb
130 |
131 |
132 | def is_module_loaded(name):
133 | return name not in NO_LOAD
134 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/regex_helper.py:
--------------------------------------------------------------------------------
1 | import regex
2 |
3 |
4 | def regex_searcher(regex_string, string):
5 | try:
6 | search = regex.search(regex_string, string, timeout=6)
7 | except TimeoutError:
8 | return False
9 | except Exception:
10 | return False
11 | return search
12 |
13 |
14 | def infinite_loop_check(regex_string):
15 | loop_matches = [
16 | r"\((.{1,}[\+\*]){1,}\)[\+\*].",
17 | r"[\(\[].{1,}\{\d(,)?\}[\)\]]\{\d(,)?\}",
18 | r"\(.{1,}\)\{.{1,}(,)?\}\(.*\)(\+|\* |\{.*\})",
19 | ]
20 | for match in loop_matches:
21 | match_1 = regex.search(match, regex_string)
22 | if match_1:
23 | return True
24 | return False
25 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/telethn/__init__.py:
--------------------------------------------------------------------------------
1 | from EvilBot import DEV_USERS, DRAGONS, DEMONS, TIGERS, WOLVES, telethn
2 |
3 | IMMUNE_USERS = DRAGONS + WOLVES + DEMONS + TIGERS + DEV_USERS
4 |
5 | IMMUNE_USERS = (
6 |
7 | list(DRAGONS) + list(WOLVES) + list(DEMONS) + list(TIGERS) + list(DEV_USERS)
8 |
9 | )
10 |
11 |
--------------------------------------------------------------------------------
/EvilBot/modules/helper_funcs/telethn/chatstatus.py:
--------------------------------------------------------------------------------
1 | from EvilBot.modules.helper_funcs.telethn import IMMUNE_USERS, telethn
2 | from EvilBot import DRAGONS
3 | from telethon.tl.types import ChannelParticipantsAdmins
4 |
5 |
6 | async def user_is_ban_protected(user_id: int, message):
7 | status = False
8 | if message.is_private or user_id in (IMMUNE_USERS):
9 | return True
10 |
11 | async for user in telethn.iter_participants(
12 | message.chat_id, filter=ChannelParticipantsAdmins
13 | ):
14 | if user_id == user.id:
15 | status = True
16 | break
17 | return status
18 |
19 |
20 | async def user_is_admin(user_id: int, message):
21 | status = False
22 | if message.is_private:
23 | return True
24 |
25 | async for user in telethn.iter_participants(
26 | message.chat_id, filter=ChannelParticipantsAdmins
27 | ):
28 | if user_id == user.id or user_id in DRAGONS:
29 | status = True
30 | break
31 | return status
32 |
33 |
34 | async def is_user_admin(user_id: int, chat_id):
35 | status = False
36 | async for user in telethn.iter_participants(
37 | chat_id, filter=ChannelParticipantsAdmins
38 | ):
39 | if user_id == user.id or user_id in DRAGONS:
40 | status = True
41 | break
42 | return status
43 |
44 |
45 | async def evil_is_admin(chat_id: int):
46 | status = False
47 | evil = await telethn.get_me()
48 | async for user in telethn.iter_participants(
49 | chat_id, filter=ChannelParticipantsAdmins
50 | ):
51 | if evil.id == user.id:
52 | status = True
53 | break
54 | return status
55 |
56 |
57 | async def is_user_in_chat(chat_id: int, user_id: int):
58 | status = False
59 | async for user in telethn.iter_participants(chat_id):
60 | if user_id == user.id:
61 | status = True
62 | break
63 | return status
64 |
65 |
66 | async def can_change_info(message):
67 | status = False
68 | if message.chat.admin_rights:
69 | status = message.chat.admin_rights.change_info
70 | return status
71 |
72 |
73 | async def can_ban_users(message):
74 | status = False
75 | if message.chat.admin_rights:
76 | status = message.chat.admin_rights.ban_users
77 | return status
78 |
79 |
80 | async def can_pin_messages(message):
81 | status = False
82 | if message.chat.admin_rights:
83 | status = message.chat.admin_rights.pin_messages
84 | return status
85 |
86 |
87 | async def can_invite_users(message):
88 | status = False
89 | if message.chat.admin_rights:
90 | status = message.chat.admin_rights.invite_users
91 | return status
92 |
93 |
94 | async def can_add_admins(message):
95 | status = False
96 | if message.chat.admin_rights:
97 | status = message.chat.admin_rights.add_admins
98 | return status
99 |
100 |
101 | async def can_delete_messages(message):
102 |
103 | if message.is_private:
104 | return True
105 | elif message.chat.admin_rights:
106 | status = message.chat.admin_rights.delete_messages
107 | return status
108 | else:
109 | return False
110 |
--------------------------------------------------------------------------------
/EvilBot/modules/logomaker.py:
--------------------------------------------------------------------------------
1 | from EvilBot.events import register
2 | from EvilBot import OWNER_ID
3 | from EvilBot import telethn as tbot
4 | import os
5 | from PIL import Image, ImageDraw, ImageFont
6 |
7 |
8 | @register(pattern="^/logo ?(.*)")
9 | async def lego(event):
10 | quew = event.pattern_match.group(1)
11 | if event.sender_id == OWNER_ID:
12 | pass
13 | else:
14 |
15 | if not quew:
16 | await event.reply('Provide Some Text To Draw!')
17 | return
18 | else:
19 | pass
20 | await event.reply('Creating your logo...wait!')
21 | try:
22 | text = event.pattern_match.group(1)
23 | img = Image.open('./EvilBot/resources/blackbg.jpg')
24 | draw = ImageDraw.Draw(img)
25 | image_widthz, image_heightz = img.size
26 | pointsize = 500
27 | fillcolor = "gold"
28 | shadowcolor = "blue"
29 | font = ImageFont.truetype("./EvilBot/resources/Chopsic.otf", 330)
30 | w, h = draw.textsize(text, font=font)
31 | h += int(h*0.21)
32 | image_width, image_height = img.size
33 | draw.text(((image_widthz-w)/2, (image_heightz-h)/2), text, font=font, fill=(255, 255, 255))
34 | x = (image_widthz-w)/2
35 | y= ((image_heightz-h)/2+6)
36 | draw.text((x, y), text, font=font, fill="black", stroke_width=25, stroke_fill="yellow")
37 | fname2 = "LogoByEvil.png"
38 | img.save(fname2, "png")
39 | await tbot.send_file(event.chat_id, fname2, caption="✌️✨")
40 | if os.path.exists(fname2):
41 | os.remove(fname2)
42 | except Exception as e:
43 | await event.reply(f'Error Report @KoraSupport, {e}')
44 |
45 |
46 |
47 |
48 | @register(pattern="^/wlogo ?(.*)")
49 | async def lego(event):
50 | quew = event.pattern_match.group(1)
51 | if event.sender_id == OWNER_ID:
52 | pass
53 | else:
54 |
55 | if not quew:
56 | await event.reply('Provide Some Text To Draw!')
57 | return
58 | else:
59 | pass
60 | await event.reply('Creating your logo...wait!')
61 | try:
62 | text = event.pattern_match.group(1)
63 | img = Image.open('./EvilBot/resources/blackbg.jpg')
64 | draw = ImageDraw.Draw(img)
65 | image_widthz, image_heightz = img.size
66 | pointsize = 500
67 | fillcolor = "white"
68 | shadowcolor = "blue"
69 | font = ImageFont.truetype("./EvilBot/resources/Maghrib.ttf", 1000)
70 | w, h = draw.textsize(text, font=font)
71 | h += int(h*0.21)
72 | image_width, image_height = img.size
73 | draw.text(((image_widthz-w)/2, (image_heightz-h)/2), text, font=font, fill=(255, 255, 255))
74 | x = (image_widthz-w)/2
75 | y= ((image_heightz-h)/2+6)
76 | draw.text((x, y), text, font=font, fill="white", stroke_width=0, stroke_fill="white")
77 | fname2 = "LogoByEvil.png"
78 | img.save(fname2, "png")
79 | await tbot.send_file(event.chat_id, fname2, caption="✌️✨")
80 | if os.path.exists(fname2):
81 | os.remove(fname2)
82 | except Exception as e:
83 | await event.reply(f'Error Report @KoraSupport, {e}')
84 |
85 | file_help = os.path.basename(__file__)
86 | file_help = file_help.replace(".py", "")
87 | file_helpo = file_help.replace("_", " ")
88 |
89 |
90 | __help__ = """
91 | ❍ /logo text : Create your logo with your name
92 |
93 | """
94 | __mod_name__ = "Logo"
95 |
--------------------------------------------------------------------------------
/EvilBot/modules/math.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | import pynewtonmath as newton
4 | from EvilBot import dispatcher
5 | from EvilBot.modules.disable import DisableAbleCommandHandler
6 | from telegram import Update
7 | from telegram.ext import CallbackContext, run_async
8 |
9 |
10 | @run_async
11 | def simplify(update: Update, context: CallbackContext):
12 | args = context.args
13 | message = update.effective_message
14 | message.reply_text(newton.simplify("{}".format(args[0])))
15 |
16 |
17 | @run_async
18 | def factor(update: Update, context: CallbackContext):
19 | args = context.args
20 | message = update.effective_message
21 | message.reply_text(newton.factor("{}".format(args[0])))
22 |
23 |
24 | @run_async
25 | def derive(update: Update, context: CallbackContext):
26 | args = context.args
27 | message = update.effective_message
28 | message.reply_text(newton.derive("{}".format(args[0])))
29 |
30 |
31 | @run_async
32 | def integrate(update: Update, context: CallbackContext):
33 | args = context.args
34 | message = update.effective_message
35 | message.reply_text(newton.integrate("{}".format(args[0])))
36 |
37 |
38 | @run_async
39 | def zeroes(update: Update, context: CallbackContext):
40 | args = context.args
41 | message = update.effective_message
42 | message.reply_text(newton.zeroes("{}".format(args[0])))
43 |
44 |
45 | @run_async
46 | def tangent(update: Update, context: CallbackContext):
47 | args = context.args
48 | message = update.effective_message
49 | message.reply_text(newton.tangent("{}".format(args[0])))
50 |
51 |
52 | @run_async
53 | def area(update: Update, context: CallbackContext):
54 | args = context.args
55 | message = update.effective_message
56 | message.reply_text(newton.area("{}".format(args[0])))
57 |
58 |
59 | @run_async
60 | def cos(update: Update, context: CallbackContext):
61 | args = context.args
62 | message = update.effective_message
63 | message.reply_text(math.cos(int(args[0])))
64 |
65 |
66 | @run_async
67 | def sin(update: Update, context: CallbackContext):
68 | args = context.args
69 | message = update.effective_message
70 | message.reply_text(math.sin(int(args[0])))
71 |
72 |
73 | @run_async
74 | def tan(update: Update, context: CallbackContext):
75 | args = context.args
76 | message = update.effective_message
77 | message.reply_text(math.tan(int(args[0])))
78 |
79 |
80 | @run_async
81 | def arccos(update: Update, context: CallbackContext):
82 | args = context.args
83 | message = update.effective_message
84 | message.reply_text(math.acos(int(args[0])))
85 |
86 |
87 | @run_async
88 | def arcsin(update: Update, context: CallbackContext):
89 | args = context.args
90 | message = update.effective_message
91 | message.reply_text(math.asin(int(args[0])))
92 |
93 |
94 | @run_async
95 | def arctan(update: Update, context: CallbackContext):
96 | args = context.args
97 | message = update.effective_message
98 | message.reply_text(math.atan(int(args[0])))
99 |
100 |
101 | @run_async
102 | def abs(update: Update, context: CallbackContext):
103 | args = context.args
104 | message = update.effective_message
105 | message.reply_text(math.fabs(int(args[0])))
106 |
107 |
108 | @run_async
109 | def log(update: Update, context: CallbackContext):
110 | args = context.args
111 | message = update.effective_message
112 | message.reply_text(math.log(int(args[0])))
113 |
114 |
115 |
116 | __mod_name__ = "Math"
117 |
118 | SIMPLIFY_HANDLER = DisableAbleCommandHandler("math", simplify)
119 | FACTOR_HANDLER = DisableAbleCommandHandler("factor", factor)
120 | DERIVE_HANDLER = DisableAbleCommandHandler("derive", derive)
121 | INTEGRATE_HANDLER = DisableAbleCommandHandler("integrate", integrate)
122 | ZEROES_HANDLER = DisableAbleCommandHandler("zeroes", zeroes)
123 | TANGENT_HANDLER = DisableAbleCommandHandler("tangent", tangent)
124 | AREA_HANDLER = DisableAbleCommandHandler("area", area)
125 | COS_HANDLER = DisableAbleCommandHandler("cos", cos)
126 | SIN_HANDLER = DisableAbleCommandHandler("sin", sin)
127 | TAN_HANDLER = DisableAbleCommandHandler("tan", tan)
128 | ARCCOS_HANDLER = DisableAbleCommandHandler("arccos", arccos)
129 | ARCSIN_HANDLER = DisableAbleCommandHandler("arcsin", arcsin)
130 | ARCTAN_HANDLER = DisableAbleCommandHandler("arctan", arctan)
131 | ABS_HANDLER = DisableAbleCommandHandler("abs", abs)
132 | LOG_HANDLER = DisableAbleCommandHandler("log", log)
133 |
134 | dispatcher.add_handler(SIMPLIFY_HANDLER)
135 | dispatcher.add_handler(FACTOR_HANDLER)
136 | dispatcher.add_handler(DERIVE_HANDLER)
137 | dispatcher.add_handler(INTEGRATE_HANDLER)
138 | dispatcher.add_handler(ZEROES_HANDLER)
139 | dispatcher.add_handler(TANGENT_HANDLER)
140 | dispatcher.add_handler(AREA_HANDLER)
141 | dispatcher.add_handler(COS_HANDLER)
142 | dispatcher.add_handler(SIN_HANDLER)
143 | dispatcher.add_handler(TAN_HANDLER)
144 | dispatcher.add_handler(ARCCOS_HANDLER)
145 | dispatcher.add_handler(ARCSIN_HANDLER)
146 | dispatcher.add_handler(ARCTAN_HANDLER)
147 | dispatcher.add_handler(ABS_HANDLER)
148 | dispatcher.add_handler(LOG_HANDLER)
149 |
--------------------------------------------------------------------------------
/EvilBot/modules/nightmodebtn.py:
--------------------------------------------------------------------------------
1 | __help__ = f"""
2 | ❍ /nightmode on/off
3 |
4 | Set NightMode - /setnightmode timezone : 12:00:00 PM : 07:00:00 AM
5 | **Note:** Now you can choose your counrty time zone and opening and closing time also.
6 | """
7 |
8 | __mod_name__ = "NightMode"
9 |
10 |
--------------------------------------------------------------------------------
/EvilBot/modules/paste.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from EvilBot import dispatcher
3 | from EvilBot.modules.disable import DisableAbleCommandHandler
4 | from telegram import ParseMode, Update
5 | from telegram.ext import CallbackContext, run_async
6 |
7 |
8 | @run_async
9 | def paste(update: Update, context: CallbackContext):
10 | args = context.args
11 | message = update.effective_message
12 |
13 | if message.reply_to_message:
14 | data = message.reply_to_message.text
15 |
16 | elif len(args) >= 1:
17 | data = message.text.split(None, 1)[1]
18 |
19 | else:
20 | message.reply_text("What am I supposed to do with this?")
21 | return
22 |
23 | key = (
24 | requests.post("https://nekobin.com/api/documents", json={"content": data})
25 | .json()
26 | .get("result")
27 | .get("key")
28 | )
29 |
30 | url = f"https://nekobin.com/{key}"
31 |
32 | reply_text = f"Nekofied to *Nekobin* : {url}"
33 |
34 | message.reply_text(
35 | reply_text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True
36 | )
37 |
38 |
39 | PASTE_HANDLER = DisableAbleCommandHandler("paste", paste)
40 | dispatcher.add_handler(PASTE_HANDLER)
41 |
42 | __command_list__ = ["paste"]
43 | __handlers__ = [PASTE_HANDLER]
44 |
--------------------------------------------------------------------------------
/EvilBot/modules/ping.py:
--------------------------------------------------------------------------------
1 | import time
2 | from typing import List
3 |
4 | import requests
5 | from telegram import ParseMode, Update
6 | from telegram.ext import CallbackContext, run_async
7 |
8 | from EvilBot import StartTime, dispatcher
9 | from EvilBot.modules.helper_funcs.chat_status import sudo_plus
10 | from EvilBot.modules.disable import DisableAbleCommandHandler
11 |
12 | sites_list = {
13 | "Telegram": "https://api.telegram.org",
14 | "Kaizoku": "https://animekaizoku.com",
15 | "Kayo": "https://animekayo.com",
16 | "Jikan": "https://api.jikan.moe/v3",
17 | }
18 |
19 |
20 | def get_readable_time(seconds: int) -> str:
21 | count = 0
22 | ping_time = ""
23 | time_list = []
24 | time_suffix_list = ["s", "m", "h", "days"]
25 |
26 | while count < 4:
27 | count += 1
28 | if count < 3:
29 | remainder, result = divmod(seconds, 60)
30 | else:
31 | remainder, result = divmod(seconds, 24)
32 | if seconds == 0 and remainder == 0:
33 | break
34 | time_list.append(int(result))
35 | seconds = int(remainder)
36 |
37 | for x in range(len(time_list)):
38 | time_list[x] = str(time_list[x]) + time_suffix_list[x]
39 | if len(time_list) == 4:
40 | ping_time += time_list.pop() + ", "
41 |
42 | time_list.reverse()
43 | ping_time += ":".join(time_list)
44 |
45 | return ping_time
46 |
47 |
48 | def ping_func(to_ping: List[str]) -> List[str]:
49 | ping_result = []
50 |
51 | for each_ping in to_ping:
52 |
53 | start_time = time.time()
54 | site_to_ping = sites_list[each_ping]
55 | r = requests.get(site_to_ping)
56 | end_time = time.time()
57 | ping_time = str(round((end_time - start_time), 2)) + "s"
58 |
59 | pinged_site = f"{each_ping}"
60 |
61 | if each_ping == "Kaizoku" or each_ping == "Kayo":
62 | pinged_site = f'{each_ping}'
63 | ping_time = f"{ping_time} (Status: {r.status_code})
"
64 |
65 | ping_text = f"{pinged_site}: {ping_time}
"
66 | ping_result.append(ping_text)
67 |
68 | return ping_result
69 |
70 |
71 | @run_async
72 | @sudo_plus
73 | def ping(update: Update, context: CallbackContext):
74 | msg = update.effective_message
75 |
76 | start_time = time.time()
77 | message = msg.reply_text("Pinging...")
78 | end_time = time.time()
79 | telegram_ping = str(round((end_time - start_time) * 1000, 3)) + " ms"
80 | uptime = get_readable_time((time.time() - StartTime))
81 |
82 | message.edit_text(
83 | "PONG!!\n"
84 | "Time Taken: {}
\n"
85 | "Service uptime: {}
".format(telegram_ping, uptime),
86 | parse_mode=ParseMode.HTML,
87 | )
88 |
89 |
90 | @run_async
91 | @sudo_plus
92 | def pingall(update: Update, context: CallbackContext):
93 | to_ping = ["Kaizoku", "Kayo", "Telegram", "Jikan"]
94 | pinged_list = ping_func(to_ping)
95 | pinged_list.insert(2, "")
96 | uptime = get_readable_time((time.time() - StartTime))
97 |
98 | reply_msg = "⏱Ping results are:\n"
99 | reply_msg += "\n".join(pinged_list)
100 | reply_msg += "\nService uptime: {}
".format(uptime)
101 |
102 | update.effective_message.reply_text(
103 | reply_msg, parse_mode=ParseMode.HTML, disable_web_page_preview=True
104 | )
105 |
106 |
107 | PING_HANDLER = DisableAbleCommandHandler("ping", ping)
108 | PINGALL_HANDLER = DisableAbleCommandHandler("pingall", pingall)
109 |
110 | dispatcher.add_handler(PING_HANDLER)
111 | dispatcher.add_handler(PINGALL_HANDLER)
112 |
113 | __command_list__ = ["ping", "pingall"]
114 | __handlers__ = [PING_HANDLER, PINGALL_HANDLER]
115 |
--------------------------------------------------------------------------------
/EvilBot/modules/purge.py:
--------------------------------------------------------------------------------
1 | import time
2 | from telethon import events
3 |
4 | from EvilBot import telethn
5 | from EvilBot.modules.helper_funcs.telethn.chatstatus import (
6 | can_delete_messages,
7 | user_is_admin,
8 | )
9 |
10 |
11 | async def purge_messages(event):
12 | start = time.perf_counter()
13 | if event.from_id is None:
14 | return
15 |
16 | if not await user_is_admin(
17 | user_id=event.sender_id, message=event
18 | ) and event.from_id not in [1087968824]:
19 | await event.reply("Only Admins are allowed to use this command")
20 | return
21 |
22 | if not await can_delete_messages(message=event):
23 | await event.reply("Can't seem to purge the message")
24 | return
25 |
26 | reply_msg = await event.get_reply_message()
27 | if not reply_msg:
28 | await event.reply("Reply to a message to select where to start purging from.")
29 | return
30 | messages = []
31 | message_id = reply_msg.id
32 | delete_to = event.message.id
33 |
34 | messages.append(event.reply_to_msg_id)
35 | for msg_id in range(message_id, delete_to + 1):
36 | messages.append(msg_id)
37 | if len(messages) == 100:
38 | await event.client.delete_messages(event.chat_id, messages)
39 | messages = []
40 |
41 | try:
42 | await event.client.delete_messages(event.chat_id, messages)
43 | except:
44 | pass
45 | time_ = time.perf_counter() - start
46 | text = f"Purged Successfully in {time_:0.2f} Second(s)"
47 | await event.respond(text, parse_mode="markdown")
48 |
49 |
50 | async def delete_messages(event):
51 | if event.from_id is None:
52 | return
53 |
54 | if not await user_is_admin(
55 | user_id=event.sender_id, message=event
56 | ) and event.from_id not in [1087968824]:
57 | await event.reply("Only Admins are allowed to use this command")
58 | return
59 |
60 | if not await can_delete_messages(message=event):
61 | await event.reply("Can't seem to delete this?")
62 | return
63 |
64 | message = await event.get_reply_message()
65 | if not message:
66 | await event.reply("Whadya want to delete?")
67 | return
68 | chat = await event.get_input_chat()
69 | del_message = [message, event.message]
70 | await event.client.delete_messages(chat, del_message)
71 |
72 |
73 |
74 | PURGE_HANDLER = purge_messages, events.NewMessage(pattern="^[!/]purge$")
75 | DEL_HANDLER = delete_messages, events.NewMessage(pattern="^[!/]del$")
76 |
77 | telethn.add_event_handler(*PURGE_HANDLER)
78 | telethn.add_event_handler(*DEL_HANDLER)
79 |
80 | __mod_name__ = "DETELE"
81 | __command_list__ = ["del", "purge"]
82 | __handlers__ = [PURGE_HANDLER, DEL_HANDLER]
83 |
--------------------------------------------------------------------------------
/EvilBot/modules/reactions.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | from telegram import Bot, Update
4 | from telegram.ext import run_async
5 |
6 | from EvilBot import dispatcher
7 | from EvilBot.modules.disable import DisableAbleCommandHandler
8 |
9 | reactions = [
10 | "( ͡° ͜ʖ ͡°)",
11 | "( . •́ _ʖ •̀ .)",
12 | "( ಠ ͜ʖ ಠ)",
13 | "( ͡ ͜ʖ ͡ )",
14 | "(ʘ ͜ʖ ʘ)",
15 | "ヾ(´〇`)ノ♪♪♪",
16 | "ヽ(o´∀`)ノ♪♬",
17 | "♪♬((d⌒ω⌒b))♬♪",
18 | "└(^^)┐",
19 | "( ̄▽ ̄)/♫•*¨*•.¸¸♪",
20 | "ヾ(⌐■_■)ノ♪",
21 | "乁( • ω •乁)",
22 | "♬♫♪◖(● o ●)◗♪♫♬",
23 | "(っ˘ڡ˘ς)",
24 | "( ˘▽˘)っ♨",
25 | "( ・ω・)⊃-[二二]",
26 | "(*´ー`)旦 旦( ̄ω ̄*)",
27 | "(  ̄▽ ̄)[] [](≧▽≦ )",
28 | "(* ̄▽ ̄)旦 且(´∀`*)",
29 | "(ノ ˘_˘)ノ ζ|||ζ ζ|||ζ ζ|||ζ",
30 | "(ノ°∀°)ノ⌒・*:.。. .。.:*・゜゚・*☆",
31 | "(⊃。•́‿•̀。)⊃━✿✿✿✿✿✿",
32 | "(∩` ロ ´)⊃━炎炎炎炎炎",
33 | "( ・∀・)・・・--------☆",
34 | "( -ω-)/占~~~~~",
35 | "○∞∞∞∞ヽ(^ー^ )",
36 | "(*^^)/~~~~~~~~~~◎",
37 | "(((  ̄□)_/",
38 | "(メ ̄▽ ̄)︻┳═一",
39 | "ヽ( ・∀・)ノ_θ彡☆Σ(ノ `Д´)ノ",
40 | "(*`0´)θ☆(メ°皿°)ノ",
41 | "(; -_-)――――――C<―_-)",
42 | "ヽ(>_<ヽ) ―⊂|=0ヘ(^‿^ )",
43 | "(҂` ロ ´)︻デ═一 \(º □ º l|l)/",
44 | "/( .□.)\ ︵╰(°益°)╯︵ /(.□. /)",
45 | "(`⌒*)O-(`⌒´Q)",
46 | "(っ•﹏•)っ ✴==≡눈٩(`皿´҂)ง",
47 | "ヾ(・ω・)メ(・ω・)ノ",
48 | "(*^ω^)八(⌒▽⌒)八(-‿‿- )ヽ",
49 | "ヽ( ⌒ω⌒)人(=^‥^= )ノ",
50 | "。*:☆(・ω・人・ω・)。:゜☆。",
51 | "(°(°ω(°ω°(☆ω☆)°ω°)ω°)°)",
52 | "(っ˘▽˘)(˘▽˘)˘▽˘ς)",
53 | "(*^ω^)人(^ω^*)",
54 | "\(▽ ̄ \ ( ̄▽ ̄) /  ̄▽)/",
55 | "( ̄Θ ̄)",
56 | "\( ˋ Θ ´ )/",
57 | "( ´(00)ˋ )",
58 | "\( ̄(oo) ̄)/",
59 | "/(≧ x ≦)\",
60 | "/(=・ x ・=)\",
61 | "(=^・ω・^=)",
62 | "(= ; ェ ; =)",
63 | "(=⌒‿‿⌒=)",
64 | "(^• ω •^)",
65 | "ଲ(ⓛ ω ⓛ)ଲ",
66 | "ଲ(ⓛ ω ⓛ)ଲ",
67 | "(^◔ᴥ◔^)",
68 | "[(--)]..zzZ",
69 | "( ̄o ̄) zzZZzzZZ",
70 | "(_ _*) Z z z",
71 | "☆ミ(o*・ω・)ノ",
72 | "ε=ε=ε=ε=┌(; ̄▽ ̄)┘",
73 | "ε===(っ≧ω≦)っ",
74 | "__φ(..)",
75 | "ヾ( `ー´)シφ__",
76 | "( ^▽^)ψ__",
77 | "|・ω・)",
78 | "|д・)",
79 | "┬┴┬┴┤・ω・)ノ",
80 | "|・д・)ノ",
81 | "(* ̄ii ̄)",
82 | "(^〃^)",
83 | "m(_ _)m",
84 | "人(_ _*)",
85 | "(シ. .)シ",
86 | "(^_~)",
87 | "(>ω^)",
88 | "(^_<)〜☆",
89 | "(^_<)",
90 | "(づ ̄ ³ ̄)づ",
91 | "(⊃。•́‿•̀。)⊃",
92 | "⊂(´• ω •`⊂)",
93 | "(*・ω・)ノ",
94 | "(^-^*)/",
95 | "ヾ(*'▽'*)",
96 | "(^0^)ノ",
97 | "(*°ー°)ノ",
98 | "( ̄ω ̄)/",
99 | "(≧▽≦)/",
100 | "w(°o°)w",
101 | "(⊙_⊙)",
102 | "(°ロ°) !",
103 | "∑(O_O;)",
104 | "(¬_¬)",
105 | "(¬_¬ )",
106 | "(↼_↼)",
107 | "( ̄ω ̄;)",
108 | "┐('~`;)┌",
109 | "(・_・;)",
110 | "(@_@)",
111 | "(•ิ_•ิ)?",
112 | "ヽ(ー_ー )ノ",
113 | "┐( ̄ヘ ̄)┌",
114 | "┐( ̄~ ̄)┌",
115 | "┐( ´ д ` )┌",
116 | "╮(︶▽︶)╭",
117 | "ᕕ( ᐛ )ᕗ",
118 | "(ノωヽ)",
119 | "(″ロ゛)",
120 | "(/ω\)",
121 | "(((><)))",
122 | "~(>_<~)",
123 | "(×_×)",
124 | "(×﹏×)",
125 | "(ノ_<。)",
126 | "(μ_μ)",
127 | "o(TヘTo)",
128 | "( ゚,_ゝ`)",
129 | "( ╥ω╥ )",
130 | "(/ˍ・、)",
131 | "(つω`。)",
132 | "(T_T)",
133 | "o(〒﹏〒)o",
134 | "(#`Д´)",
135 | "(・`ω´・)",
136 | "( `ε´ )",
137 | "(メ` ロ ´)",
138 | "Σ(▼□▼メ)",
139 | "(҂ `з´ )",
140 | "٩(╬ʘ益ʘ╬)۶",
141 | "↑_(ΦwΦ)Ψ",
142 | "(ノಥ益ಥ)ノ",
143 | "(#><)",
144 | "(; ̄Д ̄)",
145 | "(¬_¬;)",
146 | "(^^#)",
147 | "( ̄︿ ̄)",
148 | "ヾ(  ̄O ̄)ツ",
149 | "(ᗒᗣᗕ)՞",
150 | "(ノ_<。)ヾ(´ ▽ ` )",
151 | "ヽ( ̄ω ̄(。。 )ゝ",
152 | "(ノ_;)ヾ(´ ∀ ` )",
153 | "(´-ω-`( _ _ )",
154 | "(⌒_⌒;)",
155 | "(*/_\)",
156 | "( ◡‿◡ *)",
157 | "(//ω//)",
158 | "( ̄▽ ̄*)ゞ",
159 | "(„ಡωಡ„)",
160 | "(ノ´ з `)ノ",
161 | "(♡-_-♡)",
162 | "(─‿‿─)♡",
163 | "(´ ω `♡)",
164 | "(ღ˘⌣˘ღ)",
165 | "(´• ω •`) ♡",
166 | "╰(*´︶`*)╯♡",
167 | "(≧◡≦) ♡",
168 | "♡ (˘▽˘>ԅ( ˘⌣˘)",
169 | "σ(≧ε≦σ) ♡",
170 | "(˘∀˘)/(μ‿μ) ❤",
171 | "Σ>―(〃°ω°〃)♡→",
172 | "(* ^ ω ^)",
173 | "(o^▽^o)",
174 | "ヽ(・∀・)ノ",
175 | "(o・ω・o)",
176 | "(^人^)",
177 | "( ´ ω ` )",
178 | "(´• ω •`)",
179 | "╰(▔∀▔)╯",
180 | "(✯◡✯)",
181 | "(⌒‿⌒)",
182 | "(*°▽°*)",
183 | "(´。• ᵕ •。`)",
184 | "ヽ(>∀<☆)ノ",
185 | "\( ̄▽ ̄)/",
186 | "(o˘◡˘o)",
187 | "(╯✧▽✧)╯",
188 | "( ‾́ ◡ ‾́ )",
189 | "(๑˘︶˘๑)",
190 | "(´・ᴗ・ ` )",
191 | "( ͡° ʖ̯ ͡°)",
192 | "( ఠ ͟ʖ ఠ)",
193 | "( ಥ ʖ̯ ಥ)",
194 | "(≖ ͜ʖ≖)",
195 | "ヘ( ̄ω ̄ヘ)",
196 | "(ノ≧∀≦)ノ",
197 | "└( ̄- ̄└))",
198 | "┌(^^)┘",
199 | "(^_^♪)",
200 | "(〜 ̄△ ̄)〜",
201 | "(「• ω •)「",
202 | "( ˘ ɜ˘) ♬♪♫",
203 | "( o˘◡˘o) ┌iii┐",
204 | "♨o(>_<)o♨",
205 | "( ・・)つ―{}@{}@{}-",
206 | "(*´з`)口゚。゚口(・∀・ )",
207 | "( *^^)o∀*∀o(^^* )",
208 | "-●●●-c(・・ )",
209 | "(ノ≧∀≦)ノ ‥…━━━★",
210 | "╰( ͡° ͜ʖ ͡° )つ──☆*:・゚",
211 | "(∩ᄑ_ᄑ)⊃━☆゚*・。*・:≡( ε:)"
212 | ]
213 |
214 |
215 | @run_async
216 | def react(bot: Bot, update: Update):
217 | message = update.effective_message
218 | react = random.choice(reactions)
219 | if message.reply_to_message:
220 | message.reply_to_message.reply_text(react)
221 | else:
222 | message.reply_text(react)
223 |
224 |
225 | __help__ = """
226 | - /react: Reacts with a random reaction
227 | """
228 |
229 | REACT_HANDLER = DisableAbleCommandHandler("react", react)
230 |
231 | dispatcher.add_handler(REACT_HANDLER)
232 |
233 | __mod_name__ = "REACT"
234 | __command_list__ = ["react"]
235 | __handlers__ = [REACT_HANDLER]
236 |
--------------------------------------------------------------------------------
/EvilBot/modules/rules.py:
--------------------------------------------------------------------------------
1 | from typing import Optional
2 |
3 | import EvilBot.modules.sql.rules_sql as sql
4 | from EvilBot import dispatcher
5 | from EvilBot.modules.helper_funcs.chat_status import user_admin
6 | from EvilBot.modules.helper_funcs.string_handling import markdown_parser
7 | from telegram import (
8 | InlineKeyboardButton,
9 | InlineKeyboardMarkup,
10 | Message,
11 | ParseMode,
12 | Update,
13 | User,
14 | )
15 | from telegram.error import BadRequest
16 | from telegram.ext import CallbackContext, CommandHandler, Filters, run_async
17 | from telegram.utils.helpers import escape_markdown
18 |
19 |
20 | @run_async
21 | def get_rules(update: Update, context: CallbackContext):
22 | chat_id = update.effective_chat.id
23 | send_rules(update, chat_id)
24 |
25 |
26 | # Do not async - not from a handler
27 | def send_rules(update, chat_id, from_pm=False):
28 | bot = dispatcher.bot
29 | user = update.effective_user # type: Optional[User]
30 | try:
31 | chat = bot.get_chat(chat_id)
32 | except BadRequest as excp:
33 | if excp.message == "Chat not found" and from_pm:
34 | bot.send_message(
35 | user.id,
36 | "The rules shortcut for this chat hasn't been set properly! Ask admins to "
37 | "fix this.\nMaybe they forgot the hyphen in ID",
38 | )
39 | return
40 | else:
41 | raise
42 |
43 | rules = sql.get_rules(chat_id)
44 | text = f"The rules for *{escape_markdown(chat.title)}* are:\n\n{rules}"
45 |
46 | if from_pm and rules:
47 | bot.send_message(
48 | user.id, text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True
49 | )
50 | elif from_pm:
51 | bot.send_message(
52 | user.id,
53 | "The group admins haven't set any rules for this chat yet. "
54 | "This probably doesn't mean it's lawless though...!",
55 | )
56 | elif rules:
57 | update.effective_message.reply_text(
58 | "Please click the button below to see the rules.",
59 | reply_markup=InlineKeyboardMarkup(
60 | [
61 | [
62 | InlineKeyboardButton(
63 | text="Rules", url=f"t.me/{bot.username}?start={chat_id}"
64 | )
65 | ]
66 | ]
67 | ),
68 | )
69 | else:
70 | update.effective_message.reply_text(
71 | "The group admins haven't set any rules for this chat yet. "
72 | "This probably doesn't mean it's lawless though...!"
73 | )
74 |
75 |
76 | @run_async
77 | @user_admin
78 | def set_rules(update: Update, context: CallbackContext):
79 | chat_id = update.effective_chat.id
80 | msg = update.effective_message # type: Optional[Message]
81 | raw_text = msg.text
82 | args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args
83 | if len(args) == 2:
84 | txt = args[1]
85 | offset = len(txt) - len(raw_text) # set correct offset relative to command
86 | markdown_rules = markdown_parser(
87 | txt, entities=msg.parse_entities(), offset=offset
88 | )
89 |
90 | sql.set_rules(chat_id, markdown_rules)
91 | update.effective_message.reply_text("Successfully set rules for this group.")
92 |
93 |
94 | @run_async
95 | @user_admin
96 | def clear_rules(update: Update, context: CallbackContext):
97 | chat_id = update.effective_chat.id
98 | sql.set_rules(chat_id, "")
99 | update.effective_message.reply_text("Successfully cleared rules!")
100 |
101 |
102 | def __stats__():
103 | return f"• {sql.num_chats()} chats have rules set."
104 |
105 |
106 | def __import_data__(chat_id, data):
107 | # set chat rules
108 | rules = data.get("info", {}).get("rules", "")
109 | sql.set_rules(chat_id, rules)
110 |
111 |
112 | def __migrate__(old_chat_id, new_chat_id):
113 | sql.migrate_chat(old_chat_id, new_chat_id)
114 |
115 |
116 | def __chat_settings__(chat_id, user_id):
117 | return f"This chat has had it's rules set: `{bool(sql.get_rules(chat_id))}`"
118 |
119 |
120 | __help__ = """
121 | ❍ /rules*:* get the rules for this chat.
122 |
123 | *Admins only:*
124 | ❍ /setrules {}
".format(e), parse_mode=ParseMode.HTML
33 | )
34 | if res:
35 | result = f"{search}\n\n"
36 | result += f"{res}\n"
37 | result += f"""Read more..."""
38 | if len(result) > 4000:
39 | with open("result.txt", "w") as f:
40 | f.write(f"{result}\n\nUwU OwO OmO UmU")
41 | with open("result.txt", "rb") as f:
42 | context.bot.send_document(
43 | document=f,
44 | filename=f.name,
45 | reply_to_message_id=update.message.message_id,
46 | chat_id=update.effective_chat.id,
47 | parse_mode=ParseMode.HTML,
48 | )
49 | else:
50 | update.message.reply_text(
51 | result, parse_mode=ParseMode.HTML, disable_web_page_preview=True
52 | )
53 |
54 |
55 | WIKI_HANDLER = DisableAbleCommandHandler("wiki", wiki)
56 | dispatcher.add_handler(WIKI_HANDLER)
57 |
--------------------------------------------------------------------------------
/EvilBot/modules/zombies.py:
--------------------------------------------------------------------------------
1 | from asyncio import sleep
2 |
3 | from telethon import events
4 | from telethon.errors import ChatAdminRequiredError, UserAdminInvalidError
5 | from telethon.tl.functions.channels import EditBannedRequest
6 | from telethon.tl.types import ChatBannedRights, ChannelParticipantsAdmins
7 | from EvilBot import telethn
8 | from EvilBot.events import register
9 |
10 | from EvilBot import telethn, OWNER_ID, DEV_USERS, DRAGONS, DEMONS
11 |
12 | # =================== CONSTANT ===================
13 |
14 | BANNED_RIGHTS = ChatBannedRights(
15 | until_date=None,
16 | view_messages=True,
17 | send_messages=True,
18 | send_media=True,
19 | send_stickers=True,
20 | send_gifs=True,
21 | send_games=True,
22 | send_inline=True,
23 | embed_links=True,
24 | )
25 |
26 |
27 | UNBAN_RIGHTS = ChatBannedRights(
28 | until_date=None,
29 | send_messages=None,
30 | send_media=None,
31 | send_stickers=None,
32 | send_gifs=None,
33 | send_games=None,
34 | send_inline=None,
35 | embed_links=None,
36 | )
37 |
38 | OFFICERS = [OWNER_ID] + DEV_USERS + DRAGONS + DEMONS
39 |
40 | # Check if user has admin rights
41 | async def is_administrator(user_id: int, message):
42 | admin = False
43 | async for user in telethn.iter_participants(
44 | message.chat_id, filter=ChannelParticipantsAdmins
45 | ):
46 | if user_id == user.id or user_id in OFFICERS:
47 | admin = True
48 | break
49 | return admin
50 |
51 |
52 |
53 | @telethn.on(events.NewMessage(pattern="^[!/]zombies ?(.*)"))
54 | async def zombies(event):
55 | """ For .zombies command, list all the zombies in a chat. """
56 |
57 | con = event.pattern_match.group(1).lower()
58 | del_u = 0
59 | del_status = "No Deleted Accounts Found, Group Is Clean."
60 |
61 | if con != "clean":
62 | find_zombies = await event.respond("Searching For Zombies...")
63 | async for user in event.client.iter_participants(event.chat_id):
64 |
65 | if user.deleted:
66 | del_u += 1
67 | await sleep(1)
68 | if del_u > 0:
69 | del_status = f"Found **{del_u}** Zombies In This Group.\
70 | \nClean Them By Using :\n👉 `/zombies clean`"
71 | await find_zombies.edit(del_status)
72 | return
73 |
74 | # Here laying the sanity check
75 | chat = await event.get_chat()
76 | admin = chat.admin_rights
77 | creator = chat.creator
78 |
79 | # Well
80 | if not await is_administrator(user_id=event.from_id, message=event):
81 | await event.respond("You're Not An Admin!")
82 | return
83 |
84 | if not admin and not creator:
85 | await event.respond("I Am Not An Admin Here!")
86 | return
87 |
88 | cleaning_zombies = await event.respond("Cleaning Zombies...")
89 | del_u = 0
90 | del_a = 0
91 |
92 | async for user in event.client.iter_participants(event.chat_id):
93 | if user.deleted:
94 | try:
95 | await event.client(
96 | EditBannedRequest(event.chat_id, user.id, BANNED_RIGHTS)
97 | )
98 | except ChatAdminRequiredError:
99 | await cleaning_zombies.edit("I Don't Have Ban Rights In This Group.")
100 | return
101 | except UserAdminInvalidError:
102 | del_u -= 1
103 | del_a += 1
104 | await event.client(EditBannedRequest(event.chat_id, user.id, UNBAN_RIGHTS))
105 | del_u += 1
106 |
107 | if del_u > 0:
108 | del_status = f"Cleaned `{del_u}` Zombies"
109 |
110 | if del_a > 0:
111 | del_status = f"Cleaned `{del_u}` Zombies \
112 | \n`{del_a}` Zombie Admin Accounts Are Not Removed!"
113 |
114 | await cleaning_zombies.edit(del_status)
115 |
--------------------------------------------------------------------------------
/EvilBot/mongo.py:
--------------------------------------------------------------------------------
1 | #Kiitu
2 | import asyncio
3 | import sys
4 |
5 | from motor import motor_asyncio
6 | from EvilBot import MONGO_DB_URI
7 | from pymongo import MongoClient
8 | from pymongo.errors import ServerSelectionTimeoutError
9 | from EvilBot.conf import get_int_key, get_str_key
10 |
11 |
12 | MONGO_PORT = get_int_key("27017")
13 | MONGO_DB_URI = get_str_key("MONGO_DB_URI")
14 | MONGO_DB = "Evil"
15 |
16 |
17 | client = MongoClient()
18 | client = MongoClient(MONGO_DB_URI, MONGO_PORT)[MONGO_DB]
19 | motor = motor_asyncio.AsyncIOMotorClient(MONGO_DB_URI, MONGO_PORT)
20 | db = motor[MONGO_DB]
21 | db = client["evilbot"]
22 | try:
23 | asyncio.get_event_loop().run_until_complete(motor.server_info())
24 | except ServerSelectionTimeoutError:
25 | sys.exit(log.critical("Can't connect to mongodb! Exiting..."))
26 |
--------------------------------------------------------------------------------
/EvilBot/pyrogramee/dark.py:
--------------------------------------------------------------------------------
1 | def get_arg(message):
2 |
3 | msg = message.text
4 |
5 | msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
6 |
7 | split = msg[1:].replace("\n", " \n").split(" ")
8 |
9 | if " ".join(split[1:]).strip() == "":
10 |
11 | return ""
12 |
13 | return " ".join(split[1:])
14 |
15 |
--------------------------------------------------------------------------------
/EvilBot/pyrogramee/errors.py:
--------------------------------------------------------------------------------
1 | # © @Mr_Dark_Prince
2 | import sys
3 | import traceback
4 | from functools import wraps
5 | from EvilBot import pbot, SUPPORT_CHAT
6 |
7 | def split_limits(text):
8 | if len(text) < 2048:
9 | return [text]
10 |
11 | lines = text.splitlines(True)
12 | small_msg = ''
13 | result = []
14 | for line in lines:
15 | if len(small_msg) + len(line) < 2048:
16 | small_msg += line
17 | else:
18 | result.append(small_msg)
19 | small_msg = line
20 | else:
21 | result.append(small_msg)
22 |
23 | return result
24 |
25 | def capture_err(func):
26 | @wraps(func)
27 | async def capture(client, message, *args, **kwargs):
28 | try:
29 | return await func(client, message, *args, **kwargs)
30 | except Exception as err:
31 | exc_type, exc_obj, exc_tb = sys.exc_info()
32 | errors = traceback.format_exception(
33 | etype=exc_type, value=exc_obj, tb=exc_tb,
34 | )
35 | error_feedback = split_limits(
36 | '**ERROR** | `{}` | `{}`\n\n```{}```\n\n```{}```\n'.format(
37 | 0 if not message.from_user else message.from_user.id,
38 | 0 if not message.chat else message.chat.id,
39 | message.text or message.caption,
40 | ''.join(errors),
41 | ),
42 | )
43 | for x in error_feedback:
44 | await pbot.send_message(
45 | SUPPORT_CHAT,
46 | x
47 | )
48 | raise err
49 | return capture
50 |
--------------------------------------------------------------------------------
/EvilBot/pyrogramee/fetch.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 |
3 |
4 | async def fetch(url):
5 | async with aiohttp.ClientSession() as session:
6 | async with session.get(url) as resp:
7 | try:
8 | data = await resp.json()
9 | except Exception:
10 | data = await resp.text()
11 | return data
12 |
--------------------------------------------------------------------------------
/EvilBot/pyrogramee/json_prettify.py:
--------------------------------------------------------------------------------
1 | async def json_object_prettify(objecc):
2 | dicc = objecc.__dict__
3 | output = ""
4 | for key, value in dicc.items():
5 | if key == "pinned_message" or key == "photo" \
6 | or key == "_" or key == "_client":
7 | continue
8 | output += f"**{key}:** `{value}`\n"
9 | return output
10 |
11 |
12 | async def json_prettify(data):
13 | output = ""
14 | try:
15 | for key, value in data.items():
16 | output += f"**{key}:** `{value}`\n"
17 | except Exception:
18 | for datas in data:
19 | for key, value in datas.items():
20 | output += f"**{key}:** `{value}`\n"
21 | output += "------------------------\n"
22 | return output
23 |
--------------------------------------------------------------------------------
/EvilBot/resources/Chopsic.otf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xhrvan/EvilBot/23d3f6f3c3245b0509fd18f39849cc72c1d78431/EvilBot/resources/Chopsic.otf
--------------------------------------------------------------------------------
/EvilBot/resources/Evil.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xhrvan/EvilBot/23d3f6f3c3245b0509fd18f39849cc72c1d78431/EvilBot/resources/Evil.jpg
--------------------------------------------------------------------------------
/EvilBot/resources/Maghrib.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xhrvan/EvilBot/23d3f6f3c3245b0509fd18f39849cc72c1d78431/EvilBot/resources/Maghrib.ttf
--------------------------------------------------------------------------------
/EvilBot/resources/blackbg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xhrvan/EvilBot/23d3f6f3c3245b0509fd18f39849cc72c1d78431/EvilBot/resources/blackbg.jpg
--------------------------------------------------------------------------------
/EvilBot/resources/images.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xhrvan/EvilBot/23d3f6f3c3245b0509fd18f39849cc72c1d78431/EvilBot/resources/images.jpeg
--------------------------------------------------------------------------------
/EvilBot/sample_config.py:
--------------------------------------------------------------------------------
1 | # Create a new config.py or rename this to config.py file in same dir and import, then extend this class.
2 | import json
3 | import os
4 |
5 |
6 | def get_user_list(config, key):
7 | with open("{}/EvilBot/{}".format(os.getcwd(), config), "r") as json_file:
8 | return json.load(json_file)[key]
9 |
10 |
11 | # Create a new config.py or rename this to config.py file in same dir and import, then extend this class.
12 | class Config(object):
13 | LOGGER = True
14 | # REQUIRED
15 | # Login to https://my.telegram.org and fill in these slots with the details given by it
16 |
17 | API_ID = 123456 # integer value, dont use ""
18 | API_HASH = "awoo"
19 | TOKEN = "BOT_TOKEN" # This var used to be API_KEY but it is now TOKEN, adjust accordingly.
20 | OWNER_ID = 1742353529 # If you dont know, run the bot and do /id in your private chat with it, also an integer
21 | OWNER_USERNAME = "shrvan42"
22 | SUPPORT_CHAT = "EVIL_SUPPORT_CHAT" # Your own group for support, do not add the @
23 | JOIN_LOGGER = (
24 | -1001236063876
25 | ) # Prints any new group the bot is added to, prints just the name and ID.
26 | EVENT_LOGS = (
27 | -1001188058807
28 | ) # Prints information like gbans, sudo promotes, AI enabled disable states that may help in debugging and shit
29 |
30 | # RECOMMENDED
31 | SQLALCHEMY_DATABASE_URI = "something://somewhat:user@hosturl:port/databasename" # needed for any database modules
32 | LOAD = []
33 | NO_LOAD = ["rss", "cleaner", "connection", "math"]
34 | WEBHOOK = False
35 | INFOPIC = True
36 | URL = None
37 | SPAMWATCH_API = "" # go to support.spamwat.ch to get key
38 | SPAMWATCH_SUPPORT_CHAT = "@SpamWatchSupport"
39 |
40 | # OPTIONAL
41 | ##List of id's - (not usernames) for users which have sudo access to the bot.
42 | DRAGONS = get_user_list("elevated_users.json", "sudos")
43 | ##List of id's - (not usernames) for developers who will have the same perms as the owner
44 | DEV_USERS = get_user_list("elevated_users.json", "devs")
45 | ##List of id's (not usernames) for users which are allowed to gban, but can also be banned.
46 | DEMONS = get_user_list("elevated_users.json", "supports")
47 | # List of id's (not usernames) for users which WONT be banned/kicked by the bot.
48 | TIGERS = get_user_list("elevated_users.json", "tigers")
49 | WOLVES = get_user_list("elevated_users.json", "whitelists")
50 | DONATION_LINK = None # EG, paypal
51 | CERT_PATH = None
52 | PORT = 5000
53 | DEL_CMDS = True # Delete commands that users dont have access to, like delete /ban if a non admin uses it.
54 | STRICT_GBAN = True
55 | WORKERS = (
56 | 8 # Number of subthreads to use. Set as number of threads your processor uses
57 | )
58 | BAN_STICKER = "" # banhammer marie sticker id, the bot will send this sticker before banning or kicking a user in chat.
59 | ALLOW_EXCL = True # Allow ! commands as well as / (Leave this to true so that blacklist can work)
60 | CASH_API_KEY = (
61 | "awoo" # Get your API key from https://www.alphavantage.co/support/#api-key
62 | )
63 | TIME_API_KEY = "awoo" # Get your API key from https://timezonedb.com/api
64 | WALL_API = (
65 | "awoo" # For wallpapers, get one from https://wall.alphacoders.com/api.php
66 | )
67 | AI_API_KEY = "awoo" # For chatbot, get one from https://coffeehouse.intellivoid.net/dashboard
68 | BL_CHATS = [] # List of groups that you want blacklisted.
69 | SPAMMERS = None
70 |
71 | class Production(Config):
72 | LOGGER = True
73 |
74 |
75 | class Development(Config):
76 | LOGGER = True
77 |
--------------------------------------------------------------------------------
/EvilBot/utils/X:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/EvilBot/utils/dbfunc.py:
--------------------------------------------------------------------------------
1 | from EvilBot.mongo import db
2 | from typing import Dict, List, Union
3 |
4 |
5 | coupledb = db.couple
6 | karmadb = db.karma
7 |
8 | # Couple Chooser
9 |
10 | async def _get_lovers(chat_id: int):
11 | lovers = coupledb.find_one({"chat_id": chat_id})
12 | if lovers:
13 | lovers = lovers["couple"]
14 | else:
15 | lovers = {}
16 | return lovers
17 |
18 |
19 | async def get_couple(chat_id: int, date: str):
20 | lovers = await _get_lovers(chat_id)
21 | if date in lovers:
22 | return lovers[date]
23 | else:
24 | return False
25 |
26 |
27 | async def save_couple(chat_id: int, date: str, couple: dict):
28 | lovers = await _get_lovers(chat_id)
29 | lovers[date] = couple
30 | coupledb.update_one(
31 | {"chat_id": chat_id},
32 | {
33 | "$set": {
34 | "couple": lovers
35 | }
36 | },
37 | upsert=True
38 | )
39 |
40 |
41 | # Karma functions
42 |
43 |
44 | async def get_karmas_count() -> dict:
45 | chats = karmadb.find({"chat_id": {"$lt": 0}})
46 | if not chats:
47 | return {}
48 | chats_count = 0
49 | karmas_count = 0
50 | for chat in await chats.to_list(length=1000000):
51 | for i in chat['karma']:
52 | karmas_count += chat['karma'][i]['karma']
53 | chats_count += 1
54 | return {
55 | "chats_count": chats_count,
56 | "karmas_count": karmas_count
57 | }
58 |
59 |
60 | async def get_karmas(chat_id: int) -> Dict[str, int]:
61 | karma = karmadb.find_one({"chat_id": chat_id})
62 | if karma:
63 | karma = karma['karma']
64 | else:
65 | karma = {}
66 | return karma
67 |
68 |
69 | async def get_karma(chat_id: int, name: str) -> Union[bool, dict]:
70 | name = name.lower().strip()
71 | karmas = await get_karmas(chat_id)
72 | if name in karmas:
73 | return karmas[name]
74 |
75 |
76 | async def update_karma(chat_id: int, name: str, karma: dict):
77 | name = name.lower().strip()
78 | karmas = await get_karmas(chat_id)
79 | karmas[name] = karma
80 | karmadb.update_one(
81 | {"chat_id": chat_id},
82 | {
83 | "$set": {
84 | "karma": karmas
85 | }
86 | },
87 | upsert=True
88 | )
89 |
90 |
91 | # Alpha integer
92 |
93 | async def int_to_alpha(user_id: int) -> str:
94 | alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
95 | text = ""
96 | user_id = str(user_id)
97 | for i in user_id:
98 | text += alphabet[int(i)]
99 | return text
100 |
101 |
102 | async def alpha_to_int(user_id_alphabet: str) -> int:
103 | alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
104 | user_id = ""
105 | for i in user_id_alphabet:
106 | index = alphabet.index(i)
107 | user_id += str(index)
108 | user_id = int(user_id)
109 | return user_id
110 |
--------------------------------------------------------------------------------
/EvilBot/utils/errors.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import traceback
3 | from functools import wraps
4 | from EvilBot import pbot as app
5 | from pyrogram.errors.exceptions.forbidden_403 import ChatWriteForbidden
6 |
7 | LOG_GROUP_ID = int(-1001236063876)
8 |
9 | def split_limits(text):
10 | if len(text) < 2048:
11 | return [text]
12 |
13 | lines = text.splitlines(True)
14 | small_msg = ''
15 | result = []
16 | for line in lines:
17 | if len(small_msg) + len(line) < 2048:
18 | small_msg += line
19 | else:
20 | result.append(small_msg)
21 | small_msg = line
22 | else:
23 | result.append(small_msg)
24 |
25 | return result
26 |
27 |
28 | def capture_err(func):
29 | @wraps(func)
30 | async def capture(client, message, *args, **kwargs):
31 | try:
32 | return await func(client, message, *args, **kwargs)
33 | except ChatWriteForbidden:
34 | await app.leave_chat(message.chat.id)
35 | return
36 | except Exception as err:
37 | exc_type, exc_obj, exc_tb = sys.exc_info()
38 | errors = traceback.format_exception(
39 | etype=exc_type, value=exc_obj, tb=exc_tb,
40 | )
41 | error_feedback = split_limits(
42 | '**ERROR** | `{}` | `{}`\n\n```{}```\n\n```{}```\n'.format(
43 | 0 if not message.from_user else message.from_user.id,
44 | 0 if not message.chat else message.chat.id,
45 | message.text or message.caption,
46 | ''.join(errors),
47 | ),
48 | )
49 | for x in error_feedback:
50 | await app.send_message(
51 | LOG_GROUP_ID,
52 | x
53 | )
54 | raise err
55 | return capture
56 |
--------------------------------------------------------------------------------
/EvilBot/utils/filter_groups.py:
--------------------------------------------------------------------------------
1 | karma_positive_group = 3
2 | karma_negative_group = 4
3 |
--------------------------------------------------------------------------------
/Git_Pull.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | TITLE Github Quick-Pull
3 |
4 | :: Print the branch cause ..oooooo fancy!
5 | echo Pulling from branch:
6 | git branch
7 | echo.
8 | git pull
9 |
--------------------------------------------------------------------------------
/Git_Push.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | TITLE Github Quick-pushing
3 |
4 | :: Print the branch cause people like me push to wrong branches and cry about it later.
5 | echo Pushing to branch:
6 | git branch
7 | echo.
8 | :: Take input for comment and thats about it
9 | set /p commit_title="Enter Commit title (pushes with you as author): "
10 |
11 | :: If you are reading comments to understand this part then you can go back stab yourself.
12 | echo.
13 | git pull
14 | git add *
15 | git commit -m "%commit_title%"
16 | git push
17 |
18 |
19 | :: Hail Hydra
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | worker: python3 -m EvilBot
2 | ps:scale worker=1
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 😈EVIL BOT😈
2 |
3 |
4 | ## You can also tap the Deploy To Heroku button below to deploy straight to Heroku!
5 |
6 | [](https://heroku.com/deploy?template=https://github.com/shrvan42/EvilBot)
24 |
25 |