This commit is contained in:
udf 2018-04-08 16:54:34 +02:00
commit 9a2c91160e
5 changed files with 31 additions and 15 deletions

View File

@ -17,11 +17,13 @@ async def get_target_message(event):
if message.out: if message.out:
return message return message
async def await_read(chat, message): async def await_read(chat, message):
chat = telethon.utils.get_peer_id(chat) chat = telethon.utils.get_peer_id(chat)
async def read_filter(read_event): async def read_filter(read_event):
return telethon.utils.get_peer_id(await read_event.input_chat) == chat \ return (telethon.utils.get_peer_id(await read_event.input_chat) == chat
and read_event.is_read(message) and read_event.is_read(message))
fut = borg.await_event(events.MessageRead(inbox=False), read_filter) fut = borg.await_event(events.MessageRead(inbox=False), read_filter)
if await util.is_read(borg, chat, message): if await util.is_read(borg, chat, message):
@ -30,6 +32,7 @@ async def await_read(chat, message):
await fut await fut
@borg.on(util.admin_cmd(r"^\.(del)(?:ete)?$")) @borg.on(util.admin_cmd(r"^\.(del)(?:ete)?$"))
@borg.on(util.admin_cmd(r"^\.(edit)(.*)$")) @borg.on(util.admin_cmd(r"^\.(edit)(.*)$"))
async def delete(event): async def delete(event):

View File

@ -9,6 +9,7 @@ from uniborg import util
DELETE_TIMEOUT = 2 DELETE_TIMEOUT = 2
@borg.on(util.admin_cmd(r"^\.load (?P<shortname>\w+)$")) @borg.on(util.admin_cmd(r"^\.load (?P<shortname>\w+)$"))
async def load_reload(event): async def load_reload(event):
await event.delete() await event.delete()
@ -19,7 +20,8 @@ async def load_reload(event):
borg.remove_plugin(shortname) borg.remove_plugin(shortname)
borg.load_plugin(shortname) borg.load_plugin(shortname)
msg = await event.respond(f"Successfully (re)loaded plugin {shortname}") msg = await event.respond(
f"Successfully (re)loaded plugin {shortname}")
await asyncio.sleep(DELETE_TIMEOUT) await asyncio.sleep(DELETE_TIMEOUT)
await borg.delete_messages(msg.to_id, msg) await borg.delete_messages(msg.to_id, msg)
@ -28,6 +30,7 @@ async def load_reload(event):
logger.warn(f"Failed to (re)load plugin {shortname}: {tb}") logger.warn(f"Failed to (re)load plugin {shortname}: {tb}")
await event.respond(f"Failed to (re)load plugin {shortname}: {e}") await event.respond(f"Failed to (re)load plugin {shortname}: {e}")
@borg.on(util.admin_cmd(r"^\.remove (?P<shortname>\w+)$")) @borg.on(util.admin_cmd(r"^\.remove (?P<shortname>\w+)$"))
async def remove(event): async def remove(event):
await event.delete() await event.delete()

View File

@ -2,6 +2,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this # 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/. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
class ReverseList(list): class ReverseList(list):
def __iter__(self): def __iter__(self):
return reversed(self) return reversed(self)

View File

@ -9,19 +9,24 @@ from pathlib import Path
from telethon import TelegramClient from telethon import TelegramClient
import telethon.utils import telethon.utils
import telethon.events
from . import hacks from . import hacks
class Uniborg(TelegramClient): class Uniborg(TelegramClient):
def __init__(self, session, *, plugin_path="plugins", **kwargs): def __init__(
self, session, *, plugin_path="plugins",
bot_token=None, **kwargs):
# TODO: handle non-string session # TODO: handle non-string session
self._name = session self._name = session
self._logger = logging.getLogger(session) self._logger = logging.getLogger(session)
self._plugins = {} self._plugins = {}
self._plugin_path = plugin_path self._plugin_path = plugin_path
super().__init__(session, super().__init__(
17349, "344583e45741c457fe1862106095a5eb", # yarr session,
17349, "344583e45741c457fe1862106095a5eb", # yarr
**kwargs) **kwargs)
# This is a hack, please avert your eyes # This is a hack, please avert your eyes
@ -29,7 +34,7 @@ class Uniborg(TelegramClient):
# precedence # precedence
self._event_builders = hacks.ReverseList() self._event_builders = hacks.ReverseList()
self._loop.run_until_complete(self._async_init()) self._loop.run_until_complete(self._async_init(bot_token=bot_token))
core_plugin = Path(__file__).parent / "_core.py" core_plugin = Path(__file__).parent / "_core.py"
self.load_plugin_from_file(core_plugin) self.load_plugin_from_file(core_plugin)
@ -37,8 +42,8 @@ class Uniborg(TelegramClient):
for p in Path().glob(f"{self._plugin_path}/*.py"): for p in Path().glob(f"{self._plugin_path}/*.py"):
self.load_plugin_from_file(p) self.load_plugin_from_file(p)
async def _async_init(self): async def _async_init(self, **kwargs):
await self.start() await self.start(**kwargs)
self.me = await self.get_me() self.me = await self.get_me()
self.uid = telethon.utils.get_peer_id(self.me) self.uid = telethon.utils.get_peer_id(self.me)
@ -84,8 +89,9 @@ class Uniborg(TelegramClient):
async def cb(event): async def cb(event):
if filter is None or await filter(event): if filter is None or await filter(event):
fut.set_result(event) fut.set_result(event)
raise telethon.events.StopPropagation
fut.add_done_callback(lambda _: fut.add_done_callback(
self.remove_event_handler(cb, event_matcher)) lambda _: self.remove_event_handler(cb, event_matcher))
return fut return fut

View File

@ -7,20 +7,23 @@ import re
from telethon import events from telethon import events
from telethon.tl.functions.messages import GetPeerDialogsRequest from telethon.tl.functions.messages import GetPeerDialogsRequest
def admin_cmd(pattern): def admin_cmd(pattern):
return events.NewMessage(outgoing=True, pattern=re.compile(pattern)) return events.NewMessage(outgoing=True, pattern=re.compile(pattern))
async def is_read(borg, entity, message, is_out=None): async def is_read(borg, entity, message, is_out=None):
""" """
Returns True if the given message (or id) has been read Returns True if the given message (or id) has been read
if a id is given, is_out needs to be a bool if a id is given, is_out needs to be a bool
""" """
is_out = getattr(message, 'out', is_out) is_out = getattr(message, "out", is_out)
if not isinstance(is_out, bool): if not isinstance(is_out, bool):
raise ValueError('Message was id but is_out not provided or not a bool') raise ValueError(
message_id = getattr(message, 'id', message) "Message was id but is_out not provided or not a bool")
message_id = getattr(message, "id", message)
if not isinstance(message_id, int): if not isinstance(message_id, int):
raise ValueError('Failed to extract id from message') raise ValueError("Failed to extract id from message")
dialog = (await borg(GetPeerDialogsRequest([entity]))).dialogs[0] dialog = (await borg(GetPeerDialogsRequest([entity]))).dialogs[0]
max_id = dialog.read_outbox_max_id if is_out else dialog.read_inbox_max_id max_id = dialog.read_outbox_max_id if is_out else dialog.read_inbox_max_id