Compare commits

..

35 Commits

Author SHA1 Message Date
udf 27d7b5ed82
Merge branch 'master' of https://git.togrand.xyz/uniborg/uniborg 2019-09-09 09:35:39 +02:00
Dan Elkouby 9fe2e80742 Count messages and sort by top posters 2019-09-07 08:08:07 +00:00
Dan Elkouby 40c398833d Add member list command 2019-09-07 07:31:43 +00:00
Lonami 332ecdcaea Escape display name in who 2019-09-03 21:50:39 +02:00
Lonami 69ccfd1207 Add license verbatim 2019-06-08 10:18:28 +02:00
Lonami 6d67ebad06 Dab *has* to be a standard plugin 2019-06-08 10:15:51 +02:00
Lonami 1dd6e63d6a Use HTML in who 2019-05-20 09:53:16 +02:00
kate fe6b878064 Fix info formatting in some cases (#8) 2019-05-19 23:10:01 +02:00
udf 573f36bf57
fix broken indentation when lots of nested items are present 2019-05-19 23:00:23 +02:00
udf b21f5ec104
Fix trailing whitespaces
kate you're better than this
2019-05-19 22:59:43 +02:00
Lonami 168ee165b9 await the now async remove_plugin 2019-04-30 20:44:08 +02:00
Lonami 93cbb44459 Make unload_plugin async for reasons 2019-04-30 20:42:32 +02:00
Lonami febe3c4bac Be more careful when unloading plugin 2019-04-30 20:34:05 +02:00
Lonami c8b5179cb5 Allow plugins to define an unload function 2019-04-30 20:32:35 +02:00
Dan Elkouby c2197e5280 Disable markdown in sed 2019-04-27 10:22:36 +00:00
Dan Elkouby ca5619b9cc Add fpost plugin 2019-03-31 21:58:32 +00:00
Lonami b4be66162e Fix fixreply on different chats 2019-03-04 08:05:40 +01:00
Lonami Exo 59a0ebe9dc Add fixreply plugin 2019-02-27 13:20:24 +01:00
Dan Elkouby 88a8b4e0d3 Add a timeout for sed 2019-02-26 22:27:01 +00:00
Dan Elkouby a53b5fb147 Revert "s/regex/re/g"
This reverts commit dc2eefd581.
2019-02-26 21:10:21 +00:00
Lonami dc2eefd581 s/regex/re/g 2019-02-26 18:52:57 +01:00
Lonami 84e3c4bef8 Support enclosing circle in markdown 2019-02-21 13:22:49 +01:00
Dan Elkouby d274f79d87 Allow sending a snippet with ! 2019-02-18 17:44:42 +00:00
Lonami 03e922ed86 Don't save unexisting snips on .snip 2018-12-28 22:27:41 +01:00
Lonami 319eb84c5a File reference 2018-12-26 22:10:02 +01:00
Lonami a254c113a7 Fix markdown parse edge case 2018-12-21 18:25:16 +00:00
Lonami c41792af6b Simplify aesthetify 2018-12-19 14:58:49 +00:00
Lonami facd436014 Strikethrough support in markdown 2018-12-19 14:52:13 +00:00
Lonami 2c75fb25a3 Support .reload to reload commands 2018-12-19 15:50:12 +01:00
Lonami ca7b636696 Merge branch 'ninja_fix' of kate/uniborg into master 2018-12-18 00:02:40 +01:00
Lonami f46a08adf1 Merge branch 'master' of kate/uniborg into master 2018-12-18 00:01:45 +01:00
Lonami c35dcbf26d
Simplify code
(cherry picked from commit 2a5e9aac94)
2018-12-18 00:53:59 +02:00
Lonami 5438f95f34 Actually write the method name to mkdir on storage 2018-12-17 17:55:53 +01:00
udf 74f0cea230
Fix ninja in saved messages
I'm not sure why you'd use ninja in your own chat, but it shouldn't raise anyways.
2018-11-21 23:24:33 +02:00
Dan Elkouby d5f70423a3 stdplugins/who: link user by ID 2018-11-08 11:00:19 +00:00
13 changed files with 230 additions and 59 deletions

27
stdplugins/fixreply.py Normal file
View File

@ -0,0 +1,27 @@
# 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
from telethon import events
_last_messages = {}
@borg.on(events.NewMessage(outgoing=True))
async def _(event):
_last_messages[event.chat_id] = event.message
@borg.on(events.NewMessage(pattern=r"\.(fix)?reply", outgoing=True))
async def _(event):
if not event.is_reply or event.chat_id not in _last_messages:
return
message = _last_messages[event.chat_id]
chat = await event.get_input_chat()
await asyncio.wait([
borg.delete_messages(chat, [event.id, message.id]),
borg.send_message(chat, message, reply_to=event.reply_to_msg_id)
])

27
stdplugins/fpost.py Normal file
View File

@ -0,0 +1,27 @@
# 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 string
from telethon import events
from telethon.tl import types
msg_cache = {}
@borg.on(events.NewMessage(pattern=r"\.fpost\s+(.*)", outgoing=True))
async def _(event):
await event.delete()
text = event.pattern_match.group(1)
destination = await event.get_input_chat()
for c in text.lower():
if c not in string.ascii_lowercase:
continue
if c not in msg_cache:
async for msg in borg.iter_messages(None, search=c):
if msg.raw_text.lower() == c and msg.media is None:
msg_cache[c] = msg
break
await borg.forward_messages(destination, msg_cache[c])

View File

@ -37,7 +37,7 @@ def yaml_format(obj, indent=0):
has_multiple_items = len(items) > 2
if has_multiple_items:
result.append('\n')
indent += 2
indent += 2
for k, v in items:
if k == '_' or v is None:
continue
@ -45,11 +45,14 @@ def yaml_format(obj, indent=0):
if not formatted.strip():
continue
result.append(' ' * (indent if has_multiple_items else 1))
result.append(f'{k}: {formatted}')
result.append(f'{k}:')
if not formatted[0].isspace():
result.append(' ')
result.append(f'{formatted}')
result.append('\n')
result.pop()
indent -= 2
result.append(' ' * indent)
if has_multiple_items:
indent -= 2
elif isinstance(obj, str):
# truncate long strings and display elipsis
result = repr(obj[:STR_LEN_MAX])
@ -75,7 +78,6 @@ def yaml_format(obj, indent=0):
result.append('\n')
result.pop()
indent -= 2
result.append(' ' * indent)
else:
return repr(obj)

View File

@ -31,19 +31,26 @@ def get_tag_parser(tag, entity):
return re.compile(tag + r'(.+?)' + tag, re.DOTALL), tag_parser
PRINTABLE_ASCII = range(0x21, 0x7f)
def parse_aesthetics(m):
def aesthetify(string):
for c in string:
c = ord(c)
if c in PRINTABLE_ASCII:
c += 0xFF00 - 0x20
elif c == ord(" "):
c = 0x3000
yield chr(c)
if " " < c <= "~":
yield chr(ord(c) + 0xFF00 - 0x20)
elif c == " ":
yield "\u3000"
else:
yield c
return "".join(aesthetify(m[1])), None
def parse_strikethrough(m):
return ("\u0336".join(m[1]) + "\u0336"), None
def parse_enclosing_circle(m):
return ("\u20e0".join(m[1]) + "\u20e0"), None
def parse_subreddit(m):
text = '/' + m.group(3)
entity = MessageEntityTextUrl(
@ -78,6 +85,8 @@ MATCHERS = [
(get_tag_parser('```', partial(MessageEntityPre, language=''))),
(get_tag_parser('`', MessageEntityCode)),
(re.compile(r'\+\+(.+?)\+\+'), parse_aesthetics),
(re.compile(r'~~(.+?)~~'), parse_strikethrough),
(re.compile(r'@@(.+?)@@'), parse_enclosing_circle),
(re.compile(r'([^/\w]|^)(/?(r/\w+))'), parse_subreddit),
(re.compile(r'(!\w+)'), parse_snip)
]
@ -98,6 +107,8 @@ def parse(message, old_entities=None):
# Skip already existing entities if we're at one
if i == e.offset:
i += e.length
else:
after += 1
# Find the first pattern that matches
for pattern, parser in MATCHERS:

View File

@ -5,6 +5,7 @@
import asyncio
from telethon import events
from telethon.tl.types import InputPeerSelf
import telethon.utils
from uniborg import util
@ -20,6 +21,8 @@ async def get_target_message(event):
async def await_read(chat, message):
if isinstance(chat, InputPeerSelf):
return
chat = telethon.utils.get_peer_id(chat)
async def read_filter(read_event):

View File

@ -0,0 +1,43 @@
# 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 random
from telethon import events, types, functions, utils
def choser(cmd, pack, blacklist={}):
docs = None
@borg.on(events.NewMessage(pattern=rf'\.{cmd}', outgoing=True))
async def handler(event):
await event.delete()
nonlocal docs
if docs is None:
docs = [
utils.get_input_document(x)
for x in (await borg(functions.messages.GetStickerSetRequest(types.InputStickerSetShortName(pack)))).documents
if x.id not in blacklist
]
await event.respond(file=random.choice(docs))
choser('brain', 'supermind')
choser('dab', 'DabOnHaters', {
1653974154589768377,
1653974154589768312,
1653974154589767857,
1653974154589768311,
1653974154589767816,
1653974154589767939,
1653974154589767944,
1653974154589767912,
1653974154589767911,
1653974154589767910,
1653974154589767909,
1653974154589767863,
1653974154589767852,
1653974154589768677
})

View File

@ -5,6 +5,8 @@ import regex
from telethon import events, utils
from telethon.tl import types, functions
from uniborg import util
HEADER = "「sed」\n"
KNOWN_RE_BOTS = re.compile(
r'(regex|moku|BananaButler_|rgx|l4mR)bot',
@ -17,6 +19,7 @@ KNOWN_RE_BOTS = re.compile(
last_msgs = defaultdict(lambda: deque(maxlen=10))
@util.sync_timeout(1)
def doit(chat_id, match, original):
fr = match.group(1)
to = match.group(2)
@ -100,7 +103,7 @@ async def on_regex(event):
if m is not None:
s = f"{HEADER}{s}"
out = await borg.send_message(
await event.get_input_chat(), s, reply_to=m.id
await event.get_input_chat(), s, reply_to=m.id, parse_mode=None
)
last_msgs[chat_id].appendleft(out)
elif s is not None:

View File

@ -1,9 +1,11 @@
# 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
from telethon import events, utils
from telethon.tl import types
loop = asyncio.get_event_loop()
TYPE_TEXT = 0
TYPE_PHOTO = 1
@ -14,70 +16,69 @@ TYPE_DOCUMENT = 2
snips = storage.snips or {}
@borg.on(events.NewMessage(pattern=r'\.snip (\S+)', outgoing=True))
@borg.on(events.NewMessage(pattern=r'(?:\.snip +|!)(\w+)$', outgoing=True))
async def on_snip(event):
loop.create_task(event.delete())
name = event.pattern_match.group(1)
if name not in snips:
await on_snip_save(event)
return
snip = snips[name]
if snip['type'] == TYPE_PHOTO:
media = types.InputPhoto(snip['id'], snip['hash'], file_reference=b'')
elif snip['type'] == TYPE_DOCUMENT:
media = types.InputDocument(snip['id'], snip['hash'], file_reference=b'')
else:
snip = snips[name]
if snip['type'] == TYPE_PHOTO:
media = types.InputPhoto(snip['id'], snip['hash'])
elif snip['type'] == TYPE_DOCUMENT:
media = types.InputDocument(snip['id'], snip['hash'])
else:
media = None
media = None
await borg.send_message(await event.get_input_chat(), snip['text'],
file=media,
reply_to=event.message.reply_to_msg_id)
await event.delete()
await borg.send_message(await event.get_input_chat(), snip['text'],
file=media,
reply_to=event.message.reply_to_msg_id)
@borg.on(events.NewMessage(pattern=r'\.snips (\S+)', outgoing=True))
async def on_snip_save(event):
loop.create_task(event.delete())
name = event.pattern_match.group(1)
msg = await event.get_reply_message()
if msg:
snips.pop(name, None)
snip = {'type': TYPE_TEXT, 'text': msg.message or ''}
if msg.media:
media = None
if isinstance(msg.media, types.MessageMediaPhoto):
media = utils.get_input_photo(msg.media.photo)
snip['type'] = TYPE_PHOTO
elif isinstance(msg.media, types.MessageMediaDocument):
media = utils.get_input_document(msg.media.document)
snip['type'] = TYPE_DOCUMENT
if media:
snip['id'] = media.id
snip['hash'] = media.access_hash
if not msg:
return
snips[name] = snip
storage.snips = snips
snips.pop(name, None)
snip = {'type': TYPE_TEXT, 'text': msg.message or ''}
if msg.media:
media = None
if isinstance(msg.media, types.MessageMediaPhoto):
media = utils.get_input_photo(msg.media.photo)
snip['type'] = TYPE_PHOTO
elif isinstance(msg.media, types.MessageMediaDocument):
media = utils.get_input_document(msg.media.document)
snip['type'] = TYPE_DOCUMENT
if media:
snip['id'] = media.id
snip['hash'] = media.access_hash
await event.delete()
snips[name] = snip
storage.snips = snips
@borg.on(events.NewMessage(pattern=r'\.snipl', outgoing=True))
async def on_snip_list(event):
loop.create_task(event.delete())
await event.respond('available snips: ' + ', '.join(snips.keys()))
await event.delete()
@borg.on(events.NewMessage(pattern=r'\.snipd (\S+)', outgoing=True))
async def on_snip_delete(event):
loop.create_task(event.delete())
snips.pop(event.pattern_match.group(1), None)
storage.snips = snips
await event.delete()
@borg.on(events.NewMessage(pattern=r'\.snipr (\S+)\s+(\S+)', outgoing=True))
async def on_snip_rename(event):
loop.create_task(event.delete())
snip = snips.pop(event.pattern_match.group(1), None)
if snip:
snips[event.pattern_match.group(2)] = snip
storage.snips = snips
await event.delete()

View File

@ -1,12 +1,21 @@
# 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 html
from telethon import events
from telethon import utils
from telethon.tl import types
def get_who_string(who):
who_string = html.escape(utils.get_display_name(who))
if isinstance(who, (types.User, types.Channel)) and who.username:
who_string += f" <i>(@{who.username})</i>"
who_string += f", <a href='tg://user?id={who.id}'>#{who.id}</a>"
return who_string
@borg.on(events.NewMessage(pattern=r"\.who", outgoing=True))
async def _(event):
if not event.message.is_reply:
@ -14,14 +23,30 @@ async def _(event):
else:
msg = await event.message.get_reply_message()
if msg.forward:
# FIXME forward privacy memes
who = await borg.get_entity(
msg.forward.from_id or msg.forward.channel_id)
else:
who = await msg.get_sender()
who_string = utils.get_display_name(who)
if isinstance(who, (types.User, types.Channel)) and who.username:
who_string += f" (@{who.username})"
who_string += f", #{who.id}"
await event.edit(get_who_string(who), parse_mode='html')
await event.edit(who_string)
@borg.on(events.NewMessage(pattern=r"\.members", outgoing=True))
async def _(event):
members = []
async for member in borg.iter_participants(event.chat_id):
messages = await borg.get_messages(
event.chat_id,
from_user=member,
limit=0
)
members.append((
messages.total,
f"{messages.total} - {get_who_string(member)}"
))
members = (
m[1] for m in sorted(members, key=lambda m: m[0], reverse=True)
)
await event.edit("\n".join(members), parse_mode='html')

View File

@ -10,14 +10,14 @@ from uniborg import util
DELETE_TIMEOUT = 2
@borg.on(util.admin_cmd(r"^\.load (?P<shortname>\w+)$"))
@borg.on(util.admin_cmd(r"^\.(?:re)?load (?P<shortname>\w+)$"))
async def load_reload(event):
await event.delete()
shortname = event.pattern_match["shortname"]
try:
if shortname in borg._plugins:
borg.remove_plugin(shortname)
await borg.remove_plugin(shortname)
borg.load_plugin(shortname)
msg = await event.respond(
@ -39,7 +39,7 @@ async def remove(event):
if shortname == "_core":
msg = await event.respond(f"Not removing {shortname}")
elif shortname in borg._plugins:
borg.remove_plugin(shortname)
await borg.remove_plugin(shortname)
msg = await event.respond(f"Removed plugin {shortname}")
else:
msg = await event.respond(f"Plugin {shortname} is not loaded")

View File

@ -48,6 +48,6 @@ class Storage:
def _save(self):
if not self._root.is_dir():
self._root(parents=True, exist_ok=True)
self._root.mkdir(parents=True, exist_ok=True)
with open(self._root / FILE_NAME, 'w') as fp:
json.dump(self._data, fp)

View File

@ -3,6 +3,7 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import asyncio
import importlib.util
import inspect
import logging
from pathlib import Path
@ -71,7 +72,7 @@ class Uniborg(TelegramClient):
self._plugins[shortname] = mod
self._logger.info(f"Successfully loaded plugin {shortname}")
def remove_plugin(self, shortname):
async def remove_plugin(self, shortname):
name = self._plugins[shortname].__name__
for i in reversed(range(len(self._event_builders))):
@ -79,7 +80,16 @@ class Uniborg(TelegramClient):
if cb.__module__ == name:
del self._event_builders[i]
del self._plugins[shortname]
plugin = self._plugins.pop(shortname)
if callable(getattr(plugin, 'unload', None)):
try:
unload = plugin.unload()
if inspect.isawaitable(unload):
await unload
except Exception:
self._logger.exception(f'Unhandled exception unloading {shortname}')
del plugin
self._logger.info(f"Removed plugin {shortname}")
def await_event(self, event_matcher, filter=None):

View File

@ -2,7 +2,9 @@
# 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 functools
import re
import signal
from telethon import events
from telethon.tl.functions.messages import GetPeerDialogsRequest
@ -28,3 +30,20 @@ async def is_read(borg, entity, message, is_out=None):
dialog = (await borg(GetPeerDialogsRequest([entity]))).dialogs[0]
max_id = dialog.read_outbox_max_id if is_out else dialog.read_inbox_max_id
return message_id <= max_id
def _handle_timeout(signum, frame):
raise TimeoutError("Execution took too long")
def sync_timeout(seconds):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.setitimer(signal.ITIMER_REAL, seconds)
try:
r = func(*args, **kwargs)
finally:
signal.alarm(0)
return r
return wrapper
return decorator