uniborg/uniborg/uniborg.py

101 lines
3.3 KiB
Python
Raw Normal View History

2018-04-06 15:47:57 +00:00
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import asyncio
2018-04-07 20:20:16 +00:00
import importlib.util
2018-04-06 15:47:57 +00:00
import logging
2018-04-07 20:20:16 +00:00
from pathlib import Path
2018-04-06 15:47:57 +00:00
from telethon import TelegramClient
import telethon.utils
2018-04-08 13:09:57 +00:00
import telethon.events
2018-04-06 15:47:57 +00:00
from .storage import Storage
2018-04-07 20:20:16 +00:00
from . import hacks
2018-04-08 14:44:09 +00:00
2018-04-06 15:47:57 +00:00
class Uniborg(TelegramClient):
2018-04-08 14:44:09 +00:00
def __init__(
self, session, *, plugin_path="plugins", storage=None,
2018-04-08 14:44:09 +00:00
bot_token=None, **kwargs):
2018-04-07 20:20:16 +00:00
# TODO: handle non-string session
#
# storage should be a callable accepting plugin name -> Storage object.
# This means that using the Storage type as a storage would work too.
2018-04-07 20:20:16 +00:00
self._name = session
2018-06-10 08:06:56 +00:00
self.storage = storage or (lambda n: Storage(Path("data") / n))
2018-04-07 20:20:16 +00:00
self._logger = logging.getLogger(session)
self._plugins = {}
self._plugin_path = plugin_path
2018-04-06 15:47:57 +00:00
2018-06-10 08:13:23 +00:00
kwargs = {
2018-06-10 17:12:53 +00:00
"api_id": 6, "api_hash": "eb06d4abfb49dc3eeb1aeb98ae0f581e",
**kwargs}
2018-06-10 08:13:23 +00:00
super().__init__(session, **kwargs)
2018-04-06 15:47:57 +00:00
2018-04-07 20:20:16 +00:00
# This is a hack, please avert your eyes
# We want this in order for the most recently added handler to take
# precedence
self._event_builders = hacks.ReverseList()
2018-06-14 21:09:25 +00:00
self.loop.run_until_complete(self._async_init(bot_token=bot_token))
2018-04-07 20:20:16 +00:00
core_plugin = Path(__file__).parent / "_core.py"
self.load_plugin_from_file(core_plugin)
2018-04-06 15:47:57 +00:00
2018-04-07 20:20:16 +00:00
for p in Path().glob(f"{self._plugin_path}/*.py"):
self.load_plugin_from_file(p)
2018-04-08 14:30:50 +00:00
async def _async_init(self, **kwargs):
await self.start(**kwargs)
2018-04-06 15:47:57 +00:00
2018-04-08 12:43:51 +00:00
self.me = await self.get_me()
self.uid = telethon.utils.get_peer_id(self.me)
2018-04-06 15:47:57 +00:00
2018-04-07 20:20:16 +00:00
def load_plugin(self, shortname):
self.load_plugin_from_file(f"{self._plugin_path}/{shortname}.py")
def load_plugin_from_file(self, path):
path = Path(path)
shortname = path.stem
name = f"_UniborgPlugins.{self._name}.{shortname}"
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
mod.borg = self
mod.logger = logging.getLogger(shortname)
mod.storage = self.storage(f"{self._name}/{shortname}")
2018-04-07 20:20:16 +00:00
spec.loader.exec_module(mod)
self._plugins[shortname] = mod
self._logger.info(f"Successfully loaded plugin {shortname}")
def remove_plugin(self, shortname):
name = self._plugins[shortname].__name__
2018-05-05 13:03:49 +00:00
for i in reversed(range(len(self._event_builders))):
ev, cb = self._event_builders[i]
if cb.__module__ == name:
del self._event_builders[i]
del self._plugins[shortname]
self._logger.info(f"Removed plugin {shortname}")
2018-04-08 12:42:31 +00:00
def await_event(self, event_matcher, filter=None):
fut = asyncio.Future()
@self.on(event_matcher)
async def cb(event):
try:
if filter is None or await filter(event):
fut.set_result(event)
except telethon.events.StopPropagation:
2018-04-08 12:42:31 +00:00
fut.set_result(event)
raise
2018-04-08 12:42:31 +00:00
2018-04-08 14:44:09 +00:00
fut.add_done_callback(
2018-06-10 17:12:53 +00:00
lambda _: self.remove_event_handler(cb, event_matcher))
2018-04-08 12:42:31 +00:00
return fut