Search code examples
pythonpyrogram

Importing decorated functions from multiple files doesn't seem to work


I am making my own userbot, I was trying to place each command in its own python file (To make it easier to manage) but for some mythical reason only one file (first on the list of imports) is being imported, I've tried to look through documentation, even asked in "Pyrogram Inn" chat on Telegram, but nobody seemed to respond

import asyncio
from os import path
from modules.clients.main_user import user

from modules.commands.echo import command_echo, execute_echo
from modules.commands.help import command_help


def login():
    if path.exists("./config.ini"):
        print('Credentials config found')
    else:
        print("Login at https://my.telegram.org/apps and")
        api_id = int(input("enter your api_id: "))
        api_hash = input("enter your api_hash: ")
        with open(f'{str(__file__).replace("main.py", "")}/config.ini', 'w') as config:
            config.write(f"[pyrogram] \n api_id = {api_id} \n api_hash = {api_hash}")

if __name__ == "__main__":
    login()
    user.run()

In example above only command_echo and execute_echo are being imported, while command_help is ignored, unless I comment out echo import, then help works

Content of echo module:

from pyrogram import filters
from modules.clients.main_user import user, command_prefix

chats_involved = {}
loop = False

@user.on_message(filters.command('echo', command_prefix))
async def command_echo(client, message) -> None:
    """Enable repeating of all incoming messages in chat

    Args:
        client ([Client]): Pyrogram client, usually passed by decorator
        message ([Message]): Pyrogram message, usually passed by decorator
    """
    global loop
    chat_data = await user.get_chat(message.chat.id)
    chat_name = f'**{chat_data.title}**'
    data = str(message.text)
    if "enable" in data.lower() or "true" in data.lower():
        chats_involved[message.chat.id] = 1
        await message.edit(f"Module **echo** was enabled in {chat_name}")
    elif "disable" in data.lower() or "false" in data.lower():
        chats_involved[message.chat.id] = 0
        loop = False
        await message.edit(f"Module **echo** was disabled in {chat_name}")
    elif ("loop" in data.lower() or "kill" in data.lower()) and "YES" in data:
        loop = True
        await message.edit(f"**Loop** mode of **echo** is **activated**! Run, fools!")
    elif "loop" in data.lower() or "kill" in data.lower():
        if loop == True:
            loop = not loop
        await message.edit(f"**Loop** mode is very dangerous and can get you **BANNED**, to confirm activation run: ```{command_prefix}echo loop YES```")
    try:
        if chats_involved[message.chat.id] == 0 and loop:
            await message.reply(f"Not really, you forgot to enable **echo**, genius... run: ```{command_prefix}echo true```")
    except:
        pass # TODO log some info or warning about chat not being in dictionary yet

    print(chats_involved)
    print(message.chat.id)
    #print(loop)

@user.on_message()
async def execute_echo(client, message):
    global loop
    if message.chat.id not in chats_involved:
        chats_involved[message.chat.id] = 0
    if chats_involved[message.chat.id] == 1:
        if message.text is not f'{command_prefix}echo':
            if message.sticker is not None:
                while loop:
                    await message.reply_sticker(message.sticker.file_id)
                await message.reply_sticker(message.sticker.file_id)
                
            elif message.text is not None:
                print(loop)
                while loop:
                    await message.reply(message.text)
                await message.reply(message.text)
                # await message.reply(message) # FOR DEBUG

Content of help module:

from pyrogram import filters
from modules.clients.main_user import user, command_prefix

commands = {
 "echo": f"""
            **==Repeat messages after others==**
            Usage: ```{command_prefix}echo [option]```
            Options:
            true, enable   : activate echo mode
            false, disable : deactivate echo mode
            loop, kill     : repeats all messages it can see indefinitely, 
                             requires further confirmation for your account's
                             safety but can be bypassed by confirming it ahead of time"""
}

#@user.on_message(filters.command('help', command_prefix))
@user.on_message()
async def command_help(client, message) -> None:
    data = str(message.text)
    for command in commands:
        await message.edit("TEST TEST!")

Content of "main_user" that's being imported in both cases:

from pyrogram import Client

user = Client("LuxTenebris")
command_prefix = '#'

Does anyone have any idea why wouldn't it work like I expected it to? I am really stuck on this one


Solution

  • I was suggested to use Smart Plugins for modular system instead of my solution, which solves it.