Unverified Commit 6e13b8b7 authored by mathieui's avatar mathieui

yapf -rip on plugins

parent d1b62475
......@@ -50,11 +50,11 @@ For affiliations
"""
from poezio.plugin import BasePlugin
from poezio.tabs import MucTab
from poezio.core.structs import Completion
class Plugin(BasePlugin):
"""
Adds several convenient aliases to /affiliation and /role:
......@@ -66,48 +66,66 @@ class Plugin(BasePlugin):
/admin
/noaffiliation
"""
def init(self):
for role in ('visitor', 'participant' , 'moderator'):
self.api.add_tab_command(MucTab, role, self.role(role),
help='Set the role of a nick to %s' % role,
usage= '<nick>',
short='Set the role to %s' % role,
completion=self.complete_nick)
for role in ('visitor', 'participant', 'moderator'):
self.api.add_tab_command(
MucTab,
role,
self.role(role),
help='Set the role of a nick to %s' % role,
usage='<nick>',
short='Set the role to %s' % role,
completion=self.complete_nick)
for aff in ('member', 'owner', 'admin'):
self.api.add_tab_command(MucTab, aff, self.affiliation(aff),
usage='<nick>',
help='Set the affiliation of a nick to %s' % aff,
short='Set the affiliation to %s' % aff,
completion=self.complete_nick)
self.api.add_tab_command(MucTab, 'noaffiliation', self.affiliation('none'),
usage='<nick>',
help='Set the affiliation of a nick to none.',
short='Set the affiliation to none.',
completion=self.complete_nick)
self.api.add_tab_command(MucTab, 'voice', self.affiliation('member'),
usage='<nick>',
help='Set the affiliation of a nick to member.',
short='Set the affiliation to member.',
completion=self.complete_nick)
self.api.add_tab_command(MucTab, 'op', self.role('moderator'),
usage='<nick>',
help='Set the role of a nick to moderator.',
short='Set the role to moderator.',
completion=self.complete_nick)
self.api.add_tab_command(MucTab, 'mute', self.role('visitor'),
usage='<nick>',
help='Set the role of a nick to visitor.',
short='Set the role to visitor.',
completion=self.complete_nick)
self.api.add_tab_command(
MucTab,
aff,
self.affiliation(aff),
usage='<nick>',
help='Set the affiliation of a nick to %s' % aff,
short='Set the affiliation to %s' % aff,
completion=self.complete_nick)
self.api.add_tab_command(
MucTab,
'noaffiliation',
self.affiliation('none'),
usage='<nick>',
help='Set the affiliation of a nick to none.',
short='Set the affiliation to none.',
completion=self.complete_nick)
self.api.add_tab_command(
MucTab,
'voice',
self.affiliation('member'),
usage='<nick>',
help='Set the affiliation of a nick to member.',
short='Set the affiliation to member.',
completion=self.complete_nick)
self.api.add_tab_command(
MucTab,
'op',
self.role('moderator'),
usage='<nick>',
help='Set the role of a nick to moderator.',
short='Set the role to moderator.',
completion=self.complete_nick)
self.api.add_tab_command(
MucTab,
'mute',
self.role('visitor'),
usage='<nick>',
help='Set the role of a nick to visitor.',
short='Set the role to visitor.',
completion=self.complete_nick)
def role(self, role):
return lambda args: self.api.current_tab().command_role(args+' '+role)
return lambda args: self.api.current_tab().command_role(args + ' ' + role)
def affiliation(self, affiliation):
return lambda args: self.api.current_tab().command_affiliation(
args+' '+affiliation)
return lambda args: self.api.current_tab().command_affiliation(args + ' ' + affiliation)
def complete_nick(self, the_input):
tab = self.api.current_tab()
......@@ -115,6 +133,3 @@ class Plugin(BasePlugin):
word_list = [user.nick for user in sorted(tab.users, key=compare_users, reverse=True)\
if user.nick != tab.own_nick]
return Completion(the_input.auto_completion, word_list, '')
......@@ -71,15 +71,19 @@ from poezio.core.structs import Completion
class Plugin(BasePlugin):
def init(self):
self.api.add_command('alias', self.command_alias,
usage='<alias> <command> [args]',
short='Create an alias command',
help='Create an alias for <command> with [args].')
self.api.add_command('unalias', self.command_unalias,
usage='<alias>',
help='Remove a previously created alias',
short='Remove an alias',
completion=self.completion_unalias)
self.api.add_command(
'alias',
self.command_alias,
usage='<alias> <command> [args]',
short='Create an alias command',
help='Create an alias for <command> with [args].')
self.api.add_command(
'unalias',
self.command_unalias,
usage='<alias>',
help='Remove a previously created alias',
short='Remove an alias',
completion=self.completion_unalias)
self.commands = {}
self.load_conf()
......@@ -114,18 +118,18 @@ class Plugin(BasePlugin):
self.config.set(alias, command + ' ' + args)
self.commands[alias] = command_wrapper(
generic_command, lambda: self.get_command(command), args)
generic_command, lambda: self.get_command(command), args)
self.api.del_command(alias)
self.api.add_command(alias, self.commands[alias],
'This command is an alias for /%s %s' %
(alias, command))
self.api.add_command(
alias, self.commands[alias],
'This command is an alias for /%s %s' % (alias, command))
if not silent:
if update:
self.api.information('Alias /%s updated' % alias, 'Info')
else:
self.api.information('Alias /%s successfuly created' % alias,
'Info')
'Info')
def command_unalias(self, alias):
"""
......@@ -135,19 +139,23 @@ class Plugin(BasePlugin):
del self.commands[alias]
self.api.del_command(alias)
self.config.remove(alias)
self.api.information('Alias /%s successfuly deleted' % alias, 'Info')
self.api.information('Alias /%s successfuly deleted' % alias,
'Info')
def completion_unalias(self, the_input):
"Completion for /unalias"
aliases = [alias for alias in self.commands]
aliases.sort()
return Completion(the_input.auto_completion, aliases, '', quotify=False)
return Completion(
the_input.auto_completion, aliases, '', quotify=False)
def get_command(self, name):
"""Returns the function associated with a command"""
def dummy(args):
"""Dummy function called if the command doesn’t exist"""
pass
if name in self.commands:
return dummy
elif name in self.core.commands:
......@@ -156,6 +164,7 @@ class Plugin(BasePlugin):
return self.api.current_tab().commands[name].func
return dummy
def split_args(line):
"""
Extract the relevant vars from the command line
......@@ -165,16 +174,17 @@ def split_args(line):
return None
alias_pos = line.find(' ')
alias = line[:alias_pos]
end = line[alias_pos+1:]
end = line[alias_pos + 1:]
args_pos = end.find(' ')
if args_pos == -1:
command = end
args = ''
else:
command = end[:args_pos]
args = end[args_pos+1:]
args = end[args_pos + 1:]
return (alias, command, args)
def generic_command(command, extra_args, args):
"""
Function that will execute the command and set the relevant
......@@ -187,10 +197,11 @@ def generic_command(command, extra_args, args):
new_extra_args += ' '.join(args)
return command()(new_extra_args)
def command_wrapper(func, command, extra_args):
"set the predefined arguments"
def wrapper(*args, **kwargs):
return func(command, extra_args, *args, **kwargs)
return wrapper
return wrapper
......@@ -19,12 +19,15 @@ Command
from poezio.plugin import BasePlugin
from poezio.tabs import MucTab
class Plugin(BasePlugin):
def init(self):
self.api.add_command('amsg', self.command_amsg,
usage='<message>',
short='Broadcast a message',
help='Broadcast the message to all the joined rooms.')
self.api.add_command(
'amsg',
self.command_amsg,
usage='<message>',
short='Broadcast a message',
help='Broadcast the message to all the joined rooms.')
def command_amsg(self, args):
for room in self.core.tabs:
......
......@@ -49,7 +49,10 @@ from poezio.plugin import BasePlugin
import re
allowed_separators = '/#!:;'
sed_re = re.compile('^([sr])(?P<sep>[%s])(.+?)(?P=sep)(.*?)((?P=sep)|(?P=sep)g)?$' % allowed_separators)
sed_re = re.compile(
'^([sr])(?P<sep>[%s])(.+?)(?P=sep)(.*?)((?P=sep)|(?P=sep)g)?$' %
allowed_separators)
class Plugin(BasePlugin):
def init(self):
......@@ -79,8 +82,9 @@ class Plugin(BasePlugin):
else:
new_body = re.sub(remove, put, body, count=1)
except Exception as e:
self.api.information('Invalid regex for the autocorrect '
'plugin: %s' % e, 'Error')
self.api.information(
'Invalid regex for the autocorrect '
'plugin: %s' % e, 'Error')
return
elif typ == 'r':
if replace_all:
......
......@@ -34,36 +34,43 @@ from mimetypes import guess_type
class Plugin(BasePlugin):
default_config = {'bob': {'max_size': 2048,
'max_age': 86400}}
default_config = {'bob': {'max_size': 2048, 'max_age': 86400}}
def init(self):
for tab in tabs.ConversationTab, tabs.PrivateTab, tabs.MucTab:
self.api.add_tab_command(tab, 'bob', self.command_bob,
usage='<image>',
help='Send image <image> to the current discussion',
short='Send a short image',
completion=self.completion_bob)
self.api.add_tab_command(
tab,
'bob',
self.command_bob,
usage='<image>',
help='Send image <image> to the current discussion',
short='Send a short image',
completion=self.completion_bob)
def command_bob(self, filename):
path = Path(expanduser(filename))
try:
size = path.stat().st_size
except OSError as exc:
self.api.information('Error sending “%s”: %s' % (path.name, exc), 'Error')
self.api.information('Error sending “%s”: %s' % (path.name, exc),
'Error')
return
mime_type = guess_type(path.as_posix())[0]
if mime_type is None or not mime_type.startswith('image/'):
self.api.information('Error sending “%s”, not an image file.' % path.name, 'Error')
self.api.information(
'Error sending “%s”, not an image file.' % path.name, 'Error')
return
if size > self.config.get('max_size'):
self.api.information('Error sending “%s”, file too big.' % path.name, 'Error')
self.api.information(
'Error sending “%s”, file too big.' % path.name, 'Error')
return
with open(path.as_posix(), 'rb') as file:
data = file.read()
max_age = self.config.get('max_age')
cid = self.core.xmpp.plugin['xep_0231'].set_bob(data, mime_type, max_age=max_age)
self.api.run_command('/xhtml <img src="cid:%s" alt="%s"/>' % (cid, path.name))
cid = self.core.xmpp.plugin['xep_0231'].set_bob(
data, mime_type, max_age=max_age)
self.api.run_command(
'/xhtml <img src="cid:%s" alt="%s"/>' % (cid, path.name))
@staticmethod
def completion_bob(the_input):
......
......@@ -4,6 +4,7 @@ Once loaded, everything you will send will be IN CAPITAL LETTERS.
from poezio.plugin import BasePlugin
from poezio import xhtml
class Plugin(BasePlugin):
def init(self):
self.api.add_event_handler('muc_say', self.caps)
......
......@@ -18,8 +18,10 @@ from poezio.decorators import command_args_parser
class Plugin(BasePlugin):
def init(self):
self.api.add_command('closeall', self.command_closeall,
help='Close all non-chatroom tabs.')
self.api.add_command(
'closeall',
self.command_closeall,
help='Close all non-chatroom tabs.')
@command_args_parser.ignored
def command_closeall(self):
......@@ -40,5 +42,3 @@ class Plugin(BasePlugin):
self.core.close_tab(tab)
self.api.information('%s tabs closed.' % length, 'Info')
self.core.refresh_window()
......@@ -30,12 +30,15 @@ from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
FORMATTER = HtmlFormatter(nowrap=True, noclasses=True)
class Plugin(BasePlugin):
def init(self):
self.api.add_command('code', self.command_code,
usage='<language> <code>',
short='Sends syntax-highlighted code',
help='Sends syntax-highlighted code in the current tab')
self.api.add_command(
'code',
self.command_code,
usage='<language> <code>',
short='Sends syntax-highlighted code',
help='Sends syntax-highlighted code in the current tab')
def command_code(self, args):
language, code = args.split(None, 1)
......
......@@ -22,23 +22,30 @@ Commands
from poezio.plugin import BasePlugin
class Plugin(BasePlugin):
def init(self):
self.api.add_command('csi_active', self.command_active,
help='Set the client state indication to “active”',
short='Manual set active')
self.api.add_command('csi_inactive', self.command_inactive,
help='Set the client state indication to “inactive”',
short='Manual set inactive')
self.api.add_command(
'csi_active',
self.command_active,
help='Set the client state indication to “active”',
short='Manual set active')
self.api.add_command(
'csi_inactive',
self.command_inactive,
help='Set the client state indication to “inactive”',
short='Manual set inactive')
def command_active(self, args):
if not self.core.xmpp.plugin['xep_0352'].enabled:
self.api.information('CSI is not enabled in this server', 'Warning')
self.api.information('CSI is not enabled in this server',
'Warning')
else:
self.core.xmpp.plugin['xep_0352'].send_active()
def command_inactive(self, args):
if not self.core.xmpp.plugin['xep_0352'].enabled:
self.api.information('CSI is not enabled in this server', 'Warning')
self.api.information('CSI is not enabled in this server',
'Warning')
else:
self.core.xmpp.plugin['xep_0352'].send_inactive()
......@@ -21,9 +21,9 @@ from poezio.plugin import BasePlugin
from random import choice, randint
import re
DEFAULT_CONFIG = {'cyber': {'frequency': 10}}
class Plugin(BasePlugin):
default_config = DEFAULT_CONFIG
......@@ -34,7 +34,9 @@ class Plugin(BasePlugin):
def cyberize(self, msg, tab):
if randint(1, 100) > self.config.get('frequency'):
return
words = [word for word in re.split('\W+', msg['body']) if len(word) > 3]
words = [
word for word in re.split('\W+', msg['body']) if len(word) > 3
]
if words:
word = choice(words)
msg['body'] = msg['body'].replace(word, 'cyber' + word)
......@@ -10,6 +10,7 @@ import datetime
from poezio import tabs
from poezio import timed_events
class Plugin(BasePlugin):
def init(self):
self.schedule_event()
......@@ -18,7 +19,8 @@ class Plugin(BasePlugin):
self.api.remove_timed_event(self.next_event)
def schedule_event(self):
day_change = datetime.datetime.combine(datetime.date.today(), datetime.time())
day_change = datetime.datetime.combine(datetime.date.today(),
datetime.time())
day_change += datetime.timedelta(1)
self.next_event = timed_events.TimedEvent(day_change, self.day_change)
self.api.add_timed_event(self.next_event)
......
......@@ -36,10 +36,15 @@ from poezio.plugin import BasePlugin
DICE = '\u2680\u2681\u2682\u2683\u2684\u2685'
class DiceRoll:
__slots__ = ['duration', 'total_duration', 'dice_number', 'msgtype',
'jid', 'last_msgid', 'increments']
def __init__(self, total_duration, dice_number, is_muc, jid, msgid, increments):
__slots__ = [
'duration', 'total_duration', 'dice_number', 'msgtype', 'jid',
'last_msgid', 'increments'
]
def __init__(self, total_duration, dice_number, is_muc, jid, msgid,
increments):
self.duration = 0
self.total_duration = total_duration
self.dice_number = dice_number
......@@ -54,14 +59,18 @@ class DiceRoll:
def is_finished(self):
return self.duration >= self.total_duration
class Plugin(BasePlugin):
default_config = {"dice": {"refresh": 0.5, "default_duration": 5}}
def init(self):
for tab_t in [tabs.MucTab, tabs.ConversationTab, tabs.PrivateTab]:
self.api.add_tab_command(tab_t, 'roll', self.command_dice,
help='Roll a die',
usage='[number] [duration]')
self.api.add_tab_command(
tab_t,
'roll',
self.command_dice,
help='Roll a die',
usage='[number] [duration]')
@command_args_parser.quoted(0, 2, ['', ''], True)
def command_dice(self, args):
......@@ -86,8 +95,10 @@ class Plugin(BasePlugin):
is_muctab = isinstance(tab, tabs.MucTab)
msg_id = tab.last_sent_message["id"]
increment = self.config.get('refresh')
roll = DiceRoll(duration, num_dice, is_muctab, tab.name, msg_id, increment)
event = self.api.create_delayed_event(increment, self.delayed_event, roll)
roll = DiceRoll(duration, num_dice, is_muctab, tab.name, msg_id,
increment)
event = self.api.create_delayed_event(increment, self.delayed_event,
roll)
self.api.add_timed_event(event)
def delayed_event(self, roll):
......@@ -96,7 +107,8 @@ class Plugin(BasePlugin):
roll.reroll()
message = self.core.xmpp.make_message(roll.jid)
message["type"] = roll.msgtype
message["body"] = ''.join(random.choice(DICE) for _ in range(roll.dice_number))
message["body"] = ''.join(
random.choice(DICE) for _ in range(roll.dice_number))
message["replace"]["id"] = roll.last_msgid
message.send()
roll.last_msgid = message['id']
......
......@@ -18,12 +18,15 @@ Usage
from poezio.plugin import BasePlugin
from slixmpp.jid import InvalidJID
class Plugin(BasePlugin):
def init(self):
self.api.add_command('disco', self.command_disco,
usage='<JID>',
short='Get the disco#info of a JID',
help='Get the disco#info of a JID')
self.api.add_command(
'disco',
self.command_disco,
usage='<JID>',
short='Get the disco#info of a JID',
help='Get the disco#info of a JID')
def on_disco(self, iq):
info = iq['disco_info']
......@@ -40,14 +43,15 @@ class Plugin(BasePlugin):
continue
sep = '\n ' + len(var) * ' '
field_value = field.get_value(convert=False)
value = sep.join(field_value) if isinstance(field_value, list) else field_value
value = sep.join(field_value) if isinstance(field_value,
list) else field_value
server_info.append('%s: %s' % (var, value))
if server_info:
self.api.information('\n'.join(server_info), title)
def command_disco(self, jid):
try:
self.core.xmpp.plugin['xep_0030'].get_info(jid=jid, cached=False,
callback=self.on_disco)
self.core.xmpp.plugin['xep_0030'].get_info(
jid=jid, cached=False, callback=self.on_disco)
except InvalidJID as e:
self.api.information('Invalid JID “%s”: %s' % (jid, e), 'Error')
......@@ -26,14 +26,18 @@ from poezio.plugin import BasePlugin
from poezio.common import shell_split
from poezio import tabs
class Plugin(BasePlugin):
def init(self):
for tab_type in (tabs.MucTab, tabs.PrivateTab, tabs.ConversationTab):
self.api.add_tab_command(tab_type, 'display_corrections',
handler=self.command_display_corrections,
usage='<number>',
help='Display all the corrections of the number-th last corrected message.',
short='Display the corrections of a message')
self.api.add_tab_command(
tab_type,
'display_corrections',
handler=self.command_display_corrections,
usage='<number>',
help=
'Display all the corrections of the number-th last corrected message.',
short='Display the corrections of a message')
def find_corrected(self, nb):
messages = self.api.get_conversation_messages()
......@@ -60,9 +64,13 @@ class Plugin(BasePlugin):
if message:
display = []
while message:
display.append('%s %s%s%s %s' % (message.str_time, '* ' if message.me else '', message.nickname, '' if message.me else '>', message.txt))
display.append('%s %s%s%s %s' %
(message.str_time, '* '
if message.me else '', message.nickname, ''
if message.me else '>', message.txt))
message = message.old_message
self.api.information('Older versions:\n' + '\n'.join(display[::-1]), 'Info')
self.api.information(
'Older versions:\n' + '\n'.join(display[::-1]), 'Info')
else:
self.api.information('No corrected message found.', 'Warning')
......
......@@ -3,6 +3,7 @@ Double the first word of any message you send in a :ref:`muctab`, making you app
"""
from poezio.plugin import BasePlugin