Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .idea/EnterpriseALRobot.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 3 additions & 5 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ bleach
cachetools
configparser
currencyconverter
emoji
emoji==1.7.0
feedparser
future
git+https://github.com/python-telegram-bot/ptbcontrib.git
gitpython
gpytranslate
markdown2
Expand All @@ -17,8 +16,8 @@ pillow>=4.2.0
psutil
psycopg2-binary
pyYAML>=5.1.2
pyrate-limiter
python-telegram-bot==13.11
pyrate-limiter==2.8.1
python-telegram-bot==13.15
requests
spamwatch
speedtest-cli
Expand All @@ -38,4 +37,3 @@ pytz

gtts
wikipedia

Empty file modified run.sh
100644 → 100755
Empty file.
18 changes: 4 additions & 14 deletions tg_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
from typing import List
import spamwatch
import telegram.ext as tg
from telegram.ext import Dispatcher, Updater
from telegram.ext import Dispatcher, JobQueue, Updater
from telethon import TelegramClient
from telethon.sessions import MemorySession
from configparser import ConfigParser
from ptbcontrib.postgres_persistence import PostgresPersistence
from functools import wraps
from SibylSystem import PsychoPass
try:
Expand Down Expand Up @@ -46,8 +45,6 @@ def get_user_list(key):
logging.basicConfig(handlers = [file_handler, stream_handler, debug_handler], level = logging.DEBUG)
log = logging.getLogger('[Enterprise]')

logging.getLogger('ptbcontrib.postgres_persistence.postgrespersistence').setLevel(logging.WARNING)

log.info("LOGGER is starting. | Project maintained by: github.com/itsLuuke (t.me/itsLuuke)")

# if version < 3.6, stop bot.
Expand Down Expand Up @@ -134,9 +131,6 @@ def __init__(self, parser: ConfigParser):
self.SIBYL_ENDPOINT = self.parser.get("SIBYL_ENDPOINT", "https://psychopass.kaizoku.cyou")





def init_sw(self):
if self.spamwatch_api is None:
log.warning("SpamWatch API key is missing! Check your config.ini")
Expand Down Expand Up @@ -234,15 +228,11 @@ def init_sw(self):

from tg_bot.modules.sql import SESSION

if not KInit.DROP_UPDATES:
updater: Updater = tg.Updater(token=TOKEN, base_url=KInit.BOT_API_URL, base_file_url=KInit.BOT_API_FILE_URL, workers=min(32, os.cpu_count() + 4), request_kwargs={"read_timeout": 10, "connect_timeout": 10}, persistence=PostgresPersistence(session=SESSION))

else:
updater = tg.Updater(token=TOKEN, base_url=KInit.BOT_API_URL, base_file_url=KInit.BOT_API_FILE_URL, workers=min(32, os.cpu_count() + 4), request_kwargs={"read_timeout": 10, "connect_timeout": 10})

updater: Updater = tg.Updater(token=TOKEN, base_url=KInit.BOT_API_URL, base_file_url=KInit.BOT_API_FILE_URL, workers=min(32, os.cpu_count() + 4), request_kwargs={"read_timeout": 10, "connect_timeout": 10})

telethn = TelegramClient(MemorySession(), APP_ID, API_HASH)
dispatcher: Dispatcher = updater.dispatcher
j: Updater.job_queue = updater.job_queue
j: JobQueue = updater.job_queue



Expand Down
15 changes: 5 additions & 10 deletions tg_bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,29 +680,24 @@ def migrate_chats(update: Update, _: CallbackContext):
def main():
dispatcher.add_error_handler(error_callback)
# dispatcher.add_error_handler(error_handler)
allowed_updates = ['message', 'edited_message', 'callback_query', 'callback_query', 'my_chat_member',
'chat_member', 'chat_join_request', 'channel_post', 'edited_channel_post', 'inline_query']

if WEBHOOK:
log.info("Using webhooks.")
updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN)
updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN, allowed_updates=allowed_updates, webhook_url=URL+TOKEN, drop_pending_updates=KInit.DROP_UPDATES, cert=CERT_PATH if CERT_PATH else None)

if CERT_PATH:
updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, "rb"))
else:
updater.bot.set_webhook(url=URL + TOKEN)
print(f"Updater started! Using webhooks. | BOT: [@{dispatcher.bot.username}]")

else:
dispatcher.bot.sendMessage(OWNER_ID, "Master, I'm awake!")
# if SUPPORT_GROUP:
# dispatcher.bot.sendMessage(SUPPORT_GROUP, "I'm up!")
KigyoINIT.bot_id = dispatcher.bot.id
KigyoINIT.bot_username = dispatcher.bot.username
KigyoINIT.bot_name = dispatcher.bot.first_name

allowed_updates = ['message', 'edited_message', 'callback_query', 'callback_query', 'my_chat_member',
'chat_member', 'chat_join_request', 'channel_post', 'edited_channel_post', 'inline_query']
updater.start_polling(
timeout=15, read_latency=4, allowed_updates=allowed_updates, drop_pending_updates=KInit.DROP_UPDATES)
print(f"Updater started! Using long polling. | BOT: [@{dispatcher.bot.username}]")
dispatcher.bot.sendMessage(OWNER_ID, "Master, I'm awake!")
telethn.run_until_disconnected()
updater.idle()

Expand Down
8 changes: 7 additions & 1 deletion tg_bot/langs/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ bans_help: |
- /tban <userhandle> x(m/h/d): bans a user for x time. (via handle, or reply). m = minutes, h = hours, d = days.
- /unban <userhandle>: unbans a user. (via handle, or reply)
- /kick <userhandle>: kick a user out of the group, (via handle, or reply)
- /dkick <userhandle>: kick a user out of the group, silently.
- /skick <userhandle>: kick a user out of the group, deleting the replied to message.
- /dskick <userhandle>: kick a user out of the group deleting the sent and replied to message.

blacklist_help: |
Blacklists are used to stop certain triggers from being said in a group. Any time the trigger is mentioned, the message will immediately be deleted. A good combo is sometimes to pair this up with warn filters!
Expand All @@ -144,7 +147,7 @@ blacklist_help: |
• `/unblacklist <triggers>`*:* Remove triggers from the blacklist. Same newline logic applies here, so you can remove multiple triggers at once.
• `/unblocklist <triggers>`*:* Same as unblacklist
• `/blacklistmode <off/del/warn/ban/kick/mute/tban/tmute>`*:* Action to perform when someone sends blacklisted words.
• `/blacklistmode <off/del/warn/ban/kick/mute/tban/tmute>`*:* Same as blacklistmode
• `/blocklistmode <off/del/warn/ban/kick/mute/tban/tmute>`*:* Same as blacklistmode

Owner only:
• `/removeallblacklists`*:* Removes all blacklists from the chat.
Expand Down Expand Up @@ -452,6 +455,9 @@ misc_help: |
muting_help: |
*Admins only:*
• `/mute <userhandle>`*:* silences a user. Can also be used as a reply, muting the replied to user.
• `/dmute <userhandle>`*:* silences a user. silently.
• `/smute <userhandle>`*:* silences a user. deleting the replied to message.
• `/dsmute <userhandle>`*:* silences a user. deleting the sent and replied to message.
• `/tmute <userhandle> x(m/h/d)`*:* mutes a user for x time. (via handle, or reply). `m` = `minutes`, `h` = `hours`, `d` = `days`.
• `/unmute <userhandle>`*:* unmutes a user. Can also be used as a reply, muting the replied to user.

Expand Down
35 changes: 31 additions & 4 deletions tg_bot/modules/admin.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import html
import time

from telegram import ParseMode, Update
from telegram.error import BadRequest
from telegram.ext import CallbackContext

from telegram.utils.helpers import mention_html
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.types import ChannelParticipantsAdmins
from telethon.tl.types import ChannelParticipantCreator
from tg_bot import telethn
Expand All @@ -23,9 +23,7 @@
bot_admin_check,
AdminPerms,
get_bot_member,
bot_is_admin,
user_is_admin,
user_not_admin_check,
A_CACHE, B_CACHE
)

from typing import Optional
Expand Down Expand Up @@ -392,6 +390,35 @@ def invite(update: Update, context: CallbackContext) -> Optional[str]:
)


@kigcmd(command=["admincache"], can_disable=False)
@spamcheck
def admincache(update: Update, context: CallbackContext):
chat = update.effective_chat
msg = update.effective_message
user = update.effective_user
try:
last = _admincache[chat.id]
except KeyError:
last = None
now = time.time()
if last and last + 600 > now:
return msg.reply_text("this command can only be used once every 10 minutes")

if chat.type in ["channel", "private"]:
return msg.reply_text("this command can only be used in groups")

if chat.get_member(user.id).status not in ["administrator", "creator"] and user.id != 1087968824:
return msg.reply_text("this command can only be used by admins")

A_CACHE[update.effective_chat.id] = update.effective_chat.get_administrators()
B_CACHE[update.effective_chat.id] = update.effective_chat.get_member(context.bot.id)
msg.reply_text("Admin cache updated")
_admincache[chat.id] = time.time()


_admincache = dict()


@register(pattern="(admin|admins|staff|adminlist)", groups_only=True, no_args=True)
async def adminList(event):
try:
Expand Down
50 changes: 31 additions & 19 deletions tg_bot/modules/bans.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def cannot_ban(banner_id, user_id, message) -> bool:
AdminPerms,
bot_is_admin,
user_is_admin,
u_na_errmsg,
)


Expand Down Expand Up @@ -371,7 +372,7 @@ def temp_ban(update: Update, context: CallbackContext) -> str:
return log_message


@kigcmd(command=['kick', 'punch'], pass_args=True)
@kigcmd(command=['kick', 'skick', 'dkick', 'dskick', 'punch'], pass_args=True)
@spamcheck
@connection_status
@bot_admin_check(AdminPerms.CAN_RESTRICT_MEMBERS)
Expand All @@ -383,8 +384,9 @@ def kick(update: Update, context: CallbackContext) -> str:
message = update.effective_message
log_message = ""
bot, args = context.bot, context.args

if message.reply_to_message.sender_chat:
silent = message.text[1] == 's' or message.text[2] == 's'
delete = message.text[1] == 'd'
if message.reply_to_message and message.reply_to_message.sender_chat:
message.reply_text("This command doesn't work on channels, but I can ban them if u want.")
return log_message

Expand Down Expand Up @@ -412,24 +414,34 @@ def kick(update: Update, context: CallbackContext) -> str:
message.reply_text("This user has immunity and cannot be banned.")
return ''

if chat.unban_member(user_id):
bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker

if reason:

bot.sendMessage(
chat.id,
f"{mention_html(member.user.id, member.user.first_name)} was kicked by {mention_html(user.id, user.first_name)} in {message.chat.title}\n<b>Reason</b>: <code>{reason}</code>",
parse_mode=ParseMode.HTML,
)

if delete and message.reply_to_message:
if user_is_admin(update, message.from_user.id, perm=AdminPerms.CAN_DELETE_MESSAGES):
if bot_is_admin(chat, AdminPerms.CAN_DELETE_MESSAGES):
message.reply_to_message.delete()
else:
update.effective_message.reply_text(
f"I can't perform this action due to missing permissions;\n"
f"Make sure i am an admin and {AdminPerms.CAN_DELETE_MESSAGES.name.lower().replace('is_', 'am ').replace('_', ' ')}!")
return
else:
return u_na_errmsg(message, AdminPerms.CAN_DELETE_MESSAGES)

bot.sendMessage(
chat.id,
f"{mention_html(member.user.id, member.user.first_name)} was kicked by {mention_html(user.id, user.first_name)} in {message.chat.title}",
parse_mode=ParseMode.HTML,
)

if chat.unban_member(user_id):
if not silent:
bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker
if reason:
bot.sendMessage(
chat.id,
f"{mention_html(member.user.id, member.user.first_name)} was kicked by {mention_html(user.id, user.first_name)} in {message.chat.title}\n<b>Reason</b>: <code>{reason}</code>",
parse_mode=ParseMode.HTML,
)
else:
bot.sendMessage(
chat.id,
f"{mention_html(member.user.id, member.user.first_name)} was kicked by {mention_html(user.id, user.first_name)} in {message.chat.title}",
parse_mode=ParseMode.HTML,
)

log = (
f"<b>{html.escape(chat.title)}:</b>\n"
Expand Down
2 changes: 1 addition & 1 deletion tg_bot/modules/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def connect_button(update, context):
def get_help(chat):
return gs(chat, "connections_help")

CONNECT_CHAT_HANDLER = CommandHandler("connect", connect_chat, pass_args=True)
CONNECT_CHAT_HANDLER = CommandHandler("connect", connect_chat, pass_args=True, run_async=True)
CONNECTION_CHAT_HANDLER = CommandHandler("connection", connection_chat, run_async=True)
DISCONNECT_CHAT_HANDLER = CommandHandler("disconnect", disconnect_chat, run_async=True)
ALLOW_CONNECTIONS_HANDLER = CommandHandler(
Expand Down
36 changes: 25 additions & 11 deletions tg_bot/modules/disable.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Union
from typing import Union, Optional

from future.utils import string_types
from telegram import ParseMode, Update, Chat
Expand Down Expand Up @@ -214,16 +214,30 @@ def enable(update, context):
@user_admin_check(AdminPerms.CAN_CHANGE_INFO)
@typing_action
def list_cmds(update, context):
if DISABLE_CMDS + DISABLE_OTHER:
if DISABLE_CMDS:
result = "".join(
" - `{}`\n".format(escape_markdown(str(cmd)))
for cmd in set(DISABLE_CMDS + DISABLE_OTHER)
for cmd in set(DISABLE_CMDS)
)

update.effective_message.reply_text(
"The following commands are toggleable:\n{}".format(result),
parse_mode=ParseMode.MARKDOWN,
)
text = "The following commands are toggleable:\n{}".format(result)
def paginate(text):
lines = text.split("\n")
previous_text = ""
for line in lines:
if len(previous_text) + 1 + len(line) > 4096: # char limit
yield previous_text
# stop before limit, if adding line makes msg too long
previous_text = line
else:
previous_text = (previous_text + "\n" + line).strip("\n")
yield previous_text

for page in paginate(text):
update.effective_message.reply_text(
page,
parse_mode=ParseMode.MARKDOWN,
)
else:
update.effective_message.reply_text("No commands can be disabled.")

Expand Down Expand Up @@ -291,16 +305,16 @@ def __chat_settings__(chat_id, user_id):
"""

DISABLE_HANDLER = CommandHandler(
"disable", disable, pass_args=True
"disable", disable, pass_args=True, run_async=True
) # , filters=Filters.chat_type.groups)
ENABLE_HANDLER = CommandHandler(
"enable", enable, pass_args=True
"enable", enable, pass_args=True, run_async=True
) # , filters=Filters.chat_type.groups)
COMMANDS_HANDLER = CommandHandler(
["cmds", "disabled"], commands
["cmds", "disabled"], commands, run_async=True
) # , filters=Filters.chat_type.groups)
TOGGLE_HANDLER = CommandHandler(
"listcmds", list_cmds
"listcmds", list_cmds, run_async=True
) # , filters=Filters.chat_type.groups)

dispatcher.add_handler(DISABLE_HANDLER)
Expand Down
Loading