Skip to content

Commit

Permalink
treewide: fixed DB and added restart alert back
Browse files Browse the repository at this point in the history
  • Loading branch information
HitaloM committed Apr 23, 2022
1 parent 5997945 commit 83a822d
Show file tree
Hide file tree
Showing 21 changed files with 135 additions and 118 deletions.
20 changes: 16 additions & 4 deletions eduu/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,30 @@
import logging
import platform

import httpx
from httpx import AsyncClient

from eduu.bot import Eduu
from eduu.database import database

logging.basicConfig(
level=logging.INFO,
format="%(name)s.%(funcName)s | %(levelname)s | %(message)s",
datefmt="[%X]",
)

# To avoid some annoying log
logging.getLogger("pyrogram.syncer").setLevel(logging.WARNING)
logging.getLogger("pyrogram.client").setLevel(logging.WARNING)

logger = logging.getLogger(__name__)

try:
import uvloop

uvloop.install()
except ImportError:
if platform.system() != "Windows":
logging.warning("uvloop is not installed and therefore will be disabled.")
logger.warning("uvloop is not installed and therefore will be disabled.")


if __name__ == "__main__":
Expand All @@ -29,10 +41,10 @@
Eduu().run()
except KeyboardInterrupt:
# exit gracefully
logging.warning("Forced stop... Bye!")
logger.warning("Forced stop... Bye!")
finally:
# close https connections and the DB if open
event_loop.run_until_complete(httpx.aclose())
event_loop.run_until_complete(AsyncClient().aclose())
if database.is_connected:
event_loop.run_until_complete(database.close())
# close asyncio event loop
Expand Down
17 changes: 8 additions & 9 deletions eduu/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@

import eduu
from eduu.config import API_HASH, API_ID, TOKEN, disabled_plugins, log_chat
from eduu.database.restarted import del_restarted, get_restarted
from eduu.utils.utils import shell_exec

logger = logging.getLogger(__name__)


class Eduu(Client):
def __init__(self):
Expand All @@ -35,22 +36,20 @@ def __init__(self):
async def start(self):
await super().start()

# Saving commit number
self.version_code = int((await shell_exec("git rev-list --count HEAD"))[0])

self.me = await self.get_me()

self.start_time = time.time()

self.me = await self.get_me()
logging.info(
logger.info(
"Eduu running with Pyrogram v%s (Layer %s) started on @%s. Hi!",
__version__,
layer,
self.me.username,
)

if "test" not in sys.argv:
from eduu.database.restarted import del_restarted, get_restarted

wr = await get_restarted()
await del_restarted()

Expand All @@ -64,11 +63,11 @@ async def start(self):
await self.send_message(chat_id=log_chat, text=start_message)
if wr:
await self.edit_message_text(
wr[0], wr[1], "Restarted successfully!"
wr[0], wr[1], text="Restarted successfully!"
)
except BadRequest:
logging.warning("Unable to send message to log_chat.")
logger.warning("Unable to send message to log_chat.")

async def stop(self):
await super().stop()
logging.warning("Eduu stopped. Bye!")
logger.warning("Eduu stopped. Bye!")
8 changes: 4 additions & 4 deletions eduu/database/admins.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ async def check_if_del_service(chat_id: int) -> bool:
cursor = await conn.execute(
"SELECT delservicemsgs FROM groups WHERE chat_id = ?", (chat_id,)
)
row = await cursor.fetchone()[0]
row = await cursor.fetchone()
await cursor.close()
return row
return row[0]


async def toggle_del_service(chat_id: int, mode: Optional[bool]) -> None:
Expand All @@ -28,9 +28,9 @@ async def check_if_antichannelpin(chat_id: int) -> bool:
cursor = await conn.execute(
"SELECT antichannelpin FROM groups WHERE chat_id = ?", (chat_id,)
)
row = await cursor.fetchone()[0]
row = await cursor.fetchone()
await cursor.close()
return row
return row[0]


async def toggle_antichannelpin(chat_id: int, mode: Optional[bool]) -> None:
Expand Down
6 changes: 3 additions & 3 deletions eduu/database/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@ async def chat_exists(chat_id, chat_type):
cursor = await conn.execute(
"SELECT user_id FROM users where user_id = ?", (chat_id,)
)
row = await cursor.fetchone()[0]
row = await cursor.fetchone()
return bool(row)
if chat_type in group_types: # groups and supergroups share the same table
cursor = await conn.execute(
"SELECT chat_id FROM groups where chat_id = ?", (chat_id,)
)
row = await cursor.fetchone()[0]
row = await cursor.fetchone()
return bool(row)
if chat_type == "channel":
cursor = conn.execute(
"SELECT chat_id FROM channels where chat_id = ?", (chat_id,)
)
row = await cursor.fetchone()[0]
row = await cursor.fetchone()
return bool(row)
raise TypeError("Unknown chat type '%s'." % chat_type)
4 changes: 2 additions & 2 deletions eduu/database/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ async def get_rules(chat_id):
"SELECT rules FROM groups WHERE chat_id = (?)", (chat_id,)
)
try:
row = await cursor.fetchone()[0]
return row
row = await cursor.fetchone()
return row[0]
except IndexError:
return None

Expand Down
9 changes: 2 additions & 7 deletions eduu/plugins/admins/bans.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@
from pyrogram.types import Message

from eduu.config import prefix
from eduu.utils import (
commands,
get_reason_text,
get_target_user,
require_admin,
time_extract,
)
from eduu.utils import commands, get_reason_text, get_target_user, time_extract
from eduu.utils.consts import admin_status
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/admins/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

from eduu.config import prefix
from eduu.database.admins import check_if_del_service, toggle_del_service
from eduu.utils import commands, require_admin
from eduu.utils import commands
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
9 changes: 2 additions & 7 deletions eduu/plugins/admins/mutes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@
from pyrogram.types import ChatPermissions, Message

from eduu.config import prefix
from eduu.utils import (
commands,
get_reason_text,
get_target_user,
require_admin,
time_extract,
)
from eduu.utils import commands, get_reason_text, get_target_user, time_extract
from eduu.utils.consts import admin_status
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/admins/pins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

from eduu.config import prefix
from eduu.database.admins import check_if_antichannelpin, toggle_antichannelpin
from eduu.utils import commands, require_admin
from eduu.utils import commands
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
2 changes: 1 addition & 1 deletion eduu/plugins/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pyrogram import Client
from pyrogram.types import Message

from eduu.utils import add_chat, chat_exists
from eduu.database.chats import add_chat, chat_exists

# This is the first plugin run to guarantee
# that the actual chat is initialized in the DB.
Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/custom_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
rm_filter,
update_filter,
)
from eduu.utils import button_parser, commands, require_admin, split_quotes
from eduu.utils import button_parser, commands, split_quotes
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
6 changes: 4 additions & 2 deletions eduu/plugins/gif.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
from eduu.utils import commands, http
from eduu.utils.localization import use_chat_lang

logger = logging.getLogger(__name__)

if not TENOR_API_KEY:
logging.warning(
f"[{__name__}] You need to fill TENOR_API_KEY in your config file in order to use this plugin."
logger.warning(
"You need to fill TENOR_API_KEY in your config file in order to use this plugin."
)


Expand Down
6 changes: 3 additions & 3 deletions eduu/plugins/langs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
)

from eduu.config import prefix
from eduu.utils import require_admin
from eduu.database.localization import set_db_lang
from eduu.utils.decorators import require_admin
from eduu.utils.localization import (
default_language,
get_locale_string,
langdict,
set_db_lang,
use_chat_lang,
)

Expand Down Expand Up @@ -85,7 +85,7 @@ async def chlang(c: Client, m: Union[CallbackQuery, Message], strings):
@use_chat_lang()
async def set_chat_lang(c: Client, m: CallbackQuery, strings):
lang = m.data.split()[1]
set_db_lang(m.message.chat.id, m.message.chat.type, lang)
await set_db_lang(m.message.chat.id, m.message.chat.type, lang)

strings = partial(
get_locale_string,
Expand Down
7 changes: 4 additions & 3 deletions eduu/plugins/notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

from eduu.config import prefix
from eduu.database.notes import add_note, get_all_notes, rm_note, update_note
from eduu.utils import button_parser, commands, require_admin, split_quotes
from eduu.utils import button_parser, commands, split_quotes
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down Expand Up @@ -115,7 +116,7 @@ async def delete_note(c: Client, m: Message, strings):
async def get_all_chat_note(c: Client, m: Message, strings):
chat_id = m.chat.id
reply_text = strings("notes_list")
all_notes = get_all_notes(chat_id)
all_notes = await get_all_notes(chat_id)
for note_s in all_notes:
keyword = note_s[1]
reply_text += f" - {keyword} \n"
Expand All @@ -130,7 +131,7 @@ async def serve_note(c: Client, m: Message, txt):
chat_id = m.chat.id
text = txt

all_notes = get_all_notes(chat_id)
all_notes = await get_all_notes(chat_id)
for note_s in all_notes:
keyword = note_s[1]
pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from eduu.config import prefix
from eduu.database.rules import get_rules, set_rules
from eduu.utils import button_parser, commands, require_admin
from eduu.utils import button_parser, commands
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
21 changes: 11 additions & 10 deletions eduu/plugins/sudos.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
from pyrogram.types import Message

from eduu.database import database
from eduu.utils import set_restarted, sudofilter
from eduu.database.restarted import set_restarted
from eduu.utils import sudofilter
from eduu.utils.localization import use_chat_lang

prefix: Union[list, str] = "!"
Expand Down Expand Up @@ -185,7 +186,7 @@ async def execsql(c: Client, m: Message):
@use_chat_lang()
async def restart(c: Client, m: Message, strings):
sent = await m.reply_text(strings("restarting"))
set_restarted(sent.chat.id, sent.message_id)
await set_restarted(sent.chat.id, sent.message_id)
await conn.commit()
args = [sys.executable, "-m", "eduu"]
os.execv(sys.executable, args) # skipcq: BAN-B606
Expand All @@ -209,22 +210,22 @@ async def leave_chat(c: Client, m: Message):
@Client.on_message(filters.command(["bot_stats", "stats"], prefix) & sudofilter)
async def getbotstats(c: Client, m: Message):
users_count = await conn.execute("select count() from users")
users_count = await users_count.fetchone()[0]
users_count = await users_count.fetchone()
groups_count = await conn.execute("select count() from groups")
groups_count = await groups_count.fetchone()[0]
groups_count = await groups_count.fetchone()
filters_count = await conn.execute("select count() from filters")
filters_count = await filters_count.fetchone()[0]
filters_count = await filters_count.fetchone()
notes_count = await conn.execute("select count() from notes")
notes_count = await notes_count.fetchone()[0]
notes_count = await notes_count.fetchone()
bot_uptime = round(time.time() - c.start_time)
bot_uptime = humanfriendly.format_timespan(bot_uptime)

await m.reply_text(
"<b>Bot statistics:</b>\n\n"
f"<b>Users:</b> {users_count}\n"
f"<b>Groups:</b> {groups_count}\n"
f"<b>Filters:</b> {filters_count}\n"
f"<b>Notes:</b> {notes_count}\n\n"
f"<b>Users:</b> {users_count[0]}\n"
f"<b>Groups:</b> {groups_count[0]}\n"
f"<b>Filters:</b> {filters_count[0]}\n"
f"<b>Notes:</b> {notes_count[0]}\n\n"
f"<b>Uptime:</b> {bot_uptime}"
)

Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/warns.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
set_warn_action,
set_warns_limit,
)
from eduu.utils import commands, get_target_user, require_admin
from eduu.utils import commands, get_target_user
from eduu.utils.consts import admin_status
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down
3 changes: 2 additions & 1 deletion eduu/plugins/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

from eduu.config import prefix
from eduu.database.welcome import get_welcome, set_welcome, toggle_welcome
from eduu.utils import button_parser, commands, get_format_keys, require_admin
from eduu.utils import button_parser, commands, get_format_keys
from eduu.utils.decorators import require_admin
from eduu.utils.localization import use_chat_lang


Expand Down

0 comments on commit 83a822d

Please sign in to comment.