Изменён парсинг конфига #10

Merged
tema merged 1 commits from testing into master 2023-03-28 10:07:25 +03:00
12 changed files with 76 additions and 92 deletions
Showing only changes of commit 42a0579f2e - Show all commits

10
bot.py
View File

@ -22,11 +22,11 @@ logging.basicConfig(
) )
logger = logging.getLogger("Bot") logger = logging.getLogger("Bot")
WEBAPP_HOST = config.bot("ip") WEBAPP_HOST = config.ip
WEBAPP_PORT = config.bot("port") WEBAPP_PORT = config.port
WEBHOOK_HOST = f'http://{WEBAPP_HOST}:{WEBAPP_PORT}' WEBHOOK_HOST = f'http://{WEBAPP_HOST}:{WEBAPP_PORT}'
WEBHOOK_PATH = f'/bot{config.bot("token")}/' WEBHOOK_PATH = f'/bot{config.token}/'
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}" WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
@ -40,7 +40,7 @@ async def on_shutdown(dp):
def main() -> None: def main() -> None:
if config.logging_user: if config.enable_logging:
logger.info("Logging enabled!") logger.info("Logging enabled!")
else: else:
logger.info("Logging disabled!") logger.info("Logging disabled!")
@ -50,7 +50,7 @@ def main() -> None:
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
loop.create_task(scheduler()) loop.create_task(scheduler())
if config.bot("use_webhook").lower() in ['t', 'true', '1', 'yes', 'y']: if config.use_webhook.lower() in ['t', 'true', '1', 'yes', 'y']:
executor.start_webhook( executor.start_webhook(
dispatcher=dp, dispatcher=dp,
loop=loop, loop=loop,

View File

@ -1,32 +1,28 @@
from configparser import ConfigParser from configparser import ConfigParser
from easydict import EasyDict as edict
from .module import Config
CONFIG_FILE = 'config.ini' CONFIG_FILE = 'config.ini'
class Configure(Config): class Configure:
def __init__(self): def __init__(self):
config = ConfigParser()
self.config = ConfigParser() config.read(CONFIG_FILE)
self.data = dict() self.data = dict()
self.__readconfig()
def __readconfig(self): for section in config.sections():
self.config.read(CONFIG_FILE)
for section in self.config.sections():
self.data[section] = dict() self.data[section] = dict()
for (key, value) in self.config.items(section): for key, value in config.items(section):
self.data[section][key] = value self.data[section][key] = value
def bot(self, key):
return self.data["Bot"][key]
def db(self, key):
return self.data["DataBase"][key]
def anons(self, key): def __getattr__(self, name):
return self.data["announcements"][key] for key in self.data.keys():
if name not in self.data[key]:
continue
return self.data[key][name]
raise NameError("Config options not found!")

View File

@ -1,54 +0,0 @@
class Config():
@property
def config_folder(self):
return self.config.get("Docs_Settings", "Config_folder").rstrip("/")
@property
def documentid(self):
return self.config.get("Docs_Settings", 'Document_ID')
@property
def token_file(self):
file = self.config.get("Docs_Settings", "token_file")
return (self.config_folder + "/" + file)
@property
def data_file(self):
file = self.config.get("Docs_Settings", "data_file")
return (self.config_folder + "/" + file)
@property
def credentials_file(self):
file = self.config.get("Docs_Settings", "credentials_file")
return (self.config_folder + "/" + file)
@property
def allowed_users(self):
usrs = self.config.get("Users", "allowed_users").split(',')
return [int(user_id) for user_id in usrs]
@property
def admin_user(self):
usrs = self.config.get("Users", "admin_users").split(',')
return [int(user_id) for user_id in usrs]
@property
def exclude_send_msg(self):
usrs = self.config.get("Users", "exclude").split(',')
return [int(user_id) for user_id in usrs]
@property
def telegram_bot_api_server(self):
server = self.config.get("Bot", "telegram_bot_api_server")
if str(server).lower() == "none":
return "https://api.telegram.org"
else:
return server
@property
def logging_user(self):
o = self.config.get("DataBase", "enable_logging")
if o.lower() in ['t', "yes", "true"]:
return True
return False

View File

@ -12,4 +12,5 @@ async def errors_handler(update, exception):
if isinstance(exception, MessageNotModified): return True if isinstance(exception, MessageNotModified): return True
await dp.bot.send_message(925150143, f"Exception: {exception}") await dp.bot.send_message(925150143, f"Exception: {exception}")
logging.error(exception)
return True return True

View File

@ -8,6 +8,7 @@ from aiogram.dispatcher.filters import ChatTypeFilter
from load import dp, bot, config from load import dp, bot, config
from database import set_group_settings, get_group from database import set_group_settings, get_group
from parser import get_about_replacements from parser import get_about_replacements
from keyboards.inline.donate import donate
from database import register from database import register
@ -29,7 +30,7 @@ async def set_group(message: types.Message):
@dp.message_handler(ChatTypeFilter(['group', 'supergroup']), commands=['start', 'get']) @dp.message_handler(ChatTypeFilter(['group', 'supergroup']), commands=['start', 'get'])
async def get_replace_on_chat(message: types.Message): async def get_replace_on_chat(message: types.Message):
if config.logging_user: if config.enable_logging:
register( register(
user_id=message.from_user.id, user_id=message.from_user.id,
username=message.from_user.username, username=message.from_user.username,
@ -52,6 +53,7 @@ async def get_replace_on_chat(message: types.Message):
) )
), ),
parse_mode="Markdown", parse_mode="Markdown",
reply_markup=donate
) )
return return
except Exception as e: except Exception as e:

View File

@ -1,3 +1,4 @@
from . import main from . import main
from . import admin from . import admin
from . import timetable from . import timetable
from . import support

View File

@ -4,12 +4,13 @@ import base64
from aiogram import types from aiogram import types
from aiogram.dispatcher.filters import ChatTypeFilter from aiogram.dispatcher.filters import ChatTypeFilter
from aiogram.dispatcher import FSMContext
from load import dp, bot, config from load import dp, bot, config
from keyboards.inline.keyboard import menu from keyboards.inline.keyboard import menu
from parser import get_about_replacements from parser import get_about_replacements
from keyboards.inline.donate import donate from keyboards.inline.donate import donate
if config.logging_user: if config.enable_logging:
from database import register from database import register
@ -27,9 +28,14 @@ async def help_msg(message: types.Message):
) )
@dp.message_handler(ChatTypeFilter(['private']), commands=['start', 'get']) @dp.message_handler(ChatTypeFilter(['private']), commands=['start', 'get'], state="*")
async def get_replace(message: types.Message): async def get_replace(message: types.Message, state: FSMContext):
if config.logging_user: if message.from_user.id in [int(i) for i in config.admin_users.split(',')] and str(message.get_args()).isdigit():
await bot.send_message(message.chat.id, "Напишите ответ")
await state.update_data(u=message.get_args())
await state.set_state(state="answer_support")
return
if config.enable_logging:
register( register(
user_id=message.from_user.id, user_id=message.from_user.id,
username=message.from_user.username, username=message.from_user.username,

View File

@ -0,0 +1,20 @@
from aiogram import types
from load import dp, bot, config
from keyboards.inline.support import answer_kb
@dp.message_handler(commands="feedback", state='*')
async def feedback(message: types.Message, state):
await bot.send_message(message.chat.id, "Напишіть ваше повідомлення!")
await state.set_state(state="wait_for_support_message")
@dp.message_handler(state="wait_for_support_message")
async def send_admins(message: types.Message, state):
await message.copy_to(config.chat_id, reply_markup=await answer_kb(message.from_user.id))
@dp.message_handler(state="answer_support")
async def send_answer(message: types.Message, state):
data = await state.get_data()
await message.copy_to(data["u"])
await state.finish()

View File

@ -0,0 +1,10 @@
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from load import bot
async def answer_kb(user_id):
me = await bot.get_me()
kb = InlineKeyboardMarkup()
kb.add(InlineKeyboardButton("Answer", url="https://t.me/{me}?start={user_id}"
.format(me=me.username, user_id=user_id)))
return kb

View File

@ -1,5 +1,6 @@
from aiogram import Dispatcher, Bot from aiogram import Dispatcher, Bot
from aiogram.bot.api import TelegramAPIServer from aiogram.bot.api import TelegramAPIServer
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from playhouse.db_url import connect from playhouse.db_url import connect
from configs import Configure from configs import Configure
@ -7,10 +8,11 @@ from configs import Configure
config = Configure() config = Configure()
db = connect(config.db("db_link")) db = connect(config.db_link)
bot = Bot( bot = Bot(
token=config.bot("token"), token=config.token,
server=TelegramAPIServer.from_base(config.telegram_bot_api_server) server=TelegramAPIServer.from_base(config.telegram_bot_api_server)
) )
dp = Dispatcher(bot) storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

View File

@ -39,7 +39,7 @@ def docs_parse():
"another_teacher":None "another_teacher":None
} }
page = requests.get(config.bot("link"), headers=headers) page = requests.get(config.link, headers=headers)
page.encoding = 'utf-8' page.encoding = 'utf-8'
soup = BeautifulSoup(page.text, "lxml") soup = BeautifulSoup(page.text, "lxml")

View File

@ -14,15 +14,15 @@ async def announce():
docs_parse() docs_parse()
except Exception: except Exception:
message = "Ошибка обновления данных!" message = "Ошибка обновления данных!"
if config.admin_user is not None: if config.admin_users.split(',') is not None:
for user_id in config.admin_user: for user_id in config.admin_users.split(','):
if user_id in config.exclude_send_msg: if user_id in config.exclude:
continue continue
await dp.bot.send_message(user_id, message) await dp.bot.send_message(user_id, message)
async def scheduler(): async def scheduler():
schedule.every(int(config.anons('time'))).seconds.do(announce) schedule.every(int(config.time)).seconds.do(announce)
while True: while True:
await schedule.run_pending() await schedule.run_pending()