调整配置文件结构,使不同插件可以将结果发送至不同telegram bot上
This commit is contained in:
@@ -3,11 +3,10 @@ import importlib.util
|
|||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from util.base_plugin import BasePlugin
|
from util.base_plugin import BasePlugin
|
||||||
|
|
||||||
import telegram
|
import telegram
|
||||||
|
|
||||||
|
|
||||||
class PluginManager:
|
class PluginManager:
|
||||||
PLUGIN_DIR = "custom_plugins"
|
PLUGIN_DIR = "custom_plugins"
|
||||||
|
|
||||||
@@ -17,7 +16,6 @@ class PluginManager:
|
|||||||
self.running_tasks = []
|
self.running_tasks = []
|
||||||
# 插件所在目录
|
# 插件所在目录
|
||||||
self.plugins_path = {}
|
self.plugins_path = {}
|
||||||
# self.loop = asyncio.new_event_loop()
|
|
||||||
self.config = config
|
self.config = config
|
||||||
|
|
||||||
def load_plugins(self):
|
def load_plugins(self):
|
||||||
@@ -37,21 +35,19 @@ class PluginManager:
|
|||||||
member = getattr(module, member_name)
|
member = getattr(module, member_name)
|
||||||
|
|
||||||
if callable(member) and hasattr(member, "__bases__") and BasePlugin in member.__bases__:
|
if callable(member) and hasattr(member, "__bases__") and BasePlugin in member.__bases__:
|
||||||
print(member)
|
self.plugins[plugin_name] = member(root)
|
||||||
self.plugins[plugin_name] = member()
|
|
||||||
self.plugins_path[plugin_name] = root
|
self.plugins_path[plugin_name] = root
|
||||||
print(f"Plugin '{plugin_name}' loaded successfully.")
|
print(f"Plugin '{plugin_name}' loaded successfully.")
|
||||||
|
|
||||||
def execute_plugins(self, *args, **kwargs):
|
def execute_plugins(self, *args, **kwargs):
|
||||||
for plugin_name, plugin_instance in self.plugins.items():
|
for plugin_name, plugin_instance in self.plugins.items():
|
||||||
print(f"Executing plugin '{plugin_name}':")
|
print(f"Executing plugin '{plugin_name}':")
|
||||||
plugin_instance.run_plugin(self.callback, *args, **kwargs)
|
plugin_instance.run_plugin(*args, **kwargs)
|
||||||
|
|
||||||
async def execute_plugin(self, plugin_name, *args, **kwargs):
|
async def execute_plugin(self, plugin_name, *args, **kwargs):
|
||||||
if plugin_name in self.plugins:
|
if plugin_name in self.plugins:
|
||||||
print(f"Executing plugin '{plugin_name}':")
|
print(f"Executing plugin '{plugin_name}':")
|
||||||
return await self.plugins[plugin_name].run_plugin(*args, **kwargs)
|
return await self.plugins[plugin_name].run_plugin(*args, **kwargs)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(f"Plugin '{plugin_name}' not found.")
|
print(f"Plugin '{plugin_name}' not found.")
|
||||||
return f"Plugin '{plugin_name}' not found."
|
return f"Plugin '{plugin_name}' not found."
|
||||||
@@ -63,6 +59,7 @@ class PluginManager:
|
|||||||
def start_scheduler(self):
|
def start_scheduler(self):
|
||||||
self.loop = asyncio.new_event_loop()
|
self.loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(self.loop)
|
asyncio.set_event_loop(self.loop)
|
||||||
|
|
||||||
def scheduler():
|
def scheduler():
|
||||||
asyncio.set_event_loop(self.loop)
|
asyncio.set_event_loop(self.loop)
|
||||||
for name in self.get_plugin_name_list():
|
for name in self.get_plugin_name_list():
|
||||||
@@ -75,9 +72,15 @@ class PluginManager:
|
|||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
|
|
||||||
async def execute_plugin_async(self, plugin_name, schedule, *args, **kwargs):
|
async def execute_plugin_async(self, plugin_name, schedule, *args, **kwargs):
|
||||||
|
telegram_need = False
|
||||||
|
result = {'result':""}
|
||||||
|
try:
|
||||||
|
token = self.config.get_plugin_config('TELEGRAM', self.plugins_path[plugin_name])['BOT_TOKEN']
|
||||||
|
chat_id = self.config.get_plugin_config('TELEGRAM', self.plugins_path[plugin_name])['CHAT_ID']
|
||||||
|
telegram_need = True
|
||||||
|
except:
|
||||||
|
telegram_need = False
|
||||||
sleep_time = 30
|
sleep_time = 30
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
@@ -86,10 +89,10 @@ class PluginManager:
|
|||||||
print(schedule)
|
print(schedule)
|
||||||
if schedule['mode'] == "INTERVAL" or schedule['mode'] == "CONTIENUOUS":
|
if schedule['mode'] == "INTERVAL" or schedule['mode'] == "CONTIENUOUS":
|
||||||
result = await self.execute_plugin(plugin_name, *args, **kwargs)
|
result = await self.execute_plugin(plugin_name, *args, **kwargs)
|
||||||
token = self.config.get_config('TELEGRAM')['BOT_TOKEN']
|
|
||||||
chat_id = self.config.get_config('TELEGRAM')['CHAT_ID']
|
|
||||||
await self.send_message_async(token, chat_id, result['result'])
|
|
||||||
sleep_time = schedule['INTERVAL_TIME']
|
sleep_time = schedule['INTERVAL_TIME']
|
||||||
|
if telegram_need:
|
||||||
|
if result['result'] != "":
|
||||||
|
await self.send_message_async(token, chat_id, result['result'])
|
||||||
elif schedule['mode'] == "FIX":
|
elif schedule['mode'] == "FIX":
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
today = now.date()
|
today = now.date()
|
||||||
@@ -97,23 +100,22 @@ class PluginManager:
|
|||||||
next_day = today
|
next_day = today
|
||||||
else:
|
else:
|
||||||
next_day = today + timedelta(days=1)
|
next_day = today + timedelta(days=1)
|
||||||
|
|
||||||
next_time = datetime(year=next_day.year, month=next_day.month, day=next_day.day,
|
next_time = datetime(year=next_day.year, month=next_day.month, day=next_day.day,
|
||||||
hour=schedule['HOUR'], minute=schedule['MINUTE'])
|
hour=schedule['HOUR'], minute=schedule['MINUTE'])
|
||||||
print(next_time)
|
print(next_time)
|
||||||
sleep_time = (next_time - now).seconds
|
sleep_time = (next_time - now).seconds
|
||||||
if now.hour == schedule['HOUR'] and now.minute == schedule["MINUTE"]:
|
if now.hour == schedule['HOUR'] and now.minute == schedule["MINUTE"]:
|
||||||
result = await self.execute_plugin(plugin_name, *args, **kwargs)
|
result = await self.execute_plugin(plugin_name, *args, **kwargs)
|
||||||
token = self.config.get_config('TELEGRAM')['BOT_TOKEN']
|
if telegram_need:
|
||||||
chat_id = self.config.get_config('TELEGRAM')['CHAT_ID']
|
if result['result'] != "":
|
||||||
await self.send_message_async(token, chat_id, result['result'])
|
await self.send_message_async(token, chat_id, result['result'])
|
||||||
else:
|
else:
|
||||||
print(f"Plugin '{plugin_name}' not found.")
|
print(f"Plugin '{plugin_name}' not found.")
|
||||||
|
|
||||||
|
|
||||||
print(sleep_time)
|
print(sleep_time)
|
||||||
await asyncio.sleep(sleep_time)
|
await asyncio.sleep(sleep_time)
|
||||||
|
|
||||||
|
|
||||||
async def send_message_async(self, bot_token, chat_id, text):
|
async def send_message_async(self, bot_token, chat_id, text):
|
||||||
proxy = telegram.request.HTTPXRequest(proxy_url='http://127.0.0.1:8889')
|
proxy = telegram.request.HTTPXRequest(proxy_url='http://127.0.0.1:8889')
|
||||||
bot = telegram.Bot(token=bot_token, request=proxy)
|
bot = telegram.Bot(token=bot_token, request=proxy)
|
||||||
@@ -129,7 +131,7 @@ class PluginManager:
|
|||||||
if 'INTERVAL_TIME' in schedule_config.keys():
|
if 'INTERVAL_TIME' in schedule_config.keys():
|
||||||
interval_time = (schedule_config['INTERVAL_TIME']['HOUR'] * 3600 +
|
interval_time = (schedule_config['INTERVAL_TIME']['HOUR'] * 3600 +
|
||||||
schedule_config['INTERVAL_TIME']['MINUTE'] * 60 +
|
schedule_config['INTERVAL_TIME']['MINUTE'] * 60 +
|
||||||
schedule_config['INTERVAL_TIME']['SECOND'])
|
schedule_config['INTERVAL_TIME']['SECOND'])
|
||||||
if interval_time < 30:
|
if interval_time < 30:
|
||||||
schedule['INTERVAL_TIME'] = 30
|
schedule['INTERVAL_TIME'] = 30
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ class Config:
|
|||||||
|
|
||||||
__BASE_PATH = os.getcwd()
|
__BASE_PATH = os.getcwd()
|
||||||
__CONFIG_PATH = os.path.join(__BASE_PATH, 'config')
|
__CONFIG_PATH = os.path.join(__BASE_PATH, 'config')
|
||||||
__CONFIG_NAME = 'test.yaml'
|
__CONFIG_NAME = 'config.yaml'
|
||||||
__SCHEDULER_DB_FILE_NAME = 'schedule_db.db'
|
# __SCHEDULER_DB_FILE_NAME = 'schedule_db.db'
|
||||||
__LOG_FILE_NAME = 'myAssistant.log'
|
__LOG_FILE_NAME = 'myAssistant.log'
|
||||||
__CONFIG_DICT = {}
|
__CONFIG_DICT = {}
|
||||||
|
|
||||||
@@ -29,17 +29,17 @@ class Config:
|
|||||||
def BASE_PATH(self):
|
def BASE_PATH(self):
|
||||||
return self.__BASE_PATH
|
return self.__BASE_PATH
|
||||||
|
|
||||||
def get_scheduler_db_file_path(self):
|
# def get_scheduler_db_file_path(self):
|
||||||
try:
|
# try:
|
||||||
return os.path.join(self.__BASE_PATH, self.__CONFIG_DICT['SCHEDULER_DB_PATH'],
|
# return os.path.join(self.__BASE_PATH, self.__CONFIG_DICT['SCHEDULER_DB_PATH'],
|
||||||
self.__SCHEDULER_DB_FILE_NAME)
|
# self.__SCHEDULER_DB_FILE_NAME)
|
||||||
except:
|
# except:
|
||||||
return os.path.join(self.__CONFIG_PATH, 'schedule_db', self.__SCHEDULER_DB_FILE_NAME)
|
# return os.path.join(self.__CONFIG_PATH, 'schedule_db', self.__SCHEDULER_DB_FILE_NAME)
|
||||||
|
|
||||||
def set_scheduler_db_path(self, new_path):
|
# def set_scheduler_db_path(self, new_path):
|
||||||
self.__CONFIG_DICT['SCHEDULER_DB_PATH'] = new_path
|
# self.__CONFIG_DICT['SCHEDULER_DB_PATH'] = new_path
|
||||||
with open(os.path.join(self.__CONFIG_PATH, self.__CONFIG_NAME), 'w') as f:
|
# with open(os.path.join(self.__CONFIG_PATH, self.__CONFIG_NAME), 'w') as f:
|
||||||
f.write(yaml.safe_dump(self.__CONFIG_DICT, sort_keys=False))
|
# f.write(yaml.safe_dump(self.__CONFIG_DICT, sort_keys=False))
|
||||||
|
|
||||||
def get_log_file_path(self):
|
def get_log_file_path(self):
|
||||||
try:
|
try:
|
||||||
@@ -75,8 +75,7 @@ class Config:
|
|||||||
f.write(yaml.safe_dump(self.__CONFIG_DICT, sort_keys=False))
|
f.write(yaml.safe_dump(self.__CONFIG_DICT, sort_keys=False))
|
||||||
|
|
||||||
def get_plugin_config(self, config_name, config_path):
|
def get_plugin_config(self, config_name, config_path):
|
||||||
print(config_path)
|
|
||||||
if config_path != '':
|
if config_path != '':
|
||||||
with open(os.path.join(config_path, self.__CONFIG_NAME)) as f:
|
with open(os.path.join(config_path, self.__CONFIG_NAME)) as f:
|
||||||
config_d = yaml.safe_load(f)
|
config_d = yaml.safe_load(f)
|
||||||
return config_d[config_name]
|
return config_d[config_name]
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from util.singleton import singleton
|
||||||
|
|
||||||
|
@singleton
|
||||||
class GlobalConfig:
|
class GlobalConfig:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
""" 初始化 """
|
""" 初始化 """
|
||||||
@@ -23,3 +26,6 @@ class GlobalConfig:
|
|||||||
return global_dict[name]
|
return global_dict[name]
|
||||||
except:
|
except:
|
||||||
return defaultvalue
|
return defaultvalue
|
||||||
|
|
||||||
|
def get_globalconfig_key(self):
|
||||||
|
return global_dict.keys()
|
||||||
9
util/singleton.py
Normal file
9
util/singleton.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
def singleton(cls):
|
||||||
|
instances = {}
|
||||||
|
|
||||||
|
def get_instance(*args, **kwargs):
|
||||||
|
if cls not in instances:
|
||||||
|
instances[cls] = cls(*args, **kwargs)
|
||||||
|
return instances[cls]
|
||||||
|
|
||||||
|
return get_instance
|
||||||
Reference in New Issue
Block a user