From f9da0356c3a5b7fc39ce845eaeae717f12b411ea Mon Sep 17 00:00:00 2001
From: Sourcery AI <>
Date: Sun, 19 Jul 2020 20:00:23 +0000
Subject: [PATCH] 'Refactored by Sourcery'
---
lynda/__main__.py | 26 +-
lynda/modules/admin.py | 12 +-
lynda/modules/anime.py | 4 +-
lynda/modules/antiflood.py | 5 +-
lynda/modules/bans.py | 6 +-
lynda/modules/blacklist.py | 6 +-
lynda/modules/blacklist_stickers.py | 11 +-
lynda/modules/blacklistusers.py | 6 +-
lynda/modules/cleaner.py | 36 +--
lynda/modules/cust_filters.py | 12 +-
lynda/modules/dbcleanup.py | 77 +++---
lynda/modules/disable.py | 10 +-
lynda/modules/disasters.py | 24 +-
lynda/modules/extra.py | 28 +-
lynda/modules/feds.py | 243 ++++++++----------
lynda/modules/fun.py | 19 +-
lynda/modules/global_bans.py | 46 ++--
lynda/modules/gtranslator.py | 5 +-
lynda/modules/helper_funcs/chat_status.py | 6 +-
lynda/modules/helper_funcs/extraction.py | 12 +-
lynda/modules/helper_funcs/handlers.py | 5 +-
lynda/modules/helper_funcs/msg_types.py | 18 +-
lynda/modules/helper_funcs/string_handling.py | 49 ++--
.../helper_funcs/telethn/chatstatus.py | 56 ++--
lynda/modules/lastfm.py | 2 +-
lynda/modules/locks.py | 14 +-
lynda/modules/log_channel.py | 16 +-
lynda/modules/misc.py | 12 +-
lynda/modules/modules.py | 2 +-
lynda/modules/muting.py | 20 +-
lynda/modules/notes.py | 2 +-
lynda/modules/ping.py | 7 +-
lynda/modules/reporting.py | 2 +-
lynda/modules/rss.py | 15 +-
lynda/modules/rules.py | 2 +-
lynda/modules/sed.py | 63 ++---
lynda/modules/special.py | 8 +-
lynda/modules/sql/chatbot_sql.py | 5 +-
lynda/modules/sql/cleaner_sql.py | 15 +-
lynda/modules/sql/feds_sql.py | 90 +++----
lynda/modules/stickers.py | 50 ++--
lynda/modules/userinfo.py | 16 +-
lynda/modules/users.py | 4 +-
lynda/modules/welcome.py | 85 +++---
44 files changed, 480 insertions(+), 672 deletions(-)
diff --git a/lynda/__main__.py b/lynda/__main__.py
index 8d407d9a..fb719832 100644
--- a/lynda/__main__.py
+++ b/lynda/__main__.py
@@ -72,7 +72,7 @@
if not hasattr(imported_module, "__mod_name__"):
imported_module.__mod_name__ = imported_module.__name__
- if not imported_module.__mod_name__.lower() in IMPORTED:
+ if imported_module.__mod_name__.lower() not in IMPORTED:
IMPORTED[imported_module.__mod_name__.lower()] = imported_module
else:
raise Exception(
@@ -242,13 +242,11 @@ def help_button(bot: Bot, update: Update):
bot.answer_callback_query(query.id)
query.message.delete()
except BadRequest as excp:
- if excp.message == "Message is not modified":
- pass
- elif excp.message == "Query_id_invalid":
- pass
- elif excp.message == "Message can't be deleted":
- pass
- else:
+ if (
+ excp.message != "Message is not modified"
+ and excp.message != "Query_id_invalid"
+ and excp.message != "Message can't be deleted"
+ ):
LOGGER.exception("Exception in help buttons. %s", str(query.data))
@@ -379,13 +377,11 @@ def settings_button(bot: Bot, update: Update):
bot.answer_callback_query(query.id)
query.message.delete()
except BadRequest as excp:
- if excp.message == "Message is not modified":
- pass
- elif excp.message == "Query_id_invalid":
- pass
- elif excp.message == "Message can't be deleted":
- pass
- else:
+ if (
+ excp.message != "Message is not modified"
+ and excp.message != "Query_id_invalid"
+ and excp.message != "Message can't be deleted"
+ ):
LOGGER.exception(
"Exception in settings buttons. %s", str(
query.data))
diff --git a/lynda/modules/admin.py b/lynda/modules/admin.py
index ef763566..6e3b8d8c 100644
--- a/lynda/modules/admin.py
+++ b/lynda/modules/admin.py
@@ -37,7 +37,7 @@ def promote(bot: Bot, update: Update, args: List[str]) -> str:
except Exception:
return log_message
- if user_member.status == 'administrator' or user_member.status == 'creator':
+ if user_member.status in ['administrator', 'creator']:
message.reply_text("How am I meant to promote someone that's already an admin?")
return log_message
@@ -61,11 +61,9 @@ def promote(bot: Bot, update: Update, args: List[str]) -> str:
except BadRequest as err:
if err.message == "User_not_mutual_contact":
message.reply_text("I can't promote someone who isn't in the group.")
- return log_message
else:
message.reply_text("An error occured while promoting.")
- return log_message
-
+ return log_message
bot.sendMessage(chat.id, f"Sucessfully promoted {user_member.user.first_name or user_id}!",
parse_mode=ParseMode.HTML)
@@ -104,7 +102,7 @@ def demote(bot: Bot, update: Update, args: List[str]) -> str:
message.reply_text("This person CREATED the chat, how would I demote them?")
return log_message
- if not user_member.status == 'administrator':
+ if user_member.status != 'administrator':
message.reply_text("Can't demote what wasn't promoted!")
return log_message
@@ -163,7 +161,7 @@ def set_title(bot: Bot, update: Update, args: List[str]):
message.reply_text("This person CREATED the chat, how can i set custom title for him?")
return
- if not user_member.status == 'administrator':
+ if user_member.status != 'administrator':
message.reply_text("Can't set title for non-admins!\nPromote them first to set custom title!")
return
@@ -256,7 +254,7 @@ def invite(bot: Bot, update: Update):
if chat.username:
update.effective_message.reply_text(chat.username)
- elif chat.type == chat.SUPERGROUP or chat.type == chat.CHANNEL:
+ elif chat.type in [chat.SUPERGROUP, chat.CHANNEL]:
bot_member = chat.get_member(bot.id)
if bot_member.can_invite_users:
invitelink = bot.exportChatInviteLink(chat.id)
diff --git a/lynda/modules/anime.py b/lynda/modules/anime.py
index 4353afdd..b9ca14e1 100644
--- a/lynda/modules/anime.py
+++ b/lynda/modules/anime.py
@@ -58,7 +58,6 @@ def formatJSON(outData):
res = list(jsonData.keys())
if "errors" in res:
msg += f"**Error** : `{jsonData['errors'][0]['message']}`"
- return msg
else:
jsonData = jsonData['data']['Media']
if "bannerImage" in jsonData.keys():
@@ -78,7 +77,8 @@ def formatJSON(outData):
msg += f"\n**Score** : {jsonData['averageScore']}"
msg += f"\n**Duration** : {jsonData['duration']} min"
msg += f"\n\n __{jsonData['description']}__"
- return msg
+
+ return msg
@run_async
diff --git a/lynda/modules/antiflood.py b/lynda/modules/antiflood.py
index d2fd0e9e..ae0424d3 100644
--- a/lynda/modules/antiflood.py
+++ b/lynda/modules/antiflood.py
@@ -104,12 +104,9 @@ def set_flood(_bot: Bot, update: Update, args: List[str]) -> str:
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"Disabled antiflood.")
- return log_message
elif amount < 3:
message.reply_text(
"Antiflood has to be either 0 (disabled), or a number bigger than 3!")
- return log_message
-
else:
sql.set_flood(chat.id, amount)
message.reply_text(
@@ -121,7 +118,7 @@ def set_flood(_bot: Bot, update: Update, args: List[str]) -> str:
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"Set antiflood to {amount}.")
- return log_message
+ return log_message
else:
message.reply_text(
"Unrecognised argument - please use a number, 'off', or 'no'.")
diff --git a/lynda/modules/bans.py b/lynda/modules/bans.py
index b0dcb379..fe38c79b 100644
--- a/lynda/modules/bans.py
+++ b/lynda/modules/bans.py
@@ -153,11 +153,7 @@ def temp_ban(bot: Bot, update: Update, args: List[str]) -> str:
split_reason = reason.split(None, 1)
time_val = split_reason[0].lower()
- if len(split_reason) > 1:
- reason = split_reason[1]
- else:
- reason = ""
-
+ reason = split_reason[1] if len(split_reason) > 1 else ""
bantime = extract_time(message, time_val)
if not bantime:
diff --git a/lynda/modules/blacklist.py b/lynda/modules/blacklist.py
index 047bffb9..eecf1278 100644
--- a/lynda/modules/blacklist.py
+++ b/lynda/modules/blacklist.py
@@ -34,7 +34,7 @@ def blacklist(_bot: Bot, update: Update, args: List[str]):
filter_list = base_blacklist_string
- if len(args) > 0 and args[0].lower() == 'copy':
+ if args and args[0].lower() == 'copy':
for trigger in all_blacklisted:
filter_list += f"{html.escape(trigger)}\n"
else:
@@ -150,9 +150,7 @@ def del_blacklist(_bot: Bot, update: Update):
try:
message.delete()
except BadRequest as excp:
- if excp.message == "Message to delete not found":
- pass
- else:
+ if excp.message != "Message to delete not found":
LOGGER.exception("Error while deleting blacklist message.")
break
diff --git a/lynda/modules/blacklist_stickers.py b/lynda/modules/blacklist_stickers.py
index 93833306..41e11da4 100644
--- a/lynda/modules/blacklist_stickers.py
+++ b/lynda/modules/blacklist_stickers.py
@@ -41,7 +41,7 @@ def blackliststicker(bot: Bot, update: Update, args: List[str]):
all_stickerlist = sql.get_chat_stickers(chat_id)
- if len(args) > 0 and args[0].lower() == 'copy':
+ if args and args[0].lower() == 'copy':
for trigger in all_stickerlist:
sticker_list += "{}\n".format(html.escape(trigger))
elif len(args) == 0:
@@ -257,11 +257,10 @@ def blacklist_mode(bot: Bot, update: Update, args: List[str]):
chat_name = update.effective_message.chat.title
if args:
- if args[0].lower() == 'off' or args[0].lower(
- ) == 'nothing' or args[0].lower() == 'no':
+ if args[0].lower() in ['off', 'nothing', 'no']:
settypeblacklist = 'turn off'
sql.set_blacklist_strength(chat_id, 0, "0")
- elif args[0].lower() == 'del' or args[0].lower() == 'delete':
+ elif args[0].lower() in ['del', 'delete']:
settypeblacklist = 'left, the message will be deleted'
sql.set_blacklist_strength(chat_id, 1, "0")
elif args[0].lower() == 'warn':
@@ -446,9 +445,7 @@ def del_blackliststicker(bot: Bot, update: Update):
parse_mode="markdown")
return
except BadRequest as excp:
- if excp.message == "Message to delete not found":
- pass
- else:
+ if excp.message != "Message to delete not found":
LOGGER.exception("Error while deleting blacklist message.")
break
diff --git a/lynda/modules/blacklistusers.py b/lynda/modules/blacklistusers.py
index 3c62a3a5..3d0c6541 100644
--- a/lynda/modules/blacklistusers.py
+++ b/lynda/modules/blacklistusers.py
@@ -120,11 +120,7 @@ def bl_users(bot: Bot, update: Update):
users.append(f"• {mention_html(user.id, user.first_name)}")
message = "Blacklisted Users\n"
- if not users:
- message += "Noone is being ignored as of yet."
- else:
- message += '\n'.join(users)
-
+ message += '\n'.join(users) if users else "Noone is being ignored as of yet."
update.effective_message.reply_text(message, parse_mode=ParseMode.HTML)
diff --git a/lynda/modules/cleaner.py b/lynda/modules/cleaner.py
index 36ca44fc..490376c2 100644
--- a/lynda/modules/cleaner.py
+++ b/lynda/modules/cleaner.py
@@ -10,11 +10,7 @@
from lynda.modules.helper_funcs.chat_status import user_admin, bot_can_delete, dev_plus, connection_status
from lynda.modules.sql import cleaner_sql as sql
-if ALLOW_EXCL:
- CMD_STARTERS = ('/', '!')
-else:
- CMD_STARTERS = '/'
-
+CMD_STARTERS = ('/', '!') if ALLOW_EXCL else '/'
BLUE_TEXT_CLEAN_GROUP = 15
CommandHandlerList = (
CommandHandler,
@@ -43,24 +39,23 @@
def clean_blue_text_must_click(bot: Bot, update: Update):
chat = update.effective_chat
- message = update.effective_message
+ if chat.get_member(bot.id).can_delete_messages and sql.is_enabled(chat.id):
+ message = update.effective_message
- if chat.get_member(bot.id).can_delete_messages:
- if sql.is_enabled(chat.id):
- fst_word = message.text.strip().split(None, 1)[0]
+ fst_word = message.text.strip().split(None, 1)[0]
- if len(fst_word) > 1 and any(fst_word.startswith(start)
- for start in CMD_STARTERS):
+ if len(fst_word) > 1 and any(fst_word.startswith(start)
+ for start in CMD_STARTERS):
- command = fst_word[1:].split('@')
- chat = update.effective_chat
+ command = fst_word[1:].split('@')
+ chat = update.effective_chat
- ignored = sql.is_command_ignored(chat.id, command[0])
- if ignored:
- return
+ ignored = sql.is_command_ignored(chat.id, command[0])
+ if ignored:
+ return
- if command[0] not in command_list:
- message.delete()
+ if command[0] not in command_list:
+ message.delete()
@run_async
@@ -91,10 +86,7 @@ def set_blue_text_must_click(_bot: Bot, update: Update, args: List[str]):
message.reply_text(reply)
else:
clean_status = sql.is_enabled(chat.id)
- if clean_status:
- clean_status = "Enabled"
- else:
- clean_status = "Disabled"
+ clean_status = "Enabled" if clean_status else "Disabled"
reply = "Bluetext cleaning for {} : {}".format(
chat.title, clean_status)
message.reply_text(reply, parse_mode=ParseMode.HTML)
diff --git a/lynda/modules/cust_filters.py b/lynda/modules/cust_filters.py
index 4969de40..267f0d49 100644
--- a/lynda/modules/cust_filters.py
+++ b/lynda/modules/cust_filters.py
@@ -215,18 +215,18 @@ def reply_filter(bot: Bot, update: Update):
disable_web_page_preview=True,
reply_markup=keyboard)
except BadRequest as excp:
- if excp.message == "Unsupported url protocol":
- message.reply_text(
- "You seem to be trying to use an unsupported url protocol. Telegram "
- "doesn't support buttons for some protocols, such as tg://. Please try "
- "again, or ask @Aman_Ahmed for help.")
- elif excp.message == "Reply message not found":
+ if excp.message == "Reply message not found":
bot.send_message(
chat.id,
filt.reply,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=keyboard)
+ elif excp.message == "Unsupported url protocol":
+ message.reply_text(
+ "You seem to be trying to use an unsupported url protocol. Telegram "
+ "doesn't support buttons for some protocols, such as tg://. Please try "
+ "again, or ask @Aman_Ahmed for help.")
else:
message.reply_text(
"This note could not be sent, as it is incorrectly formatted. Ask in "
diff --git a/lynda/modules/dbcleanup.py b/lynda/modules/dbcleanup.py
index f9c0963f..4a48305a 100644
--- a/lynda/modules/dbcleanup.py
+++ b/lynda/modules/dbcleanup.py
@@ -40,21 +40,16 @@ def get_invalid_chats(bot: Bot, update: Update, remove: bool = False):
chat_list.append(cid)
except Exception as e:
print(e)
- pass
-
try:
progress_message.delete()
except Exception as e:
print(e)
- pass
-
- if not remove:
- return kicked_chats
- else:
+ if remove:
for muted_chat in chat_list:
sleep(0.1)
user_sql.rem_chat(muted_chat)
- return kicked_chats
+
+ return kicked_chats
def get_invalid_gban(bot: Bot, _update: Update, remove: bool = False):
@@ -72,15 +67,12 @@ def get_invalid_gban(bot: Bot, _update: Update, remove: bool = False):
ungban_list.append(user_id)
except Exception as e:
print(e)
- pass
-
- if not remove:
- return ungbanned_users
- else:
+ if remove:
for user_id in ungban_list:
sleep(0.1)
gban_sql.ungban_user(user_id)
- return ungbanned_users
+
+ return ungbanned_users
@run_async
@@ -122,7 +114,6 @@ def get_muted_chats(bot: Bot, update: Update, leave: bool = False):
progress_bar, chat_id, progress_message.message_id)
except Exception as e:
print(e)
- pass
else:
progress_message = bot.sendMessage(chat_id, progress_bar)
progress += 5
@@ -137,26 +128,20 @@ def get_muted_chats(bot: Bot, update: Update, leave: bool = False):
chat_list.append(cid)
except Exception as e:
print(e)
- pass
-
try:
progress_message.delete()
except Exception as e:
print(e)
- pass
-
- if not leave:
- return muted_chats
- else:
+ if leave:
for muted_chat in chat_list:
sleep(0.1)
try:
bot.leaveChat(muted_chat, timeout=60)
except Exception as e:
print(e)
- pass
user_sql.rem_chat(muted_chat)
- return muted_chats
+
+ return muted_chats
@run_async
@@ -187,29 +172,29 @@ def callback_button(bot: Bot, update: Update):
bot.answer_callback_query(query.id)
- if query_type == "db_leave_chat":
- if query.from_user.id in admin_list:
- bot.editMessageText(
- "Leaving chats ...",
- chat_id,
- message.message_id)
- chat_count = get_muted_chats(bot, update, True)
- bot.sendMessage(chat_id, f"Left {chat_count} chats.")
- else:
- query.answer("You are not allowed to use this.")
+ if query_type == "db_leave_chat" and query.from_user.id in admin_list:
+ bot.editMessageText(
+ "Leaving chats ...",
+ chat_id,
+ message.message_id)
+ chat_count = get_muted_chats(bot, update, True)
+ bot.sendMessage(chat_id, f"Left {chat_count} chats.")
+ elif (
+ query_type == "db_leave_chat"
+ or query_type == "db_cleanup"
+ and query.from_user.id not in admin_list
+ ):
+ query.answer("You are not allowed to use this.")
elif query_type == "db_cleanup":
- if query.from_user.id in admin_list:
- bot.editMessageText(
- "Cleaning up DB ...",
- chat_id,
- message.message_id)
- invalid_chat_count = get_invalid_chats(bot, update, True)
- invalid_gban_count = get_invalid_gban(bot, update, True)
- reply = "Cleaned up {} chats and {} gbanned users from db.".format(
- invalid_chat_count, invalid_gban_count)
- bot.sendMessage(chat_id, reply)
- else:
- query.answer("You are not allowed to use this.")
+ bot.editMessageText(
+ "Cleaning up DB ...",
+ chat_id,
+ message.message_id)
+ invalid_chat_count = get_invalid_chats(bot, update, True)
+ invalid_gban_count = get_invalid_gban(bot, update, True)
+ reply = "Cleaned up {} chats and {} gbanned users from db.".format(
+ invalid_chat_count, invalid_gban_count)
+ bot.sendMessage(chat_id, reply)
DB_CLEANUP_HANDLER = CommandHandler("dbcleanup", dbcleanup)
diff --git a/lynda/modules/disable.py b/lynda/modules/disable.py
index 70407f56..f9157158 100644
--- a/lynda/modules/disable.py
+++ b/lynda/modules/disable.py
@@ -75,10 +75,7 @@ def check_update(self, update):
chat = update.effective_chat
if super().check_update(update):
- if sql.is_command_disabled(chat.id, self.friendly):
- return False
- else:
- return True
+ return not sql.is_command_disabled(chat.id, self.friendly)
class DisableAbleRegexHandler(RegexHandler):
def __init__(
@@ -95,10 +92,7 @@ def __init__(
def check_update(self, update):
chat = update.effective_chat
if super().check_update(update):
- if sql.is_command_disabled(chat.id, self.friendly):
- return False
- else:
- return True
+ return not sql.is_command_disabled(chat.id, self.friendly)
@run_async
@connection_status
diff --git a/lynda/modules/disasters.py b/lynda/modules/disasters.py
index 258ccbc6..09b36e52 100644
--- a/lynda/modules/disasters.py
+++ b/lynda/modules/disasters.py
@@ -277,9 +277,6 @@ def addSardegna(bot: Bot, update: Update, args: List[str]) -> str:
@gloggable
def removesudo(bot: Bot, update: Update, args: List[str]) -> str:
message = update.effective_message
- user = update.effective_user
- chat = update.effective_chat
-
user_id = extract_user(message, args)
user_member = bot.getChat(user_id)
@@ -299,11 +296,14 @@ def removesudo(bot: Bot, update: Update, args: List[str]) -> str:
with open(ELEVATED_USERS_FILE, 'w') as outfile:
json.dump(data, outfile, indent=4)
+ user = update.effective_user
log_message = (
f"#UNSUDO\n"
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"User: {mention_html(user_member.id, user_member.first_name)}")
+ chat = update.effective_chat
+
if chat.type != 'private':
log_message = "{}:\n".format(
html.escape(chat.title)) + log_message
@@ -320,9 +320,6 @@ def removesudo(bot: Bot, update: Update, args: List[str]) -> str:
@gloggable
def removesupport(bot: Bot, update: Update, args: List[str]) -> str:
message = update.effective_message
- user = update.effective_user
- chat = update.effective_chat
-
user_id = extract_user(message, args)
user_member = bot.getChat(user_id)
@@ -342,11 +339,14 @@ def removesupport(bot: Bot, update: Update, args: List[str]) -> str:
with open(ELEVATED_USERS_FILE, 'w') as outfile:
json.dump(data, outfile, indent=4)
+ user = update.effective_user
log_message = (
f"#UNSUPPORT\n"
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"User: {mention_html(user_member.id, user_member.first_name)}")
+ chat = update.effective_chat
+
if chat.type != 'private':
log_message = f"{html.escape(chat.title)}:\n" + log_message
@@ -362,9 +362,6 @@ def removesupport(bot: Bot, update: Update, args: List[str]) -> str:
@gloggable
def removewhitelist(bot: Bot, update: Update, args: List[str]) -> str:
message = update.effective_message
- user = update.effective_user
- chat = update.effective_chat
-
user_id = extract_user(message, args)
user_member = bot.getChat(user_id)
@@ -384,11 +381,14 @@ def removewhitelist(bot: Bot, update: Update, args: List[str]) -> str:
with open(ELEVATED_USERS_FILE, 'w') as outfile:
json.dump(data, outfile, indent=4)
+ user = update.effective_user
log_message = (
f"#UNWHITELIST\n"
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"User: {mention_html(user_member.id, user_member.first_name)}")
+ chat = update.effective_chat
+
if chat.type != 'private':
log_message = f"{html.escape(chat.title)}:\n" + log_message
@@ -403,9 +403,6 @@ def removewhitelist(bot: Bot, update: Update, args: List[str]) -> str:
@gloggable
def removeSardegna(bot: Bot, update: Update, args: List[str]) -> str:
message = update.effective_message
- user = update.effective_user
- chat = update.effective_chat
-
user_id = extract_user(message, args)
user_member = bot.getChat(user_id)
@@ -425,11 +422,14 @@ def removeSardegna(bot: Bot, update: Update, args: List[str]) -> str:
with open(ELEVATED_USERS_FILE, 'w') as outfile:
json.dump(data, outfile, indent=4)
+ user = update.effective_user
log_message = (
f"#UNSARDEGNA\n"
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"User: {mention_html(user_member.id, user_member.first_name)}")
+ chat = update.effective_chat
+
if chat.type != 'private':
log_message = f"{html.escape(chat.title)}:\n" + log_message
diff --git a/lynda/modules/extra.py b/lynda/modules/extra.py
index 93dec2b2..f390ecee 100644
--- a/lynda/modules/extra.py
+++ b/lynda/modules/extra.py
@@ -135,7 +135,7 @@ def reverse(bot: Bot, update: Update, args: List[str]):
lim = 2
else:
lim = 2
- elif args and not reply:
+ elif args:
splatargs = msg.text.split(" ")
if len(splatargs) == 3:
img_link = splatargs[1]
@@ -257,7 +257,6 @@ def ParseSauce(googleurl):
results['override'] = url
except Exception as e:
print(e)
- pass
for similar_image in soup.findAll('input', {'class': 'gLFyf'}):
url = 'https://www.google.com/search?tbm=isch&q=' + \
urllib.parse.quote_plus(similar_image.get('value'))
@@ -304,11 +303,7 @@ def generate_time(to_find: str, findtype: List[str]) -> str:
country_zone = zone['zoneName']
country_code = zone['countryCode']
- if zone['dst'] == 1:
- daylight_saving = "Yes"
- else:
- daylight_saving = "No"
-
+ daylight_saving = "Yes" if zone['dst'] == 1 else "No"
date_fmt = r"%d-%m-%Y"
time_fmt = r"%H:%M:%S"
day_fmt = r"%A"
@@ -406,14 +401,10 @@ def convert(_bot: Bot, update: Update):
@run_async
def wall(bot: Bot, update: Update, args):
- chat_id = update.effective_chat.id
msg = update.effective_message
msg_id = update.effective_message.message_id
query = " ".join(args)
- if not query:
- msg.reply_text("Please enter a query!")
- return
- else:
+ if query:
caption = query
term = query.replace(" ", "%20")
json_rep = requests.get(
@@ -422,14 +413,12 @@ def wall(bot: Bot, update: Update, args):
msg.reply_text("An error occurred! Report this @LyndaEagleSupport")
else:
wallpapers = json_rep.get("wallpapers")
- if not wallpapers:
- msg.reply_text("No results found! Refine your search.")
- return
- else:
+ if wallpapers:
index = randint(0, len(wallpapers) - 1) # Choose random index
wallpaper = wallpapers[index]
wallpaper = wallpaper.get("url_image")
wallpaper = wallpaper.replace("\\", "")
+ chat_id = update.effective_chat.id
bot.send_photo(chat_id, photo=wallpaper, caption='Preview',
reply_to_message_id=msg_id, timeout=60)
bot.send_document(
@@ -440,6 +429,13 @@ def wall(bot: Bot, update: Update, args):
reply_to_message_id=msg_id,
timeout=60)
+ else:
+ msg.reply_text("No results found! Refine your search.")
+ return
+ else:
+ msg.reply_text("Please enter a query!")
+ return
+
@run_async
def covid(_bot: Bot, update: Update):
diff --git a/lynda/modules/feds.py b/lynda/modules/feds.py
index 6beed414..d6668650 100644
--- a/lynda/modules/feds.py
+++ b/lynda/modules/feds.py
@@ -74,7 +74,7 @@ def new_fed(bot: Bot, update: Update):
"Please write the name of the federation!")
return
fednam = message.text.split(None, 1)[1]
- if not fednam == '':
+ if fednam != '':
fed_id = str(uuid.uuid4())
fed_name = fednam
LOGGER.info(fed_id)
@@ -185,18 +185,13 @@ def join_fed(bot: Bot, update: Update, args: List[str]):
administrators = chat.get_administrators()
fed_id = sql.get_fed_id(chat.id)
- if user.id in SUDO_USERS:
- pass
- else:
+ if user.id not in SUDO_USERS:
for admin in administrators:
status = admin.status
- if status == "creator":
- if str(admin.user.id) == str(user.id):
- pass
- else:
- message.reply_text(
- "Only group creators can use this command!")
- return
+ if status == "creator" and str(admin.user.id) != str(user.id):
+ message.reply_text(
+ "Only group creators can use this command!")
+ return
if fed_id:
message.reply_text("You cannot join two federations from one chat")
return
@@ -214,14 +209,13 @@ def join_fed(bot: Bot, update: Update, args: List[str]):
return
get_fedlog = sql.get_fed_log(args[0])
- if get_fedlog:
- if eval(get_fedlog):
- bot.send_message(
- get_fedlog,
- "Chat *{}* has joined the federation *{}*".format(
- chat.title,
- getfed['fname']),
- parse_mode="markdown")
+ if get_fedlog and eval(get_fedlog):
+ bot.send_message(
+ get_fedlog,
+ "Chat *{}* has joined the federation *{}*".format(
+ chat.title,
+ getfed['fname']),
+ parse_mode="markdown")
message.reply_text(
"This group has joined the federation: {}!".format(
@@ -246,11 +240,10 @@ def leave_fed(bot: Bot, update: Update, _args: List[str]):
if getuser in 'creator' or user.id in SUDO_USERS:
if sql.chat_leave_fed(chat.id):
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if eval(get_fedlog):
- bot.send_message(
- get_fedlog, "Chat *{}* has left the federation *{}*".format(
- chat.title, fed_info['fname']), parse_mode="markdown")
+ if get_fedlog and eval(get_fedlog):
+ bot.send_message(
+ get_fedlog, "Chat *{}* has left the federation *{}*".format(
+ chat.title, fed_info['fname']), parse_mode="markdown")
send_message(
message,
"This group has left the federation {}!".format(
@@ -281,9 +274,13 @@ def user_join_fed(bot: Bot, update: Update, args: List[str]):
user = bot.get_chat(user_id)
elif not message.reply_to_message and not args:
user = message.from_user
- elif not message.reply_to_message and (not args or (
- len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not message.parse_entities(
- [MessageEntity.TEXT_MENTION]))):
+ elif (
+ not message.reply_to_message
+ and len(args) >= 1
+ and not args[0].startswith("@")
+ and not args[0].isdigit()
+ and not message.parse_entities([MessageEntity.TEXT_MENTION])
+ ):
message.reply_text("I cannot extract user from this message")
return
else:
@@ -335,9 +332,13 @@ def user_demote_fed(bot: Bot, update: Update, args: List[str]):
elif not message.reply_to_message and not args:
user = message.from_user
- elif not message.reply_to_message and (not args or (
- len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not message.parse_entities(
- [MessageEntity.TEXT_MENTION]))):
+ elif (
+ not message.reply_to_message
+ and len(args) >= 1
+ and not args[0].startswith("@")
+ and not args[0].isdigit()
+ and not message.parse_entities([MessageEntity.TEXT_MENTION])
+ ):
message.reply_text("I cannot extract user from this message")
return
else:
@@ -371,7 +372,6 @@ def fed_info(bot: Bot, update: Update, args: List[str]):
message = update.effective_message
if args:
fed_id = args[0]
- info = sql.get_fed_info(fed_id)
else:
fed_id = sql.get_fed_id(chat.id)
if not fed_id:
@@ -379,8 +379,7 @@ def fed_info(bot: Bot, update: Update, args: List[str]):
message,
"This group is not in any federation!")
return
- info = sql.get_fed_info(fed_id)
-
+ info = sql.get_fed_info(fed_id)
if is_user_fed_admin(fed_id, user.id) is False:
message.reply_text(
"Only a federation admin can do this!")
@@ -604,21 +603,20 @@ def fed_ban(bot: Bot, update: Update, args: List[str]):
parse_mode="HTML")
# If fedlog is set, then send message, except fedlog is current chat
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if int(get_fedlog) != int(chat.id):
- bot.send_message(get_fedlog,
- "FedBan reason updated"
- "\nFederation: {}"
- "\nFederation Admin: {}"
- "\nUser: {}"
- "\nUser ID: {}"
- "\nReason: {}".format(fed_name,
- mention_html(user.id,
- user.first_name),
- user_target,
- fban_user_id,
- reason),
- parse_mode="HTML")
+ if get_fedlog and int(get_fedlog) != int(chat.id):
+ bot.send_message(get_fedlog,
+ "FedBan reason updated"
+ "\nFederation: {}"
+ "\nFederation Admin: {}"
+ "\nUser: {}"
+ "\nUser ID: {}"
+ "\nReason: {}".format(fed_name,
+ mention_html(user.id,
+ user.first_name),
+ user_target,
+ fban_user_id,
+ reason),
+ parse_mode="HTML")
for fedschat in fed_chats:
try:
# Do not spam all fed chats
@@ -744,21 +742,20 @@ def fed_ban(bot: Bot, update: Update, args: List[str]):
parse_mode="HTML")
# If fedlog is set, then send message, except fedlog is current chat
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if int(get_fedlog) != int(chat.id):
- bot.send_message(get_fedlog,
- "FedBan reason updated"
- "\nFederation: {}"
- "\nFederation Admin: {}"
- "\nUser: {}"
- "\nUser ID: {}"
- "\nReason: {}".format(fed_name,
- mention_html(user.id,
- user.first_name),
- user_target,
- fban_user_id,
- reason),
- parse_mode="HTML")
+ if get_fedlog and int(get_fedlog) != int(chat.id):
+ bot.send_message(get_fedlog,
+ "FedBan reason updated"
+ "\nFederation: {}"
+ "\nFederation Admin: {}"
+ "\nUser: {}"
+ "\nUser ID: {}"
+ "\nReason: {}".format(fed_name,
+ mention_html(user.id,
+ user.first_name),
+ user_target,
+ fban_user_id,
+ reason),
+ parse_mode="HTML")
chats_in_fed = 0
for fedschat in fed_chats:
chats_in_fed += 1
@@ -925,19 +922,18 @@ def unfban(bot: Bot, update: Update, args: List[str]):
parse_mode="HTML")
# If fedlog is set, then send message, except fedlog is current chat
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if int(get_fedlog) != int(chat.id):
- bot.send_message(get_fedlog,
- "Un-FedBan"
- "\nFederation: {}"
- "\nFederation Admin: {}"
- "\nUser: {}"
- "\nUser ID: {}".format(info['fname'],
- mention_html(user.id,
- user.first_name),
- user_target,
- fban_user_id),
- parse_mode="HTML")
+ if get_fedlog and int(get_fedlog) != int(chat.id):
+ bot.send_message(get_fedlog,
+ "Un-FedBan"
+ "\nFederation: {}"
+ "\nFederation Admin: {}"
+ "\nUser: {}"
+ "\nUser ID: {}".format(info['fname'],
+ mention_html(user.id,
+ user.first_name),
+ user_target,
+ fban_user_id),
+ parse_mode="HTML")
unfbanned_in_chats = 0
for fedchats in chat_list:
unfbanned_in_chats += 1
@@ -974,8 +970,6 @@ def unfban(bot: Bot, update: Update, args: List[str]):
return
except BaseException as e:
print(e)
- pass
-
# UnFban for fed subscriber
subscriber = list(sql.get_subscriber(fed_id))
if len(subscriber) != 0:
@@ -1070,14 +1064,13 @@ def set_frules(bot: Bot, update: Update, args: List[str]):
rules = sql.get_fed_info(fed_id)['frules']
getfed = sql.get_fed_info(fed_id)
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if eval(get_fedlog):
- bot.send_message(
- get_fedlog,
- "*{}* has updated federation rules for fed *{}*".format(
- user.first_name,
- getfed['fname']),
- parse_mode="markdown")
+ if get_fedlog and eval(get_fedlog):
+ bot.send_message(
+ get_fedlog,
+ "*{}* has updated federation rules for fed *{}*".format(
+ user.first_name,
+ getfed['fname']),
+ parse_mode="markdown")
message.reply_text(
f"Rules have been changed to :\n{rules}!")
else:
@@ -1538,13 +1531,12 @@ def fed_import_bans(bot: Bot, update: Update, chat_data):
if failed >= 1:
text += " {} Failed to import.".format(failed)
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if eval(get_fedlog):
- teks = "Fed *{}* has successfully imported data. {} banned.".format(
- getfed['fname'], success)
- if failed >= 1:
- teks += " {} Failed to import.".format(failed)
- bot.send_message(get_fedlog, teks, parse_mode="markdown")
+ if get_fedlog and eval(get_fedlog):
+ teks = "Fed *{}* has successfully imported data. {} banned.".format(
+ getfed['fname'], success)
+ if failed >= 1:
+ teks += " {} Failed to import.".format(failed)
+ bot.send_message(get_fedlog, teks, parse_mode="markdown")
elif fileformat == 'csv':
multi_fed_id = []
multi_import_userid = []
@@ -1612,13 +1604,12 @@ def fed_import_bans(bot: Bot, update: Update, chat_data):
if failed >= 1:
text += " {} Failed to import.".format(failed)
get_fedlog = sql.get_fed_log(fed_id)
- if get_fedlog:
- if eval(get_fedlog):
- teks = "Fed *{}* has successfully imported data. {} banned.".format(
- getfed['fname'], success)
- if failed >= 1:
- teks += " {} Failed to import.".format(failed)
- bot.send_message(get_fedlog, teks, parse_mode="markdown")
+ if get_fedlog and eval(get_fedlog):
+ teks = "Fed *{}* has successfully imported data. {} banned.".format(
+ getfed['fname'], success)
+ if failed >= 1:
+ teks += " {} Failed to import.".format(failed)
+ bot.send_message(get_fedlog, teks, parse_mode="markdown")
else:
send_message(
message,
@@ -1647,14 +1638,10 @@ def del_fed_button(_bot, update):
@run_async
def fed_stat_user(bot, update, args):
message = update.effective_message
- if args:
- if args[0].isdigit():
- user_id = args[0]
- else:
- user_id = extract_user(message, args)
+ if args and args[0].isdigit():
+ user_id = args[0]
else:
user_id = extract_user(message, args)
-
if user_id:
if len(args) == 2 and args[0].isdigit():
fed_id = args[1]
@@ -1855,11 +1842,10 @@ def subs_feds(bot, update, args):
getfed['fname']),
parse_mode="markdown")
get_fedlog = sql.get_fed_log(args[0])
- if get_fedlog:
- if int(get_fedlog) != int(chat.id):
- bot.send_message(
- get_fedlog, "Federation `{}` has subscribe the federation `{}`".format(
- fedinfo['fname'], getfed['fname']), parse_mode="markdown")
+ if get_fedlog and int(get_fedlog) != int(chat.id):
+ bot.send_message(
+ get_fedlog, "Federation `{}` has subscribe the federation `{}`".format(
+ fedinfo['fname'], getfed['fname']), parse_mode="markdown")
else:
send_message(
message,
@@ -1907,14 +1893,13 @@ def unsubs_feds(bot, update, args):
getfed['fname']),
parse_mode="markdown")
get_fedlog = sql.get_fed_log(args[0])
- if get_fedlog:
- if int(get_fedlog) != int(chat.id):
- bot.send_message(
- get_fedlog,
- "Federation `{}` has unsubscribe fed `{}`.".format(
- fedinfo['fname'],
- getfed['fname']),
- parse_mode="markdown")
+ if get_fedlog and int(get_fedlog) != int(chat.id):
+ bot.send_message(
+ get_fedlog,
+ "Federation `{}` has unsubscribe fed `{}`.".format(
+ fedinfo['fname'],
+ getfed['fname']),
+ parse_mode="markdown")
else:
send_message(
message,
@@ -1953,7 +1938,7 @@ def get_myfedsubs(bot, update, args):
except BaseException:
getmy = []
- if len(getmy) == 0:
+ if not getmy:
send_message(
message,
"Federation `{}` is not subscribing any federation.".format(
@@ -1987,10 +1972,7 @@ def is_user_fed_admin(fed_id, user_id):
fed_admins = sql.all_fed_users(fed_id)
if not fed_admins:
return False
- if int(user_id) in fed_admins or int(user_id) == OWNER_ID:
- return True
- else:
- return False
+ return int(user_id) in fed_admins or int(user_id) == OWNER_ID
def is_user_fed_owner(fed_id, user_id):
@@ -2001,10 +1983,7 @@ def is_user_fed_owner(fed_id, user_id):
if getfedowner is None or getfedowner is False:
return False
getfedowner = getfedowner['owner']
- if str(user_id) == getfedowner or int(user_id) == OWNER_ID:
- return True
- else:
- return False
+ return str(user_id) == getfedowner or int(user_id) == OWNER_ID
@run_async
@@ -2057,18 +2036,14 @@ def __user_info__(user_id, chat_id):
# Temporary data
def put_chat(chat_id, value, chat_data):
# print(chat_data)
- if not value:
- status = False
- else:
- status = True
+ status = False if not value else True
chat_data[chat_id] = {'federation': {"status": status, "value": value}}
def get_chat(chat_id, chat_data):
# print(chat_data)
try:
- value = chat_data[chat_id]['federation']
- return value
+ return chat_data[chat_id]['federation']
except KeyError:
return {"status": False, "value": False}
diff --git a/lynda/modules/fun.py b/lynda/modules/fun.py
index a56aa70c..b3feb9eb 100644
--- a/lynda/modules/fun.py
+++ b/lynda/modules/fun.py
@@ -90,12 +90,9 @@ def vapor(_bot: Bot, update: Update, args: List[str]):
else:
noreply = True
data = message.text.split(None, 1)[1]
- elif message.reply_to_message:
+ else:
noreply = False
data = message.reply_to_message.text
- else:
- data = ''
-
reply_text = str(data).translate(WIDE_MAP)
if noreply:
message.reply_text(reply_text)
@@ -172,11 +169,7 @@ def zalgotext(_bot: Bot, update: Update):
@run_async
def forbesify(_bot: Bot, update: Update):
message = update.effective_message
- if message.reply_to_message:
- data = message.reply_to_message.text
- else:
- data = ''
-
+ data = message.reply_to_message.text if message.reply_to_message else ''
data = data.lower()
accidentals = ['VB', 'VBD', 'VBG', 'VBN']
reply_text = data.split()
@@ -259,8 +252,7 @@ def shout(_bot: Bot, update: Update, args):
return
text = " ".join(args)
- result = []
- result.append(' '.join(s for s in text))
+ result = [' '.join(iter(text))]
for pos, symbol in enumerate(text[1:]):
result.append(symbol + ' ' + ' ' * pos + symbol)
result = list("\n".join(result))
@@ -285,10 +277,7 @@ def copypasta(_bot: Bot, update: Update):
elif c.lower() == b_char:
reply_text += "🅱️"
else:
- if bool(random.getrandbits(1)):
- reply_text += c.upper()
- else:
- reply_text += c.lower()
+ reply_text += c.upper() if bool(random.getrandbits(1)) else c.lower()
reply_text += random.choice(fun_strings.emojis)
message.reply_to_message.reply_text(reply_text)
diff --git a/lynda/modules/global_bans.py b/lynda/modules/global_bans.py
index 65bac887..44b64fd0 100644
--- a/lynda/modules/global_bans.py
+++ b/lynda/modules/global_bans.py
@@ -299,9 +299,7 @@ def ungban(bot: Bot, update: Update, args: List[str]):
ungbanned_chats += 1
except BadRequest as excp:
- if excp.message in UNGBAN_ERRORS:
- pass
- else:
+ if excp.message not in UNGBAN_ERRORS:
message.reply_text(f"Could not un-gban due to: {excp.message}")
if GBAN_LOGS:
bot.send_message(
@@ -372,13 +370,9 @@ def check_and_ban(update, user_id, should_message=True):
if should_message:
message.reply_markdown(
"**This user is detected as spam bot by SpamWatch and have been removed!**\n\nPlease visit @SpamWatchSupport to appeal!")
- return
- else:
- return
+ return
except Exception as e:
print(e)
- pass
-
if sql.is_user_gbanned(user_id):
update.effective_chat.kick_member(user_id)
if should_message:
@@ -391,31 +385,33 @@ def check_and_ban(update, user_id, should_message=True):
@run_async
def enforce_gban(bot: Bot, update: Update):
# Not using @restrict handler to avoid spamming - just ignore if cant gban.
- if sql.does_chat_gban(
- update.effective_chat.id) and update.effective_chat.get_member(
- bot.id).can_restrict_members:
- user = update.effective_user
- chat = update.effective_chat
- msg = update.effective_message
+ if (
+ not sql.does_chat_gban(update.effective_chat.id)
+ or not update.effective_chat.get_member(bot.id).can_restrict_members
+ ):
+ return
+ user = update.effective_user
+ chat = update.effective_chat
+ msg = update.effective_message
- if user and not is_user_admin(chat, user.id):
- check_and_ban(update, user.id)
+ if user and not is_user_admin(chat, user.id):
+ check_and_ban(update, user.id)
- if msg.new_chat_members:
- new_members = update.effective_message.new_chat_members
- for mem in new_members:
- check_and_ban(update, mem.id)
+ if msg.new_chat_members:
+ new_members = update.effective_message.new_chat_members
+ for mem in new_members:
+ check_and_ban(update, mem.id)
- if msg.reply_to_message:
- user = msg.reply_to_message.from_user
- if user and not is_user_admin(chat, user.id):
- check_and_ban(update, user.id, should_message=False)
+ if msg.reply_to_message:
+ user = msg.reply_to_message.from_user
+ if user and not is_user_admin(chat, user.id):
+ check_and_ban(update, user.id, should_message=False)
@run_async
@user_admin
def gbanstat(_bot: Bot, update: Update, args: List[str]):
- if len(args) > 0:
+ if args:
if args[0].lower() in ["on", "yes"]:
sql.enable_gbans(update.effective_chat.id)
update.effective_message.reply_text(
diff --git a/lynda/modules/gtranslator.py b/lynda/modules/gtranslator.py
index 30fb9226..2817e89f 100644
--- a/lynda/modules/gtranslator.py
+++ b/lynda/modules/gtranslator.py
@@ -10,10 +10,7 @@
@run_async
def totranslate(_bot: Bot, update: Update):
msg = update.effective_message
- problem_lang_code = []
- for key in LANGUAGES:
- if "-" in key:
- problem_lang_code.append(key)
+ problem_lang_code = [key for key in LANGUAGES if "-" in key]
try:
if msg.reply_to_message and msg.reply_to_message.text:
diff --git a/lynda/modules/helper_funcs/chat_status.py b/lynda/modules/helper_funcs/chat_status.py
index 454e8859..2241537e 100644
--- a/lynda/modules/helper_funcs/chat_status.py
+++ b/lynda/modules/helper_funcs/chat_status.py
@@ -171,8 +171,6 @@ def is_not_admin(bot: Bot, update: Update, *args, **kwargs):
if user and not is_user_admin(chat, user.id):
return func(bot, update, *args, **kwargs)
- elif not user:
- pass
return is_not_admin
@@ -286,13 +284,13 @@ def connected_status(bot: Bot, update: Update, *args, **kwargs):
if conn:
chat = dispatcher.bot.getChat(conn)
update.__setattr__("_effective_chat", chat)
- return func(bot, update, *args, **kwargs)
else:
if update.effective_message.chat.type == "private":
update.effective_message.reply_text("Send /connect in a group that you and I have in common first.")
return connected_status
- return func(bot, update, *args, **kwargs)
+
+ return func(bot, update, *args, **kwargs)
return connected_status
diff --git a/lynda/modules/helper_funcs/extraction.py b/lynda/modules/helper_funcs/extraction.py
index ddbc68d9..577770e8 100644
--- a/lynda/modules/helper_funcs/extraction.py
+++ b/lynda/modules/helper_funcs/extraction.py
@@ -34,11 +34,7 @@ def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int],
text = ""
entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
- if len(entities) > 0:
- ent = entities[0]
- else:
- ent = None
-
+ ent = entities[0] if entities else None
# if entity offset matches (command end/text start) then all good
if entities and ent and ent.offset == len(message.text) - len(text_to_parse):
ent = entities[0]
@@ -102,11 +98,7 @@ def extract_unt_fedban(message: Message, args: List[str]) -> (Optional[int], Opt
text = ""
entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
- if len(entities) > 0:
- ent = entities[0]
- else:
- ent = None
-
+ ent = entities[0] if entities else None
# if entity offset matches (command end/text start) then all good
if entities and ent and ent.offset == len(message.text) - len(text_to_parse):
ent = entities[0]
diff --git a/lynda/modules/helper_funcs/handlers.py b/lynda/modules/helper_funcs/handlers.py
index 34f467bc..b012df2c 100644
--- a/lynda/modules/helper_funcs/handlers.py
+++ b/lynda/modules/helper_funcs/handlers.py
@@ -4,10 +4,7 @@
import lynda.modules.sql.blacklistusers_sql as sql
from lynda import ALLOW_EXCL
-if ALLOW_EXCL:
- CMD_STARTERS = ('/', '!')
-else:
- CMD_STARTERS = ('/',)
+CMD_STARTERS = ('/', '!') if ALLOW_EXCL else ('/', )
class CustomCommandHandler(CommandHandler):
diff --git a/lynda/modules/helper_funcs/msg_types.py b/lynda/modules/helper_funcs/msg_types.py
index 19ad0796..10c810cb 100644
--- a/lynda/modules/helper_funcs/msg_types.py
+++ b/lynda/modules/helper_funcs/msg_types.py
@@ -31,22 +31,14 @@ def get_note_type(msg: Message):
offset = len(args[2]) - len(raw_text) # set correct offset relative to command + notename
text, buttons = button_markdown_parser(args[2], entities=msg.parse_entities() or msg.parse_caption_entities(),
offset=offset)
- if buttons:
- data_type = Types.BUTTON_TEXT
- else:
- data_type = Types.TEXT
-
+ data_type = Types.BUTTON_TEXT if buttons else Types.TEXT
elif msg.reply_to_message:
entities = msg.reply_to_message.parse_entities()
msgtext = msg.reply_to_message.text or msg.reply_to_message.caption
if len(args) >= 2 and msg.reply_to_message.text: # not caption, text
text, buttons = button_markdown_parser(msgtext,
entities=entities)
- if buttons:
- data_type = Types.BUTTON_TEXT
- else:
- data_type = Types.TEXT
-
+ data_type = Types.BUTTON_TEXT if buttons else Types.TEXT
elif msg.reply_to_message.sticker:
content = msg.reply_to_message.sticker.file_id
data_type = Types.STICKER
@@ -92,11 +84,7 @@ def get_welcome_type(msg: Message):
if len(args) >= 2:
offset = len(args[1]) - len(msg.text) # set correct offset relative to command + notename
text, buttons = button_markdown_parser(args[1], entities=msg.parse_entities(), offset=offset)
- if buttons:
- data_type = Types.BUTTON_TEXT
- else:
- data_type = Types.TEXT
-
+ data_type = Types.BUTTON_TEXT if buttons else Types.TEXT
elif msg.reply_to_message and msg.reply_to_message.sticker:
content = msg.reply_to_message.sticker.file_id
text = msg.reply_to_message.caption
diff --git a/lynda/modules/helper_funcs/string_handling.py b/lynda/modules/helper_funcs/string_handling.py
index b7cec776..8044a95e 100644
--- a/lynda/modules/helper_funcs/string_handling.py
+++ b/lynda/modules/helper_funcs/string_handling.py
@@ -154,11 +154,7 @@ def escape_invalid_curly_brackets(text: str, valids: List[str]) -> str:
new_text += "{{{{"
continue
else:
- success = False
- for v in valids:
- if text[idx:].startswith('{' + v + '}'):
- success = True
- break
+ success = any(text[idx:].startswith('{' + v + '}') for v in valids)
if success:
new_text += text[idx: idx + len(v) + 2]
idx += len(v) + 2
@@ -187,41 +183,38 @@ def escape_invalid_curly_brackets(text: str, valids: List[str]) -> str:
def split_quotes(text: str) -> List:
- if any(text.startswith(char) for char in START_CHAR):
- counter = 1 # ignore first char -> is some kind of quote
- while counter < len(text):
- if text[counter] == "\\":
- counter += 1
- elif text[counter] == text[0] or (text[0] == SMART_OPEN and text[counter] == SMART_CLOSE):
- break
+ if not any(text.startswith(char) for char in START_CHAR):
+ return text.split(None, 1)
+ counter = 1 # ignore first char -> is some kind of quote
+ while counter < len(text):
+ if text[counter] == "\\":
counter += 1
- else:
- return text.split(None, 1)
-
- # 1 to avoid starting quote, and counter is exclusive so avoids ending
- key = remove_escapes(text[1:counter].strip())
- # index will be in range, or `else` would have been executed and returned
- rest = text[counter + 1:].strip()
- if not key:
- key = text[0] + text[0]
- return list(filter(None, [key, rest]))
+ elif text[counter] == text[0] or (text[0] == SMART_OPEN and text[counter] == SMART_CLOSE):
+ break
+ counter += 1
else:
return text.split(None, 1)
+ # 1 to avoid starting quote, and counter is exclusive so avoids ending
+ key = remove_escapes(text[1:counter].strip())
+ # index will be in range, or `else` would have been executed and returned
+ rest = text[counter + 1:].strip()
+ if not key:
+ key = text[0] + text[0]
+ return list(filter(None, [key, rest]))
+
def remove_escapes(text: str) -> str:
- counter = 0
res = ""
is_escaped = False
- while counter < len(text):
+ for item in text:
if is_escaped:
- res += text[counter]
+ res += item
is_escaped = False
- elif text[counter] == "\\":
+ elif item == "\\":
is_escaped = True
else:
- res += text[counter]
- counter += 1
+ res += item
return res
diff --git a/lynda/modules/helper_funcs/telethn/chatstatus.py b/lynda/modules/helper_funcs/telethn/chatstatus.py
index d64e87cc..038f0965 100644
--- a/lynda/modules/helper_funcs/telethn/chatstatus.py
+++ b/lynda/modules/helper_funcs/telethn/chatstatus.py
@@ -3,56 +3,50 @@
from lynda.modules.helper_funcs.telethn import IMMUNE_USERS, telethn
async def user_is_ban_protected(user_id: int, message):
- status = False
if message.is_private or user_id in (IMMUNE_USERS):
return True
- async for user in telethn.iter_participants(message.chat_id, filter=ChannelParticipantsAdmins):
- if user_id == user.id:
- status = True
- break
- return status
+ return any(
+ user_id == user.id
+ for user in telethn.iter_participants(
+ message.chat_id, filter=ChannelParticipantsAdmins
+ )
+ )
async def user_is_admin(user_id: int, message):
- status = False
if message.is_private:
return True
- async for user in telethn.iter_participants(message.chat_id, filter=ChannelParticipantsAdmins):
- if user_id == user.id or user_id in IMMUNE_USERS:
- status = True
- break
- return status
+ return any(
+ user_id == user.id or user_id in IMMUNE_USERS
+ for user in telethn.iter_participants(
+ message.chat_id, filter=ChannelParticipantsAdmins
+ )
+ )
async def is_user_admin(user_id: int, chat_id):
- status = False
- async for user in telethn.iter_participants(chat_id, filter=ChannelParticipantsAdmins):
- if user_id == user.id or user_id in IMMUNE_USERS:
- status = True
- break
- return status
+ return any(
+ user_id == user.id or user_id in IMMUNE_USERS
+ for user in telethn.iter_participants(
+ chat_id, filter=ChannelParticipantsAdmins
+ )
+ )
async def haruka_is_admin(chat_id: int):
- status = False
haruka = await telethn.get_me()
- async for user in telethn.iter_participants(chat_id,
- filter=ChannelParticipantsAdmins):
- if haruka.id == user.id:
- status = True
- break
- return status
+ return any(
+ haruka.id == user.id
+ for user in telethn.iter_participants(
+ chat_id, filter=ChannelParticipantsAdmins
+ )
+ )
async def is_user_in_chat(chat_id: int, user_id: int):
- status = False
- async for user in telethn.iter_participants(chat_id):
- if user_id == user.id:
- status = True
- break
- return status
+ return any(user_id == user.id for user in telethn.iter_participants(chat_id))
async def can_change_info(message):
diff --git a/lynda/modules/lastfm.py b/lynda/modules/lastfm.py
index 81d63ead..bc1bb33a 100644
--- a/lynda/modules/lastfm.py
+++ b/lynda/modules/lastfm.py
@@ -45,7 +45,7 @@ def last_fm(_bot: Bot, update: Update):
base_url = "http://ws.audioscrobbler.com/2.0"
res = requests.get(
f"{base_url}?method=user.getrecenttracks&limit=3&extended=1&user={username}&api_key={LASTFM_API_KEY}&format=json")
- if not res.status_code == 200:
+ if res.status_code != 200:
msg.reply_text(
"Hmm... something went wrong.\nPlease ensure that you've set the correct username!")
return
diff --git a/lynda/modules/locks.py b/lynda/modules/locks.py
index cb92d27d..3f11283e 100644
--- a/lynda/modules/locks.py
+++ b/lynda/modules/locks.py
@@ -84,8 +84,6 @@ def restr_members(
other=False,
previews=False):
for mem in members:
- if mem.user in SUDO_USERS or mem.user in DEV_USERS:
- pass
try:
bot.restrict_chat_member(chat_id, mem.user,
can_send_messages=messages,
@@ -129,11 +127,11 @@ def locktypes(_bot: Bot, update: Update):
@loggable
def lock(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat
- user = update.effective_user
message = update.effective_message
if can_delete(chat, bot.id):
if len(args) >= 1:
+ user = update.effective_user
if args[0] in LOCK_TYPES:
sql.update_lock(chat.id, args[0], locked=True)
message.reply_text(
@@ -188,11 +186,11 @@ def lock(bot: Bot, update: Update, args: List[str]) -> str:
@loggable
def unlock(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat
- user = update.effective_user
message = update.effective_message
if is_user_admin(chat, message.from_user.id):
if len(args) >= 1:
+ user = update.effective_user
if args[0] in LOCK_TYPES:
sql.update_lock(chat.id, args[0], locked=False)
message.reply_text(f"Unlocked {args[0]} for everyone!")
@@ -267,9 +265,7 @@ def del_lockables(bot: Bot, update: Update):
try:
message.delete()
except BadRequest as excp:
- if excp.message == "Message to delete not found":
- pass
- else:
+ if excp.message != "Message to delete not found":
LOGGER.exception("ERROR in lockables")
break
@@ -289,9 +285,7 @@ def rest_handler(bot: Bot, update: Update):
try:
msg.delete()
except BadRequest as excp:
- if excp.message == "Message to delete not found":
- pass
- else:
+ if excp.message != "Message to delete not found":
LOGGER.exception("ERROR in restrictions")
break
diff --git a/lynda/modules/log_channel.py b/lynda/modules/log_channel.py
index 8ffb6dc9..0a1ac37e 100644
--- a/lynda/modules/log_channel.py
+++ b/lynda/modules/log_channel.py
@@ -41,12 +41,6 @@ def log_action(
log_chat = sql.get_chat_log_channel(chat.id)
if log_chat:
send_log(bot, log_chat, chat.id, result)
- elif result == "" or not result:
- pass
- else:
- LOGGER.warning(
- "%s was set as loggable, but had no return statement.", func)
-
return result
return log_action
@@ -69,12 +63,6 @@ def glog_action(bot: Bot, update: Update, *args, **kwargs):
log_chat = str(GBAN_LOGS)
if log_chat:
send_log(bot, log_chat, chat.id, result)
- elif result == "" or not result:
- pass
- else:
- LOGGER.warning(
- "%s was set as loggable to gbanlogs, but had no return statement.", func)
-
return result
return glog_action
@@ -136,9 +124,7 @@ def setlog(bot: Bot, update: Update):
try:
message.delete()
except BadRequest as excp:
- if excp.message == "Message to delete not found":
- pass
- else:
+ if excp.message != "Message to delete not found":
LOGGER.exception(
"Error deleting message in log channel. Should work anyway though.")
diff --git a/lynda/modules/misc.py b/lynda/modules/misc.py
index d447ff0a..fda7aeb7 100644
--- a/lynda/modules/misc.py
+++ b/lynda/modules/misc.py
@@ -42,7 +42,6 @@
@run_async
def get_id(bot: Bot, update: Update, args: List[str]):
message = update.effective_message
- chat = update.effective_chat
msg = update.effective_message
user_id = extract_user(msg, args)
@@ -68,6 +67,7 @@ def get_id(bot: Bot, update: Update, args: List[str]):
else:
+ chat = update.effective_chat
if chat.type == "private":
msg.reply_text(f"Your id is {chat.id}.",
parse_mode=ParseMode.HTML)
@@ -101,9 +101,13 @@ def info(bot: Bot, update: Update, args: List[str]):
elif not message.reply_to_message and not args:
user = message.from_user
- elif not message.reply_to_message and (not args or (
- len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not message.parse_entities(
- [MessageEntity.TEXT_MENTION]))):
+ elif (
+ not message.reply_to_message
+ and len(args) >= 1
+ and not args[0].startswith("@")
+ and not args[0].isdigit()
+ and not message.parse_entities([MessageEntity.TEXT_MENTION])
+ ):
message.reply_text("I can't extract a user from this.")
return
diff --git a/lynda/modules/modules.py b/lynda/modules/modules.py
index 49173bd0..9ff40559 100644
--- a/lynda/modules/modules.py
+++ b/lynda/modules/modules.py
@@ -35,7 +35,7 @@ def load(_bot: Bot, update: Update):
if not hasattr(imported_module, "__mod_name__"):
imported_module.__mod_name__ = imported_module.__name__
- if not imported_module.__mod_name__.lower() in IMPORTED:
+ if imported_module.__mod_name__.lower() not in IMPORTED:
IMPORTED[imported_module.__mod_name__.lower()] = imported_module
else:
load_messasge.edit_text("Module already loaded.")
diff --git a/lynda/modules/muting.py b/lynda/modules/muting.py
index 94ec9184..bbaea760 100644
--- a/lynda/modules/muting.py
+++ b/lynda/modules/muting.py
@@ -89,7 +89,6 @@ def mute(bot: Bot, update: Update, args: List[str]) -> str:
@loggable
def unmute(bot: Bot, update: Update, args: List[str]) -> str:
chat = update.effective_chat
- user = update.effective_user
message = update.effective_message
user_id = extract_user(message, args)
@@ -100,7 +99,12 @@ def unmute(bot: Bot, update: Update, args: List[str]) -> str:
member = chat.get_member(int(user_id))
- if member.status != 'kicked' and member.status != 'left':
+ if member.status in ['kicked', 'left']:
+ message.reply_text(
+ "This user isn't even in the chat, unmuting them won't make them talk more than they "
+ "already do!")
+
+ else:
if (member.can_send_messages
and member.can_send_media_messages
and member.can_send_other_messages
@@ -116,16 +120,12 @@ def unmute(bot: Bot, update: Update, args: List[str]) -> str:
chat.id,
f"I shall allow {html.escape(member.user.first_name)} to text!",
parse_mode=ParseMode.HTML)
+ user = update.effective_user
return (
f"{html.escape(chat.title)}:\n"
f"#UNMUTE\n"
f"Admin: {mention_html(user.id, user.first_name)}\n"
f"User: {mention_html(member.user.id, member.user.first_name)}")
- else:
- message.reply_text(
- "This user isn't even in the chat, unmuting them won't make them talk more than they "
- "already do!")
-
return ""
@@ -157,11 +157,7 @@ def temp_mute(bot: Bot, update: Update, args: List[str]) -> str:
split_reason = reason.split(None, 1)
time_val = split_reason[0].lower()
- if len(split_reason) > 1:
- reason = split_reason[1]
- else:
- reason = ""
-
+ reason = split_reason[1] if len(split_reason) > 1 else ""
mutetime = extract_time(message, time_val)
if not mutetime:
diff --git a/lynda/modules/notes.py b/lynda/modules/notes.py
index 27d6a1fd..f78550ff 100644
--- a/lynda/modules/notes.py
+++ b/lynda/modules/notes.py
@@ -205,10 +205,10 @@ def save(_bot: Bot, update: Update):
@run_async
@user_admin
def clear(_bot: Bot, update: Update, args: List[str]):
- chat_id = update.effective_chat.id
if len(args) >= 1:
notename = args[0]
+ chat_id = update.effective_chat.id
if sql.rm_note(chat_id, notename):
update.effective_message.reply_text("Successfully removed note.")
else:
diff --git a/lynda/modules/ping.py b/lynda/modules/ping.py
index 011b77bb..8d576dd4 100644
--- a/lynda/modules/ping.py
+++ b/lynda/modules/ping.py
@@ -24,10 +24,7 @@ def get_readable_time(seconds: int) -> str:
while count < 4:
count += 1
- if count < 3:
- remainder, result = divmod(seconds, 60)
- else:
- remainder, result = divmod(seconds, 24)
+ remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
@@ -57,7 +54,7 @@ def ping_func(to_ping: List[str]) -> List[str]:
pinged_site = f"{each_ping}"
- if each_ping == "Kaizoku" or each_ping == "Kayo":
+ if each_ping in ["Kaizoku", "Kayo"]:
pinged_site = f'{each_ping}'
ping_time = f"{ping_time} (Status: {r.status_code})"
diff --git a/lynda/modules/reporting.py b/lynda/modules/reporting.py
index c5fc128a..d50486f2 100644
--- a/lynda/modules/reporting.py
+++ b/lynda/modules/reporting.py
@@ -118,7 +118,7 @@ def report(bot: Bot, update: Update) -> str:
if sql.user_should_report(admin.user.id):
try:
- if not chat.type == Chat.SUPERGROUP:
+ if chat.type != Chat.SUPERGROUP:
bot.send_message(
admin.user.id, msg + link, parse_mode=ParseMode.HTML)
diff --git a/lynda/modules/rss.py b/lynda/modules/rss.py
index 9e15b2b5..6ce53455 100644
--- a/lynda/modules/rss.py
+++ b/lynda/modules/rss.py
@@ -11,8 +11,6 @@
def show_url(bot, update, args):
- tg_chat_id = str(update.effective_chat.id)
-
if len(args) >= 1:
tg_feed_link = args[0]
link_processed = parse(tg_feed_link)
@@ -34,6 +32,8 @@ def show_url(bot, update, args):
feed_description,
html.escape(feed_link))
+ tg_chat_id = str(update.effective_chat.id)
+
if len(link_processed.entries) >= 1:
entry_title = link_processed.entries[0].get(
"title", default="Unknown")
@@ -103,8 +103,6 @@ def list_urls(bot, update):
def add_url(_bot, update, args):
if len(args) >= 1:
- tg_chat_id = str(update.effective_chat.id)
-
tg_feed_link = args[0]
link_processed = parse(tg_feed_link)
@@ -116,6 +114,8 @@ def add_url(_bot, update, args):
else:
tg_old_entry_link = ""
+ tg_chat_id = str(update.effective_chat.id)
+
# gather the row which contains exactly that telegram group ID and
# link for later comparison
row = sql.check_url_availability(tg_chat_id, tg_feed_link)
@@ -140,10 +140,10 @@ def add_url(_bot, update, args):
@user_admin
def remove_url(_bot, update, args):
if len(args) >= 1:
- tg_chat_id = str(update.effective_chat.id)
tg_feed_link = args[0]
link_processed = parse(tg_feed_link)
if link_processed.bozo == 0:
+ tg_chat_id = str(update.effective_chat.id)
user_data = sql.check_url_availability(tg_chat_id, tg_feed_link)
if user_data:
sql.remove_url(tg_chat_id, tg_feed_link)
@@ -183,9 +183,6 @@ def rss_update(bot, _job):
# check if there's any new entries queued from the last check
if new_entry_links:
sql.update_url(row_id, new_entry_links)
- else:
- pass
-
if len(new_entry_links) < 5:
# this loop sends every new update to each user from each group
# based on the DB entries
@@ -254,8 +251,6 @@ def rss_set(_bot, _job):
# check if there's any new entries queued from the last check
if new_entry_links:
sql.update_url(row_id, new_entry_links)
- else:
- pass
__help__ = """
diff --git a/lynda/modules/rules.py b/lynda/modules/rules.py
index afdc8b9b..f52f84e9 100644
--- a/lynda/modules/rules.py
+++ b/lynda/modules/rules.py
@@ -61,7 +61,6 @@ def send_rules(update, chat_id, from_pm=False):
@run_async
@user_admin
def set_rules(_bot: Bot, update: Update):
- chat_id = update.effective_chat.id
msg = update.effective_message # type: Optional[Message]
raw_text = msg.text
# use python's maxsplit to separate cmd and args
@@ -73,6 +72,7 @@ def set_rules(_bot: Bot, update: Update):
markdown_rules = markdown_parser(
txt, entities=msg.parse_entities(), offset=offset)
+ chat_id = update.effective_chat.id
sql.set_rules(chat_id, markdown_rules)
update.effective_message.reply_text(
"Successfully set rules for this group.")
diff --git a/lynda/modules/sed.py b/lynda/modules/sed.py
index 5e9c797e..b1e341d2 100644
--- a/lynda/modules/sed.py
+++ b/lynda/modules/sed.py
@@ -12,43 +12,48 @@
def separate_sed(sed_string):
- if len(sed_string) >= 3 and sed_string[1] in DELIMITERS and sed_string.count(
- sed_string[1]) >= 2:
- delim = sed_string[1]
- start = counter = 2
- while counter < len(sed_string):
- if sed_string[counter] == "\\":
- counter += 1
-
- elif sed_string[counter] == delim:
- replace = sed_string[start:counter]
- counter += 1
- start = counter
- break
+ if (
+ len(sed_string) < 3
+ or sed_string[1] not in DELIMITERS
+ or sed_string.count(sed_string[1]) < 2
+ ):
+ return
+
+ delim = sed_string[1]
+ start = counter = 2
+ while counter < len(sed_string):
+ if sed_string[counter] == "\\":
+ counter += 1
+ elif sed_string[counter] == delim:
+ replace = sed_string[start:counter]
counter += 1
+ start = counter
+ break
- else:
- return None
+ counter += 1
- while counter < len(sed_string):
- if sed_string[counter] == "\\" and counter + \
- 1 < len(sed_string) and sed_string[counter + 1] == delim:
- sed_string = sed_string[:counter] + sed_string[counter + 1:]
+ else:
+ return None
- elif sed_string[counter] == delim:
- replace_with = sed_string[start:counter]
- counter += 1
- break
+ while counter < len(sed_string):
+ if sed_string[counter] == "\\" and counter + \
+ 1 < len(sed_string) and sed_string[counter + 1] == delim:
+ sed_string = sed_string[:counter] + sed_string[counter + 1:]
+ elif sed_string[counter] == delim:
+ replace_with = sed_string[start:counter]
counter += 1
- else:
- return replace, sed_string[start:], ""
+ break
+
+ counter += 1
+ else:
+ return replace, sed_string[start:], ""
- flags = ""
- if counter < len(sed_string):
- flags = sed_string[counter:]
- return replace, replace_with, flags.lower()
+ flags = ""
+ if counter < len(sed_string):
+ flags = sed_string[counter:]
+ return replace, replace_with, flags.lower()
@run_async
diff --git a/lynda/modules/special.py b/lynda/modules/special.py
index 364df3ab..402e094c 100644
--- a/lynda/modules/special.py
+++ b/lynda/modules/special.py
@@ -25,12 +25,8 @@
@run_async
def banall(bot: Bot, update: Update, args: List[int]):
- if args:
- chat_id = str(args[0])
- all_mems = sql.get_chat_members(chat_id)
- else:
- chat_id = str(update.effective_chat.id)
- all_mems = sql.get_chat_members(chat_id)
+ chat_id = str(args[0]) if args else str(update.effective_chat.id)
+ all_mems = sql.get_chat_members(chat_id)
for mems in all_mems:
try:
bot.kick_chat_member(chat_id, mems.user)
diff --git a/lynda/modules/sql/chatbot_sql.py b/lynda/modules/sql/chatbot_sql.py
index 65f91527..cd4a8aa5 100644
--- a/lynda/modules/sql/chatbot_sql.py
+++ b/lynda/modules/sql/chatbot_sql.py
@@ -25,10 +25,7 @@ def __init__(self, chat_id, ses_id, expires):
def is_chat(chat_id):
try:
chat = SESSION.query(ChatbotChats).get(str(chat_id))
- if chat:
- return True
- else:
- return False
+ return bool(chat)
finally:
SESSION.close()
diff --git a/lynda/modules/sql/cleaner_sql.py b/lynda/modules/sql/cleaner_sql.py
index 1f4f9095..54cda6c5 100644
--- a/lynda/modules/sql/cleaner_sql.py
+++ b/lynda/modules/sql/cleaner_sql.py
@@ -141,17 +141,18 @@ def is_command_ignored(chat_id, command):
if command.lower() in GLOBAL_IGNORE_COMMANDS:
return True
- if str(chat_id) in CLEANER_CHATS:
- if command.lower() in CLEANER_CHATS.get(str(chat_id)).get('commands'):
- return True
-
- return False
+ return str(
+ chat_id
+ ) in CLEANER_CHATS and command.lower() in CLEANER_CHATS.get(
+ str(chat_id)
+ ).get(
+ 'commands'
+ )
def is_enabled(chat_id):
if str(chat_id) in CLEANER_CHATS:
- settings = CLEANER_CHATS.get(str(chat_id)).get('setting')
- return settings
+ return CLEANER_CHATS.get(str(chat_id)).get('setting')
return False
diff --git a/lynda/modules/sql/feds_sql.py b/lynda/modules/sql/feds_sql.py
index a5838cb9..d5b8ab2b 100644
--- a/lynda/modules/sql/feds_sql.py
+++ b/lynda/modules/sql/feds_sql.py
@@ -147,35 +147,37 @@ def get_user_fban(fed_id, user_id):
def get_user_admin_fed_name(user_id):
- user_feds = []
- for f in FEDERATION_BYFEDID:
- if int(user_id) in eval(eval(FEDERATION_BYFEDID[f]['fusers'])['members']):
- user_feds.append(FEDERATION_BYFEDID[f]['fname'])
- return user_feds
+ return [
+ FEDERATION_BYFEDID[f]['fname']
+ for f in FEDERATION_BYFEDID
+ if int(user_id)
+ in eval(eval(FEDERATION_BYFEDID[f]['fusers'])['members'])
+ ]
def get_user_owner_fed_name(user_id):
- user_feds = []
- for f in FEDERATION_BYFEDID:
- if int(user_id) == int(eval(FEDERATION_BYFEDID[f]['fusers'])['owner']):
- user_feds.append(FEDERATION_BYFEDID[f]['fname'])
- return user_feds
+ return [
+ FEDERATION_BYFEDID[f]['fname']
+ for f in FEDERATION_BYFEDID
+ if int(user_id) == int(eval(FEDERATION_BYFEDID[f]['fusers'])['owner'])
+ ]
def get_user_admin_fed_full(user_id):
- user_feds = []
- for f in FEDERATION_BYFEDID:
- if int(user_id) in eval(eval(FEDERATION_BYFEDID[f]['fusers'])['members']):
- user_feds.append({"fed_id": f, "fed": FEDERATION_BYFEDID[f]})
- return user_feds
+ return [
+ {"fed_id": f, "fed": FEDERATION_BYFEDID[f]}
+ for f in FEDERATION_BYFEDID
+ if int(user_id)
+ in eval(eval(FEDERATION_BYFEDID[f]['fusers'])['members'])
+ ]
def get_user_owner_fed_full(user_id):
- user_feds = []
- for f in FEDERATION_BYFEDID:
- if int(user_id) == int(eval(FEDERATION_BYFEDID[f]['fusers'])['owner']):
- user_feds.append({"fed_id": f, "fed": FEDERATION_BYFEDID[f]})
- return user_feds
+ return [
+ {"fed_id": f, "fed": FEDERATION_BYFEDID[f]}
+ for f in FEDERATION_BYFEDID
+ if int(user_id) == int(eval(FEDERATION_BYFEDID[f]['fusers'])['owner'])
+ ]
def get_user_fbanlist(user_id):
@@ -289,10 +291,7 @@ def search_user_in_fed(fed_id, user_id):
if getfed is None:
return False
getfed = eval(getfed['fusers'])['members']
- if user_id in eval(getfed):
- return True
- else:
- return False
+ return user_id in eval(getfed)
def user_demote_fed(fed_id, user_id):
@@ -321,18 +320,6 @@ def user_demote_fed(fed_id, user_id):
SESSION.commit()
return True
- curr = SESSION.query(UserF).all()
- result = False
- for r in curr:
- if int(r.user_id) == int(user_id):
- if r.fed_id == fed_id:
- SESSION.delete(r)
- SESSION.commit()
- result = True
-
- SESSION.close()
- return result
-
def user_join_fed(fed_id, user_id):
with FEDS_LOCK:
@@ -402,8 +389,7 @@ def all_fed_users(fed_id):
def all_fed_members(fed_id):
with FEDS_LOCK:
getfed = FEDERATION_BYFEDID.get(str(fed_id))
- fed_admins = eval(eval(getfed['fusers'])['members'])
- return fed_admins
+ return eval(eval(getfed['fusers'])['members'])
def set_frules(fed_id, rules):
@@ -429,17 +415,15 @@ def set_frules(fed_id, rules):
def get_frules(fed_id):
with FEDS_LOCK:
- rules = FEDERATION_BYFEDID[str(fed_id)]['frules']
- return rules
+ return FEDERATION_BYFEDID[str(fed_id)]['frules']
def fban_user(fed_id, user_id, first_name, last_name, user_name, reason, time):
with FEDS_LOCK:
r = SESSION.query(BansF).all()
for I in r:
- if I.fed_id == fed_id:
- if int(I.user_id) == int(user_id):
- SESSION.delete(I)
+ if I.fed_id == fed_id and int(I.user_id) == int(user_id):
+ SESSION.delete(I)
r = BansF(str(fed_id), str(user_id), first_name, last_name, user_name, reason, time)
@@ -497,9 +481,8 @@ def un_fban_user(fed_id, user_id):
with FEDS_LOCK:
r = SESSION.query(BansF).all()
for I in r:
- if I.fed_id == fed_id:
- if int(I.user_id) == int(user_id):
- SESSION.delete(I)
+ if I.fed_id == fed_id and int(I.user_id) == int(user_id):
+ SESSION.delete(I)
try:
SESSION.commit()
except Exception:
@@ -519,10 +502,9 @@ def get_fban_user(fed_id, user_id):
r = SESSION.query(BansF).all()
reason = None
for I in r:
- if I.fed_id == fed_id:
- if int(I.user_id) == int(user_id):
- reason = I.reason
- time = I.time
+ if I.fed_id == fed_id and int(I.user_id) == int(user_id):
+ reason = I.reason
+ time = I.time
return True, reason, time
else:
return False, None, None
@@ -540,8 +522,7 @@ def get_all_fban_users_target(fed_id, user_id):
if list_fbanned is None:
FEDERATION_BANNED_FULL[fed_id] = []
return False
- getuser = list_fbanned[str(user_id)]
- return getuser
+ return list_fbanned[str(user_id)]
def get_all_fban_users_global():
@@ -553,10 +534,7 @@ def get_all_fban_users_global():
def get_all_feds_users_global():
- total = []
- for x in list(FEDERATION_BYFEDID):
- total.append(FEDERATION_BYFEDID[x])
- return total
+ return [FEDERATION_BYFEDID[x] for x in list(FEDERATION_BYFEDID)]
def search_fed_by_id(fed_id):
diff --git a/lynda/modules/stickers.py b/lynda/modules/stickers.py
index dd4f5493..a0f80f57 100644
--- a/lynda/modules/stickers.py
+++ b/lynda/modules/stickers.py
@@ -33,11 +33,11 @@ def stickerid(_bot: Bot, update: Update):
@run_async
def getsticker(bot: Bot, update: Update):
msg = update.effective_message
- chat_id = update.effective_chat.id
if msg.reply_to_message and msg.reply_to_message.sticker:
file_id = msg.reply_to_message.sticker.file_id
new_file = bot.get_file(file_id)
new_file.download('sticker.png')
+ chat_id = update.effective_chat.id
bot.send_document(chat_id, document=open('sticker.png', 'rb'))
os.remove("sticker.png")
else:
@@ -88,7 +88,7 @@ def kang(bot: Bot, update: Update, args: List[str]):
if (im.width and im.height) < 512:
size1 = im.width
size2 = im.height
- if im.width > im.height:
+ if size1 > size2:
scale = 512/size1
size1new = 512
size2new = size2 * scale
@@ -113,21 +113,24 @@ def kang(bot: Bot, update: Update, args: List[str]):
print(e)
return
except TelegramError as e:
- if e.message == "Stickerset_invalid":
- makepack_internal(msg, user, open('stolensticker.png', 'rb'), sticker_emoji, bot, packname, packnum)
+ if (
+ e.message
+ == "Internal Server Error: sticker set not found (500)"
+ ):
+ msg.reply_text("Sticker successfully added to [pack](t.me/addstickers/%s)" % packname + "\n"
+ "Emoji is:" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN)
+ elif e.message == "Invalid sticker emojis":
+ msg.reply_text("Invalid emoji(s).")
elif e.message == "Sticker_png_dimensions":
im.save(stolensticker, "PNG")
bot.add_sticker_to_set(user_id=user.id, name=packname,
png_sticker=open('stolensticker.png', 'rb'), emojis=sticker_emoji)
msg.reply_text(f"Sticker successfully added to [pack](t.me/addstickers/{packname})" +
f"\nEmoji is: {sticker_emoji}", parse_mode=ParseMode.MARKDOWN)
- elif e.message == "Invalid sticker emojis":
- msg.reply_text("Invalid emoji(s).")
elif e.message == "Stickers_too_much":
msg.reply_text("Max packsize reached.")
- elif e.message == "Internal Server Error: sticker set not found (500)":
- msg.reply_text("Sticker successfully added to [pack](t.me/addstickers/%s)" % packname + "\n"
- "Emoji is:" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN)
+ elif e.message == "Stickerset_invalid":
+ makepack_internal(msg, user, open('stolensticker.png', 'rb'), sticker_emoji, bot, packname, packnum)
print(e)
elif args:
try:
@@ -143,7 +146,7 @@ def kang(bot: Bot, update: Update, args: List[str]):
if (im.width and im.height) < 512:
size1 = im.width
size2 = im.height
- if im.width > im.height:
+ if size1 > size2:
scale = 512/size1
size1new = 512
size2new = size2 * scale
@@ -168,27 +171,30 @@ def kang(bot: Bot, update: Update, args: List[str]):
print(e)
return
except TelegramError as e:
- if e.message == "Stickerset_invalid":
- makepack_internal(msg, user, open('stolensticker.png', 'rb'), sticker_emoji, bot, packname, packnum)
+ if (
+ e.message
+ == "Internal Server Error: sticker set not found (500)"
+ ):
+ msg.reply_text("Sticker successfully added to [pack](t.me/addstickers/%s)" % packname + "\n"
+ "Emoji is:" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN)
+ elif e.message == "Invalid sticker emojis":
+ msg.reply_text("Invalid emoji(s).")
elif e.message == "Sticker_png_dimensions":
im.save(stolensticker, "PNG")
bot.add_sticker_to_set(user_id=user.id, name=packname,
png_sticker=open('stolensticker.png', 'rb'), emojis=sticker_emoji)
msg.reply_text("Sticker successfully added to [pack](t.me/addstickers/%s)" % packname + "\n" +
"Emoji is:" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN)
- elif e.message == "Invalid sticker emojis":
- msg.reply_text("Invalid emoji(s).")
elif e.message == "Stickers_too_much":
msg.reply_text("Max packsize reached.")
- elif e.message == "Internal Server Error: sticker set not found (500)":
- msg.reply_text("Sticker successfully added to [pack](t.me/addstickers/%s)" % packname + "\n"
- "Emoji is:" + " " + sticker_emoji, parse_mode=ParseMode.MARKDOWN)
+ elif e.message == "Stickerset_invalid":
+ makepack_internal(msg, user, open('stolensticker.png', 'rb'), sticker_emoji, bot, packname, packnum)
print(e)
else:
packs = "Please reply to a sticker or image to steal it to your pack!\nOh by the way, here are your packs:\n"
if packnum > 0:
firstpackname = "a" + str(user.id) + "_by_"+bot.username
- for i in range(0, packnum + 1):
+ for i in range(packnum + 1):
if i == 0:
packs += f"[pack](t.me/addstickers/{firstpackname})\n"
else:
@@ -215,13 +221,13 @@ def makepack_internal(msg, user, png_sticker, emoji, bot):
emojis=emoji)
except TelegramError as e:
print(e)
- if e.message == "Sticker set name is already occupied":
+ if e.message == "Peer_id_invalid":
+ msg.reply_text("Contact me in PM first.", reply_markup=InlineKeyboardMarkup(
+ [[InlineKeyboardButton(text="Start", url=f"t.me/{bot.username}")]]))
+ elif e.message == "Sticker set name is already occupied":
msg.reply_text(
f"Your pack can be found [here](t.me/addstickers/{packname})",
parse_mode=ParseMode.MARKDOWN)
- elif e.message == "Peer_id_invalid":
- msg.reply_text("Contact me in PM first.", reply_markup=InlineKeyboardMarkup(
- [[InlineKeyboardButton(text="Start", url=f"t.me/{bot.username}")]]))
return
if success:
diff --git a/lynda/modules/userinfo.py b/lynda/modules/userinfo.py
index e01c56db..e461cf55 100644
--- a/lynda/modules/userinfo.py
+++ b/lynda/modules/userinfo.py
@@ -16,11 +16,7 @@ def about_me(bot: Bot, update: Update, args: List[str]):
message = update.effective_message
user_id = extract_user(message, args)
- if user_id:
- user = bot.get_chat(user_id)
- else:
- user = message.from_user
-
+ user = bot.get_chat(user_id) if user_id else message.from_user
info = sql.get_user_me_info(user.id)
if info:
@@ -67,11 +63,7 @@ def about_bio(bot: Bot, update: Update, args: List[str]):
message = update.effective_message
user_id = extract_user(message, args)
- if user_id:
- user = bot.get_chat(user_id)
- else:
- user = message.from_user
-
+ user = bot.get_chat(user_id) if user_id else message.from_user
info = sql.get_user_bio(user.id)
if info:
@@ -89,8 +81,6 @@ def about_bio(bot: Bot, update: Update, args: List[str]):
@run_async
def set_about_bio(bot: Bot, update: Update):
message = update.effective_message
- sender_id = update.effective_user.id
-
if message.reply_to_message:
repl_message = message.reply_to_message
user_id = repl_message.from_user.id
@@ -100,6 +90,8 @@ def set_about_bio(bot: Bot, update: Update):
"Ha, you can't set your own bio! You're at the mercy of others here...")
return
+ sender_id = update.effective_user.id
+
if user_id == bot.id and sender_id not in SUDO_USERS and sender_id not in DEV_USERS:
message.reply_text(
"Erm... yeah, I only trust sudo users or developers to set my bio.")
diff --git a/lynda/modules/users.py b/lynda/modules/users.py
index c3369670..f7a57337 100644
--- a/lynda/modules/users.py
+++ b/lynda/modules/users.py
@@ -38,9 +38,7 @@ def get_user_id(username):
return userdat.id
except BadRequest as excp:
- if excp.message == 'Chat not found':
- pass
- else:
+ if excp.message != 'Chat not found':
LOGGER.exception("Error extracting user ID")
return None
diff --git a/lynda/modules/welcome.py b/lynda/modules/welcome.py
index 6af6bcda..9be8d655 100644
--- a/lynda/modules/welcome.py
+++ b/lynda/modules/welcome.py
@@ -218,49 +218,48 @@ def new_member(bot: Bot, update: Update, job_queue: JobQueue):
if new_mem.is_bot:
should_mute = False
- if user.id == new_mem.id:
- if should_mute:
- if welc_mutes == "soft":
- bot.restrict_chat_member(chat.id, new_mem.id,
- can_send_messages=True,
- can_send_media_messages=False,
- can_send_other_messages=False,
- can_add_web_page_previews=False,
- until_date=(int(time.time() + 24 * 60 * 60)))
-
- if welc_mutes == "strong":
- welcome_bool = False
- VERIFIED_USER_WAITLIST.update({
- new_mem.id: {
- "should_welc": should_welc,
- "status": False,
- "update": update,
- "res": res,
- "keyboard": keyboard,
- "backup_message": backup_message
- }
- })
- new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})"
- message = msg.reply_text(
- f"{new_join_mem}, click the button below to prove you're human.\nYou have 160 seconds.",
- reply_markup=InlineKeyboardMarkup(
- [
- {
- InlineKeyboardButton(
- text="Yes, I'm human.",
- callback_data=f"user_join_({new_mem.id})")}]),
- parse_mode=ParseMode.MARKDOWN)
- bot.restrict_chat_member(chat.id, new_mem.id,
- can_send_messages=False,
- can_send_media_messages=False,
- can_send_other_messages=False,
- can_add_web_page_previews=False)
-
- job_queue.run_once(
- partial(
- check_not_bot, new_mem, chat.id, message.message_id
- ), 160, name="welcomemute"
- )
+ if user.id == new_mem.id and should_mute:
+ if welc_mutes == "soft":
+ bot.restrict_chat_member(chat.id, new_mem.id,
+ can_send_messages=True,
+ can_send_media_messages=False,
+ can_send_other_messages=False,
+ can_add_web_page_previews=False,
+ until_date=(int(time.time() + 24 * 60 * 60)))
+
+ if welc_mutes == "strong":
+ welcome_bool = False
+ VERIFIED_USER_WAITLIST.update({
+ new_mem.id: {
+ "should_welc": should_welc,
+ "status": False,
+ "update": update,
+ "res": res,
+ "keyboard": keyboard,
+ "backup_message": backup_message
+ }
+ })
+ new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})"
+ message = msg.reply_text(
+ f"{new_join_mem}, click the button below to prove you're human.\nYou have 160 seconds.",
+ reply_markup=InlineKeyboardMarkup(
+ [
+ {
+ InlineKeyboardButton(
+ text="Yes, I'm human.",
+ callback_data=f"user_join_({new_mem.id})")}]),
+ parse_mode=ParseMode.MARKDOWN)
+ bot.restrict_chat_member(chat.id, new_mem.id,
+ can_send_messages=False,
+ can_send_media_messages=False,
+ can_send_other_messages=False,
+ can_add_web_page_previews=False)
+
+ job_queue.run_once(
+ partial(
+ check_not_bot, new_mem, chat.id, message.message_id
+ ), 160, name="welcomemute"
+ )
if welcome_bool:
sent = send(update, res, keyboard, backup_message)