我有两个文件:bot.py 和 utils/FunctionsWorker.py .
bot.py代码:
from telethon.sync import TelegramClient, events
from telethon.sessions import StringSession
import asyncio
import os
import logging
from utils import FunctionsWorker
from pathlib import Path
import glob
api_id = 0
api_hash = ""
if os.path.exists("your.session"):
client = TelegramClient(StringSession(open("your.session", "r").read()), api_id=0, api_hash="")
else:
print("Creating new session.")
with TelegramClient(StringSession(), api_id, api_hash) as client:
file = open("your.session", "x+")
file.write(client.session.save())
client.tgbot = client
async def run():
await client.connect()
print("[Connection] Connection to telegram established.")
async with client:
await client.run_until_disconnected()
path = 'modules/*.py'
files = glob.glob(path)
FunctionsWorker.Worker("modules/")
for name in files:
with open(name) as f:
path1 = Path(f.name)
shortname = path1.stem
try:
FunctionsWorker.Worker("modules").load_module(shortname.replace(".py", ""))
logging.info(f" Module loaded. {name}")
except Exception as Error:
logging.error(f" Module not loaded: {Error}")
print(FunctionsWorker.Worker("Modules").get_mods())
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
utils/FunctionsWorker.py:
import sys
import importlib.util
import logging
from pathlib import Path
from bot import client
class Worker:
def __init__(self, moduless):
self.moduless = moduless
self.instant = []
def load_mod(self, name):
mod = name
name = name.replace(".py", "")
path = Path(f"modules/{name}.py")
name = f"modules.{name}"
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
mod.tgbot = client.tgbot
mod.borg = client
spec.loader.exec_module(mod)
self.instant.append(mod)
sys.modules["modules."+mod] = mod
print("Successfully (re)imported " + name)
def get_mods(self):
try:
return self.instant
except Exception as Error:
logging.debug(f"Error: {Error}")
但是,我收到这个错误:
Traceback (most recent call last):
File "bot.py", line 9, in <module>
from utils import FunctionsWorker
File "/home/debian/teletbot/kobra_me/utils/FunctionsWorker.py", line 5, in <module>
from bot import client
File "/home/debian/teletbot/kobra_me/bot.py", line 35, in <module>
FunctionsWorker.Worker("modules/")
AttributeError: module 'utils.FunctionsWorker' has no attribute 'Worker'
谁能解决这个问题? 我什么也做不了:我找不到为什么会出错。这是严重的错误:( 我尝试编辑这 >9 次尝试,但它不会工作 好吗?