Пример #1
0
def set_setting(bot, uid, key, value):
    settings = AutosaveDict('polaris/data/%s.settings.json' % bot.name)
    uid = str(uid)
    if not uid in settings:
        settings[uid] = {}
    settings[uid][key] = value
    settings.store_database()
Пример #2
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.reminders.commands
     self.description = self.bot.trans.plugins.reminders.description
     self.reminders = AutosaveDict('polaris/data/%s.reminders.json' %
                                   self.bot.name)
     self.sort_reminders()
Пример #3
0
def set_setting(bot, uid, key, value):
    settings = AutosaveDict('polaris/data/%s.settings.json' % bot.name)
    uid = str(uid)
    if not uid in settings:
        settings[uid] = {}
    settings[uid][key] = value
    settings.store_database()
Пример #4
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.administration.commands
     self.description = self.bot.trans.plugins.administration.description
     self.administration = AutosaveDict('polaris/data/%s.administration.json' % self.bot.name)
     self.groups = AutosaveDict('polaris/data/%s.groups.json' % self.bot.name)
     self.users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)
Пример #5
0
def del_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)

    if not isinstance(target, str):
        target = str(target)

    tags[target].remove(tag)
    tags.store_database()
Пример #6
0
def set_step(bot, target, plugin, step):
    steps = AutosaveDict('polaris/data/%s.steps.json' % bot.name)

    if not isinstance(target, str):
        target = str(target)

    steps[target] = {'plugin': plugin, 'step': step}
    steps.store_database()
Пример #7
0
def set_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)
    if not target in tags:
        tags[target] = []

    if not tag in tags[target]:
        tags[target].append(tag)
        tags.store_database()
Пример #8
0
def del_setting(bot, uid, key):
    settings = AutosaveDict('polaris/data/%s.settings.json' % bot.name)

    if not isinstance(uid, str):
        uid = str(uid)

    del (settings[uid][key])
    settings.store_database()
Пример #9
0
def set_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)
    if not target in tags:
        tags[target] = []

    if not tag in tags[target]:
        tags[target].append(tag)
        tags.store_database()
Пример #10
0
def cancel_steps(bot, target):
    steps = AutosaveDict('polaris/data/%s.steps.json' % bot.name)

    if not isinstance(target, str):
        target = str(target)

    if target in steps:
        del steps[target]
        steps.store_database()
Пример #11
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.administration.commands
     self.commands.append({
         "command": "^new_chat_member$",
         "parameters": [],
         "hidden": True
     })
     self.description = self.bot.trans.plugins.administration.description
     self.administration = AutosaveDict('polaris/data/%s.administration.json' % self.bot.name)
     self.groups = AutosaveDict('polaris/data/%s.groups.json' % self.bot.name)
     self.users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)
Пример #12
0
 def __init__(self, name):
     self.name = name
     self.config = AutosaveDict('bots/%s.json' % self.name)
     self.trans = AutosaveDict('polaris/translations/%s.json' %
                               self.config.translation)
     self.bindings = importlib.import_module(
         'polaris.bindings.%s' % self.config.bindings).bindings(self)
     self.inbox = Queue()
     self.outbox = Queue()
     self.started = False
     self.plugins = None
     self.info = None
Пример #13
0
    def run(self, m):
        groups = AutosaveDict('polaris/data/%s.groups.json' % self.bot.name)
        users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)

        tag = subprocess.check_output(['git', 'describe', '--tags']).decode('ascii').rstrip('\n')

        greeting = self.bot.trans.plugins.about.strings.greeting % self.bot.info.first_name
        version = self.bot.trans.plugins.about.strings.version % (tag)
        # license = self.bot.trans.plugins.about.strings.license
        help = self.bot.trans.plugins.about.strings.help % self.bot.config.prefix
        stats = self.bot.trans.plugins.about.strings.stats % (len(users), len(groups))

        text = '%s\n\n%s\n\n%s\n\n%s' % (greeting, help, version, stats)

        self.bot.send_message(m, text, extra={'format': 'HTML'})
Пример #14
0
def get_setting(bot, uid, key):
    settings = AutosaveDict('polaris/data/%s.settings.json' % bot.name)
    uid = str(uid)
    try:
        return settings[uid][key]
    except:
        return None
Пример #15
0
def get_step(bot, target):
    steps = AutosaveDict('polaris/data/%s.steps.json' % bot.name)

    if not isinstance(target, str):
        target = str(target)

    if not target in steps:
        return None
    else:
        return steps[target]
Пример #16
0
def has_tag(bot, target, tag, return_match=False):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)

    if not isinstance(target, str):
        target = str(target)

    if target in tags and '?' in tag:
        for target_tag in tags[target]:
            if target_tag.startswith(tag.split('?')[0]):
                if return_match:
                    return target_tag

                else:
                    return True

        return False

    elif target in tags and tag in tags[target]:
        return True

    else:
        return False
Пример #17
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.pins.commands
     self.description = self.bot.trans.plugins.pins.description
     self.pins = AutosaveDict('polaris/data/%s.pins.json' % self.bot.name)
     self.update_triggers()
Пример #18
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.pins.commands
        self.description = self.bot.trans.plugins.pins.description
        self.pins = AutosaveDict('polaris/data/%s.pins.json' % self.bot.name)
        self.update_triggers()

    # Plugin action #
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.pins:
                if self.pins[pin].creator == m.sender.id:
                    pins.append(pin)

            if len(pins) > 0:
                text = self.bot.trans.plugins.pins.strings.pins % len(pins)
                for pin in pins:
                    text += '\n • %s' % pin

            else:
                text = self.bot.trans.plugins.pins.strings.no_pins

            # If the message is too long send an error message instead #
            if len(text) < 4096:
                return self.bot.send_message(m, text, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.unknown,
                                             extra={'format': 'HTML'})

        # Add a pin #
        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            input = input.lower()
            input = sub(r'[^\w\ ]', '',
                        input)  # Removes every special character.
            input = " ".join(
                input.split())  # Removes any duplicated whitespace.
            #input = input.split(' ', 1)[0]
            #input = sub(r'[^\w]','',input)

            if not m.reply:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.needs_reply,
                                             extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.invalid_parameter,
                    extra={'format': 'HTML'})

            if input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.already_pinned % input,
                    extra={'format': 'HTML'})

            if len(input) < 4:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.too_short,
                    extra={'format': 'HTML'})

            if input == self.bot.info.first_name.lower():
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.illegal_pinname,
                    extra={'format': 'HTML'})

            self.pins[input] = {
                'content':
                m.reply.content.replace('<', '&lt;').replace('>', '&gt;'),
                'creator':
                m.sender.id,
                'type':
                m.reply.type
            }

            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.pinned % input,
                extra={'format': 'HTML'})

        # Remove a pin #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            input = input.lower()
            input = sub(r'[^\w\ ]', '', input)
            input = " ".join(input.split())
            #input = input.split(' ', 1)[0]

            print(input)

            if not input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.not_found % input,
                    extra={'format': 'HTML'})

            if not m.sender.id == self.pins[input]['creator']:
                if not is_mod(self.bot, m.sender.id, m.conversation.id):
                    return self.bot.send_message(
                        m,
                        self.bot.trans.plugins.pins.strings.not_creator %
                        input,
                        extra={'format': 'HTML'})
            try:
                del (self.pins[input])
            except KeyErrorException:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.unknown,
                                             extra={'format': 'HTML'})

            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.unpinned % input,
                extra={'format': 'HTML'})

        # Check what pin was triggered #
        else:
            # Finds the first 3 pins of the message and sends them. #
            #pins = findall(r"(\w+)", m.content.lower())
            if not randint(0, 4):
                replymessage = False
                pins = m.content.lower()
                #count = 3

                # Checks if the message contains a saved pin
                for pin in self.pins:
                    if pins.find(pin) > -1:
                        pinlength = len(pin)
                        textlength = len(pins)
                        foundpin = pins.find(pin)

                        # Found at first position of sent text and checks if it has a non-alphanumerical char next to the matching word
                        if foundpin == 0:
                            if textlength == pinlength:
                                replymessage = True
                            elif textlength > pinlength and match(
                                    '\W', pins[foundpin + pinlength]):
                                replymessage = True

                        # Ensures that the keyword is between spaces.
                        elif foundpin > 0 and match('\W', pins[foundpin - 1]):
                            if foundpin + pinlength == textlength or match(
                                    '\W',
                                    pins[foundpin +
                                         pinlength]):  # Last or middle word
                                replymessage = True

                        # You can reply with a pin and the message will reply too. #
                        if m.reply:
                            reply = m.reply.id
                        else:
                            reply = m.id

                        if replymessage:
                            self.bot.send_message(m,
                                                  self.pins[pin]['content'],
                                                  self.pins[pin]['type'],
                                                  extra={'format': 'HTML'
                                                         })  #, reply = reply)
                        #count -= 1

                    #if count == 0:
                    #    return

    def update_triggers(self):
        # Add new triggers #
        for pin, attributes in self.pins.items():
            if not next((i for i, d in enumerate(self.commands)
                         if 'command' in d and d.command == pin), None):
                self.commands.append({'command': pin, 'hidden': True})

        # Remove unused triggers #
        for command in self.commands:
            if 'hidden' in command and command.hidden and not command.command.lstrip(
                    '#') in self.pins:
                self.commands.remove(command)
Пример #19
0
def has_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)
    if target in tags and tag in tags[target]:
        return True
    else:
        return False
Пример #20
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.pins.commands
        self.description = self.bot.trans.plugins.pins.description
        self.pins = AutosaveDict('polaris/data/%s.pins.json' % self.bot.name)
        self.update_triggers()

    # Plugin action #
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.pins:
                if self.pins[pin].creator == m.sender.id:
                    pins.append(pin)

            if len(pins) > 0:
                text = self.bot.trans.plugins.pins.strings.pins % len(pins)
                for pin in pins:
                    text += '\n • #%s' % pin

            else:
                text = self.bot.trans.plugins.pins.strings.no_pins

            # If the message is too long send an error message instead #
            if len(text) < 4096:
                return self.bot.send_message(m, text, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.unknown,
                                             extra={'format': 'HTML'})

        # Add a pin #
        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not m.reply:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.needs_reply,
                                             extra={'format': 'HTML'})

            if input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.already_pinned % input,
                    extra={'format': 'HTML'})

            self.pins[input] = {
                'content':
                m.reply.content.replace('<', '&lt;').replace('>', '&gt;'),
                'creator':
                m.sender.id,
                'type':
                m.reply.type
            }

            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.pinned % input,
                extra={'format': 'HTML'})

        # Remove a pin #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not input in self.pins:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.not_found % input,
                    extra={'format': 'HTML'})

            if not m.sender.id == self.pins[input]['creator']:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.pins.strings.not_creator % input,
                    extra={'format': 'HTML'})

            del (self.pins[input])
            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(
                m,
                self.bot.trans.plugins.pins.strings.unpinned % input,
                extra={'format': 'HTML'})

        # Check what pin was triggered #
        else:
            # Finds the first 3 pins of the message and sends them. #
            pins = findall(r"#(\w+)", m.content.lower())
            count = 3

            for pin in pins:
                if pin in self.pins:
                    # You can reply with a pin and the message will reply too. #
                    if m.reply:
                        reply = m.reply.id
                    else:
                        reply = m.id

                    self.bot.send_message(m,
                                          self.pins[pin]['content'],
                                          self.pins[pin]['type'],
                                          extra={'format': 'HTML'},
                                          reply=reply)
                    count -= 1

                if count == 0:
                    return

    def update_triggers(self):
        # Add new triggers #
        for pin, attributes in self.pins.items():
            if not next((i for i, d in enumerate(self.commands)
                         if 'command' in d and d.command == '#' + pin), None):
                self.commands.append({'command': '#' + pin, 'hidden': True})

        # Remove unused triggers #
        for command in self.commands:
            if 'hidden' in command and command.hidden and not command.command.lstrip(
                    '#') in self.pins:
                self.commands.remove(command)
Пример #21
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.administration.commands
        self.description = self.bot.trans.plugins.administration.description
        self.administration = AutosaveDict(
            'polaris/data/%s.administration.json' % self.bot.name)
        self.groups = AutosaveDict('polaris/data/%s.groups.json' %
                                   self.bot.name)
        self.users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)

    # Plugin action #
    def run(self, m):
        input = get_input(m)
        uid = str(m.sender.id)
        gid = str(m.conversation.id)

        # List all administration commands. #
        if is_command(self, 1, m.content):
            text = self.bot.trans.plugins.administration.strings.commands
            for command in self.commands:
                # Adds the command and parameters#
                if command['command'] == '^new_chat_member$':
                    text += '\n • ' + self.bot.trans.plugins.administration.strings.new_chat_member
                else:
                    text += '\n • ' + command['command'].replace(
                        '/', self.bot.config.prefix)

                if 'parameters' in command:
                    for parameter in command['parameters']:
                        name, required = list(parameter.items())[0]
                        # Bold for required parameters, and italic for optional #
                        if required:
                            text += ' <b>&lt;%s&gt;</b>' % name
                        else:
                            text += ' [%s]' % name

                if 'description' in command:
                    text += '\n   <i>%s</i>' % command['description']
                else:
                    text += '\n   <i>?¿</i>'

            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # List all groups. #
        if is_command(self, 2, m.content):
            text = self.bot.trans.plugins.administration.strings.groups
            i = 1
            for gid, attr in self.administration.items():
                text += '\n %s. %s (%s)' % (i, self.groups[gid]['title'],
                                            attr['alias'])
                i += 1
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # Send message to another group. #
        if is_command(self, 10, m.content):
            input = get_input(m, ignore_reply=False)
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            id_backup = m.conversation.id
            group_number = int(findall(r"(\w+)", m.content)[1])
            msg_offset = len(str(group_number)) + 1
            text = input[msg_offset:]

            if text and is_int(group_number):
                m.conversation.id = 0

                for gid in self.administration:
                    if group_number == 1:
                        m.conversation.id = int(gid)
                    group_number -= 1

                if m.conversation.id != id_backup and m.conversation.id != 0:
                    text = self.bot.trans.plugins.administration.strings.message_received % m.conversation.title + text
                    return self.bot.send_message(m,
                                                 text,
                                                 extra={'format': 'HTML'})
                    #return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.sent, extra={'format': 'HTML'})
                elif m.conversation.id == id_backup:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.plugins.administration.strings.no_echo,
                        extra={'format': 'HTML'})
                else:
                    m.conversation.id = id_backup
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.send_error,
                        extra={'format': 'HTML'})
            else:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.
                    invalid_syntax,
                    extra={'format': 'HTML'})

        # Join a group. #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            for id in self.administration:
                if (input in self.administration
                        or input in self.administration[id]['alias']
                        or input in self.groups[id]['title']):
                    gid_to_join = id
                    break

            if not gid_to_join in self.administration:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.not_added %
                    m.conversation.title,
                    extra={'format': 'HTML'})

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (
                self.groups[gid_to_join]['title'],
                self.administration[gid_to_join]['description'],
                self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid_to_join]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1
            if not self.administration[gid_to_join]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if not self.administration[gid_to_join]['link']:
                text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
            else:
                text += '\n\n<a href="%s">%s</a>' % (
                    self.administration[gid_to_join]['link'],
                    self.bot.trans.plugins.administration.strings.join)
            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': False
                                         })

        # Information about a group. #
        elif is_command(self, 4, m.content) or is_command(self, 9, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.group_only,
                                             extra={'format': 'HTML'})
            if not gid in self.administration:
                if is_command(self, 4, m.content):
                    return self.bot.send_message(
                        m,
                        self.bot.trans.plugins.administration.strings.not_added
                        % m.conversation.title,
                        extra={'format': 'HTML'})
                elif is_command(self, 9, m.content):
                    return

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (
                self.groups[gid]['title'],
                self.administration[gid]['description'],
                self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if is_command(self, 4, m.content):
                if not self.administration[gid]['link']:
                    text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
                else:
                    text += '\n\n<a href="%s">%s</a>' % (
                        self.bot.trans.plugins.administration.strings.join.
                        self.administration[gid]['link'])
            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': False
                                         })

        # Rules of a group. #
        elif is_command(self, 5, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.group_only,
                                             extra={'format': 'HTML'})
            if not gid in self.administration:
                return self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.not_added %
                    m.conversation.title,
                    extra={'format': 'HTML'})

            if input and is_int(input):
                try:
                    i = int(input)
                    text = '%s. <i>%s</i>' % (
                        i, self.administration[gid]['rules'][i - 1])
                except:
                    text = self.bot.trans.plugins.administration.strings.notfound

            else:
                text = self.bot.trans.plugins.administration.strings.rules
                i = 1
                for rule in self.administration[gid]['rules']:
                    text += '\n %s. <i>%s</i>' % (i, rule)
                    i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            return self.bot.send_message(m,
                                         text,
                                         extra={
                                             'format': 'HTML',
                                             'preview': False
                                         })

        # Kicks a user. #
        elif is_command(self, 6, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.group_only,
                                             extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.permission_required,
                    extra={'format': 'HTML'})

            if not input and not m.reply:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            if m.reply:
                target = m.reply.sender.id
            elif input:
                target = input
            else:
                target = m.sender.id

            res = self.bot.kick_user(m, target)
            self.bot.unban_user(m, target)
            if res is None:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.admin_required,
                    extra={'format': 'HTML'})
            elif not res:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.failed,
                                             extra={'format': 'HTML'})
            else:
                return self.bot.send_message(
                    m,
                    '<pre>An enemy has been slain.</pre>',
                    extra={'format': 'HTML'})

            return self.bot.send_message(m,
                                         self.bot.trans.errors.unknown,
                                         extra={'format': 'HTML'})

        # Bans a user. #
        elif is_command(self, 7, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.group_only,
                                             extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.permission_required,
                    extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.missing_parameter,
                    extra={'format': 'HTML'})

            return self.bot.send_message(m,
                                         self.bot.trans.errors.unknown,
                                         extra={'format': 'HTML'})

        # Configures a group. #
        elif is_command(self, 8, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m,
                                             self.bot.trans.errors.group_only,
                                             extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(
                    m,
                    self.bot.trans.errors.permission_required,
                    extra={'format': 'HTML'})

            if not input:
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_to_add %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })
                if not gid in self.administration:
                    self.administration[gid] = {
                        'alias': None,
                        'description': None,
                        'link': None,
                        'rules': []
                    }
                    self.administration.store_database()
                set_step(self.bot, m.conversation.id, get_plugin_name(self), 1)
            else:
                if first_word(input) == 'add':
                    if not gid in self.administration:
                        self.administration[gid] = {
                            'alias': None,
                            'description': None,
                            'link': None,
                            'rules': []
                        }
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.added
                            % m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            already_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'remove':
                    if gid in self.administration:
                        del (self.administration[gid])
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            removed % m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'alias':
                    if gid in self.administration:
                        self.administration[gid]['alias'] = all_but_first_word(
                            input)
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.set %
                            m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'motd':
                    if gid in self.administration:
                        self.administration[gid][
                            'description'] = all_but_first_word(input)
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.set %
                            m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'link':
                    if gid in self.administration:
                        self.administration[gid]['link'] = all_but_first_word(
                            input)
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.set %
                            m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'rules':
                    if gid in self.administration:
                        self.administration[gid]['rules'] = all_but_first_word(
                            input).split('\n')[0:]
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.set %
                            m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                elif first_word(input) == 'rule':
                    if gid in self.administration:
                        try:
                            i = int(first_word(all_but_first_word(input))) - 1
                            if i > len(self.administration[gid]['rules']):
                                i = len(self.administration[gid]['rules'])
                            elif i < 1:
                                i = 0
                        except:
                            return self.bot.send_message(
                                m,
                                self.bot.trans.errors.unknown,
                                extra={'format': 'HTML'})
                        self.administration[gid]['rules'].insert(
                            i, all_but_first_word(all_but_first_word(input)))
                        self.administration.store_database()
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.set %
                            m.conversation.title,
                            extra={'format': 'HTML'})
                    else:
                        return self.bot.send_message(
                            m,
                            self.bot.trans.plugins.administration.strings.
                            not_added % m.conversation.title,
                            extra={'format': 'HTML'})

                else:
                    return self.bot.send_message(
                        m,
                        self.bot.trans.errors.no_results,
                        extra={'format': 'HTML'})

    def always(self, m):
        if str(m.sender.id).startswith('-100'):
            return

        # Update group data #
        gid = str(m.conversation.id)
        if m.conversation.id < 0:
            if gid in self.groups:
                self.groups[gid].title = m.conversation.title
                self.groups[gid].messages += 1

            else:
                self.groups[gid] = {
                    "title": m.conversation.title,
                    "messages": 1
                }

        # Update user data #
        uid = str(m.sender.id)
        if uid in self.users:
            self.users[uid].first_name = m.sender.first_name
            if hasattr(m.sender, 'last_name'):
                self.users[uid].last_name = m.sender.last_name
            if hasattr(m.sender, 'username'):
                self.users[uid].username = m.sender.username
            self.users[uid].messages += 1

        else:
            self.users[uid] = {
                "first_name": m.sender.first_name,
                "last_name": m.sender.last_name,
                "username": m.sender.username,
                "messages": 1
            }

        # Update group id when upgraded to supergroup #
        if m.type == 'notification' and m.content == 'upgrade_to_supergroup':
            to_id = str(m.extra['chat_id'])
            from_id = str(m.extra['from_chat_id'])
            if from_id in self.administration:
                self.administration[to_id] = self.administration.pop(from_id)
            self.groups[to_id] = self.groups.pop(from_id)

        self.administration.store_database()
        self.groups.store_database()
        self.users.store_database()

    def steps(self, m, step):
        gid = str(m.conversation.id)

        if step == -1:
            self.bot.send_message(
                m,
                self.bot.trans.plugins.administration.strings.cancel %
                m.conversation.title,
                extra={'format': 'HTML'})
            cancel_steps(self.bot, m.conversation.id)

        if step == 0:
            self.bot.send_message(
                m,
                self.bot.trans.plugins.administration.strings.done %
                m.conversation.title,
                extra={'format': 'HTML'})
            cancel_steps(self.bot, m.conversation.id)

        elif step == 1:
            if self.bot.trans.plugins.administration.strings.yes.lower(
            ) in m.content.lower():
                set_step(self.bot, m.conversation.id, get_plugin_name(self), 2)
                if not m.content.startswith(
                        '/next') and not m.content.startswith('/done'):
                    self.bot.send_message(
                        m,
                        self.bot.trans.plugins.administration.strings.ask_link
                        % m.conversation.title,
                        extra={
                            'format': 'HTML',
                            'force_reply': True
                        })

            else:
                cancel_steps(self.bot, m.conversation.id)
                self.bot.send_message(m,
                                      self.bot.trans.errors.unknown,
                                      extra={'format': 'HTML'})

        elif step == 2:
            set_step(self.bot, m.conversation.id, get_plugin_name(self), 3)
            if not m.content.startswith('/next') and not m.content.startswith(
                    '/done'):
                self.administration[gid]['link'] = m.content
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_alias %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })

        elif step == 3:
            set_step(self.bot, m.conversation.id, get_plugin_name(self), 4)
            if not m.content.startswith('/next') and not m.content.startswith(
                    '/done'):
                self.administration[gid]['alias'] = m.content.lower()
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_rules %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })

        elif step == 4:
            set_step(self.bot, m.conversation.id, get_plugin_name(self), 5)
            if not m.content.startswith('/next') and not m.content.startswith(
                    '/done'):
                self.administration[gid]['rules'] = m.content.split('\n')
                self.bot.send_message(
                    m,
                    self.bot.trans.plugins.administration.strings.ask_motd %
                    m.conversation.title,
                    extra={
                        'format': 'HTML',
                        'force_reply': True
                    })

        elif step == 5:
            set_step(self.bot, m.conversation.id, get_plugin_name(self), -1)
            if not m.content.startswith('/next') and not m.content.startswith(
                    '/done'):
                self.administration[gid]['motd'] = m.content
Пример #22
0
    def bot_config(name):
        config = AutosaveDict('bots/%s.json' % name)

        i = 1
        finished = False
        while not finished:
            text = 'Editing /bots/%s.json\n' % name

            if 'bindings' in config:
                bindings = config['bindings']
            else:
                bindings = 'telegram-bot-api'

            if 'bindings_token' in config:
                bindings_token = config['bindings_token']
            else:
                bindings_token = 'YOUR TELEGRAM BOT TOKEN'

            if 'command_start' in config:
                command_start = config['command_start']
            else:
                command_start = '/'

            if 'owner' in config:
                owner = config['owner']
            else:
                owner = 0

            if 'debug' in config:
                debug = config['debug']
            else:
                debug = False

            if 'language' in config:
                language = config['language']
            else:
                language = 'default'

            if 'plugins' in config:
                plugins = config['plugins']
            else:
                plugins = load_plugin_list()

            if 'api_keys' in config:
                api_keys = config['api_keys']
            else:
                api_keys = {}

            text += '(0) Finish editing\n'
            text += '(1) bindings: %s\n' % bindings
            text += '(2) bindings_token: %s\n' % bindings_token
            text += '(3) command_start: %s\n' % command_start
            text += '(4) owner: %s\n' % owner
            text += '(5) debug: %s\n' % debug
            text += '(6) language: %s\n' % language
            text += '(7) plugins: %s\n' % plugins
            text += '(8) api_keys: %s\n' % api_keys

            option = int(input(text))
            if option == 0:
                print('Saving all values to "bots/%s.json".' % name)
                config.bindings = bindings
                config.bindings_token = bindings_token
                config.command_start = command_start
                config.owner = owner
                config.debug = debug
                config.language = language
                config.plugins = plugins
                config.api_keys = api_keys
                finished = True
            
            elif option == 1:
                option = input('What bindings want to use? (Current value: "%s")\n' % bindings)
                config.bindings = option
Пример #23
0
def del_setting(bot, uid, key):
    settings = AutosaveDict('polaris/data/%s.settings.json' % bot.name)
    uid = str(uid)
    del(settings[uid][key])
    settings.store_database()
Пример #24
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.pins.commands
     self.description = self.bot.trans.plugins.pins.description
     self.pins = AutosaveDict('polaris/data/%s.pins.json' % self.bot.name)
     self.update_triggers()
Пример #25
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.reminders.commands
        self.description = self.bot.trans.plugins.reminders.description
        self.reminders = AutosaveDict("polaris/data/%s.reminders.json" % self.bot.name)
        self.sort_reminders()

    # Plugin action #
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={"format": "HTML"})

        self.reminders.load_database()
        # Lists all pins #
        delay = first_word(input)
        if delay:
            delaytime = delay[:-1]
            unit = delay[-1:]
            if not is_int(delaytime) or is_int(unit):
                return self.bot.send_message(m, self.bot.trans.plugins.reminders.strings.wrongdelay)

        alarm = time() + self.to_seconds(delaytime, unit)

        text = all_but_first_word(input)
        if not text:
            return self.bot.send_message(m, self.bot.trans.plugins.reminders.strings.noreminder)

        reminder = DictObject(OrderedDict())
        reminder.id = "%s:%s" % (m.sender.id, time())
        reminder.alarm = alarm
        reminder.chat_id = m.conversation.id
        reminder.text = text
        reminder.first_name = m.sender.first_name
        reminder.username = m.sender.username

        self.reminders.list.append(reminder)
        self.sort_reminders()
        self.reminders.store_database()

        if unit == "s":
            delay = delay.replace("s", " seconds")
        if unit == "m":
            delay = delay.replace("m", " minutes")
        if unit == "h":
            delay = delay.replace("h", " hours")
        if unit == "d":
            delay = delay.replace("d", " days")

        message = self.bot.trans.plugins.reminders.strings.added % (m.sender.first_name, delay, text)

        return self.bot.send_message(m, message, extra={"format": "HTML"})

    def cron(self):
        self.reminders.load_database()
        while len(self.reminders.list) > 0 and self.reminders.list[0].alarm < time():
            reminder = self.reminders.list[0]
            text = "<i>%s</i>\n - %s" % (reminder.text, reminder.first_name)
            if reminder.username:
                text += " (@%s)" % reminder.username

            m = Message(None, Conversation(reminder.chat_id), None, None)
            self.bot.send_message(m, text, extra={"format": "HTML"})
            self.reminders.list.remove(reminder)
            self.sort_reminders()

    @staticmethod
    def to_seconds(delaytime, unit):
        if unit == "s":
            return float(delaytime)
        elif unit == "m":
            return float(delaytime) * 60
        elif unit == "h":
            return float(delaytime) * 60 * 60
        elif unit == "d":
            return float(delaytime) * 60 * 60 * 24

    def sort_reminders(self):
        if not "list" in self.reminders:
            self.reminders.list = []

        if len(self.reminders.list) > 0:
            self.reminders.list = sorted(self.reminders.list, key=lambda k: k["alarm"])

        self.reminders.store_database()
Пример #26
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.administration.commands
        self.commands.append({
            "command": "^new_chat_member$",
            "parameters": [],
            "hidden": True
        })
        self.description = self.bot.trans.plugins.administration.description
        self.administration = AutosaveDict('polaris/data/%s.administration.json' % self.bot.name)
        self.groups = AutosaveDict('polaris/data/%s.groups.json' % self.bot.name)
        self.users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)

    # Plugin action #
    def run(self, m):
        input = get_input(m)
        uid = str(m.sender.id)
        gid = str(m.conversation.id)

        # List all administration commands. #
        if is_command(self, 1, m.content):
            text = self.bot.trans.plugins.administration.strings.commands
            for command in self.commands:
                # Adds the command and parameters#
                if self.commands[-1]['command'].replace('/', self.bot.config.prefix) in m.content:
                    text += '\n' + command['command'].lstrip('/')

                    if 'description' in command:
                        text += ' - %s' % command['description']
                    else:
                        text += ' - ?¿'
                else:
                    text += '\n • ' + command['command'].replace('/', self.bot.config.prefix)
                    if 'parameters' in command:
                        for parameter in command['parameters']:
                            name, required = list(parameter.items())[0]
                            # Bold for required parameters, and italic for optional #
                            if required:
                                text += ' <b>&lt;%s&gt;</b>' % name
                            else:
                                text += ' [%s]' % name

                    if 'description' in command:
                        text += '\n   <i>%s</i>' % command['description']
                    else:
                        text += '\n   <i>?¿</i>'
                        text += '\n   <i>?¿</i>'

            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # List all groups. #
        if is_command(self, 2, m.content):
            text = self.bot.trans.plugins.administration.strings.groups
            for gid, attr in self.administration.items():
                text += '\n • %s |%s|' % (self.groups[gid]['title'], attr['alias'])
            return self.bot.send_message(m, text, extra={'format': 'HTML'})

        # Join a group. #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            for id in self.administration:
                if (input in self.administration or
                    input in self.administration[id]['alias'] or
                    input in self.groups[id]['title']):
                    gid_to_join = id
                    break

            if not gid_to_join in self.administration:
                return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (self.groups[gid_to_join]['title'], self.administration[gid_to_join]['description'], self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid_to_join]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1
            if not self.administration[gid_to_join]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if not self.administration[gid_to_join]['link']:
                text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
            else:
                text += '\n\n<a href="%s">%s</a>' % (self.administration[gid_to_join]['link'], self.bot.trans.plugins.administration.strings.join)
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Information about a group. #
        elif is_command(self, 4, m.content) or is_command(self, 9, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})
            if not gid in self.administration:
                if is_command(self, 4, m.content):
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})
                elif is_command(self, 9, m.content):
                    return

            text = '<b>%s</b>\n<i>%s</i>\n\n%s' % (self.groups[gid]['title'], self.administration[gid]['description'], self.bot.trans.plugins.administration.strings.rules)
            i = 1
            for rule in self.administration[gid]['rules']:
                text += '\n %s. <i>%s</i>' % (i, rule)
                i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            if is_command(self, 4, m.content):
                if not self.administration[gid]['link']:
                    text += '\n\n%s' % self.bot.trans.plugins.administration.strings.nolink
                else:
                    text += '\n\n<a href="%s">%s</a>' % (self.bot.trans.plugins.administration.strings.join. self.administration[gid]['link'])
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Rules of a group. #
        elif is_command(self, 5, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})
            if not gid in self.administration:
                return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            if input and is_int(input):
                try:
                    i = int(input)
                    text = '%s. <i>%s</i>' % (i, self.administration[gid]['rules'][i - 1])
                except:
                    text = self.bot.trans.plugins.administration.strings.notfound

            else:
                text = self.bot.trans.plugins.administration.strings.rules
                i = 1
                for rule in self.administration[gid]['rules']:
                    text += '\n %s. <i>%s</i>' % (i, rule)
                    i += 1

            if not self.administration[gid]['rules']:
                text += '\n%s' % self.bot.trans.plugins.administration.strings.norules
            return self.bot.send_message(m, text, extra={'format': 'HTML', 'preview': False})

        # Kicks a user. #
        elif is_command(self, 6, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if not input and not m.reply:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if m.reply:
                target = m.reply.sender.id
            elif input:
                target = input
            else:
                target = m.sender.id

            res = self.bot.kick_user(m, target)
            self.bot.unban_user(m, target)
            if res is None:
                return self.bot.send_message(m, self.bot.trans.errors.admin_required, extra={'format': 'HTML'})
            elif not res:
                return self.bot.send_message(m, self.bot.trans.errors.failed, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m, '<pre>An enemy has been slain.</pre>', extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Bans a user. #
        elif is_command(self, 7, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Configures a group. #
        elif is_command(self, 8, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_trusted(self.bot, m.sender.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            parameters = [
                'add',
                'remove',
                'alias',
                'description',
                'rules',
                'rule'
            ]

            if not input:
                text = '<b>Available commands:</b>'
                for param in parameters:
                    text += '\n • %scfg %s' % (self.bot.config.prefix, param)
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if first_word(input) == 'add':
                if not gid in self.administration:
                    self.administration[gid] = {
                        'alias': None,
                        'description': None,
                        'link': None,
                        'rules': []
                    }
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.added % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.already_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'remove':
                if gid in self.administration:
                    del(self.administration[gid])
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.removed % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'alias':
                if gid in self.administration:
                    self.administration[gid]['alias'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'description':
                if gid in self.administration:
                    self.administration[gid]['description'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'link':
                if gid in self.administration:
                    self.administration[gid]['link'] = all_but_first_word(input)
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rules':
                if gid in self.administration:
                    self.administration[gid]['rules'] = all_but_first_word(input).split('\n')[0:]
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rule':
                if gid in self.administration:
                    try:
                        i = int(first_word(all_but_first_word(input)))-1
                        if i > len(self.administration[gid]['rules']):
                            i = len(self.administration[gid]['rules'])
                        elif i < 1:
                            i = 0
                    except:
                        return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})
                    self.administration[gid]['rules'].insert(i, all_but_first_word(all_but_first_word(input)))
                    self.administration.store_database()
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})


            else:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})


    def always(self, m):
        if str(m.sender.id).startswith('-100'):
            return

        # Update group data #
        gid = str(m.conversation.id)
        if m.conversation.id < 0:
            if gid in self.groups:
                self.groups[gid].title = m.conversation.title
                self.groups[gid].messages += 1

            else:
                self.groups[gid] = {
                    "title": m.conversation.title,
                    "messages": 1
                }

        # Update user data #
        uid = str(m.sender.id)
        if uid in self.users:
            self.users[uid].first_name = m.sender.first_name
            if hasattr(m.sender, 'last_name'):
                self.users[uid].last_name = m.sender.last_name
            if hasattr(m.sender, 'username'):
                self.users[uid].username = m.sender.username
            self.users[uid].messages += 1

        else:
            self.users[uid] = {
                "first_name": m.sender.first_name,
                "last_name": m.sender.last_name,
                "username": m.sender.username,
                "messages": 1
            }

        # Update group id when upgraded to supergroup #
        if m.type == 'notification' and m.content == 'upgrade_to_supergroup':
            to_id = str(m.extra['chat_id'])
            from_id = str(m.extra['from_chat_id'])
            if from_id in self.administration:
                self.administration[to_id] = self.administration.pop(from_id)
            self.groups[to_id] = self.groups.pop(from_id)

        self.administration.store_database()
        self.groups.store_database()
        self.users.store_database()
Пример #27
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.administration.commands
        self.description = self.bot.trans.plugins.administration.description
        self.administration = AutosaveDict('polaris/data/%s.administration.json' % self.bot.name)
        self.groups = AutosaveDict('polaris/data/%s.groups.json' % self.bot.name)
        self.users = AutosaveDict('polaris/data/%s.users.json' % self.bot.name)

    # Plugin action #
    def run(self, m):
        input = get_input(m)
        uid = str(m.sender.id)
        gid = str(m.conversation.id)

        # List all administration commands. #
        if is_command(self, 1, m.content):
            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # List all groups. #
        if is_command(self, 2, m.content):
            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Join a group. #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Information about a group. #
        elif is_command(self, 4, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Rules of a group. #
        elif is_command(self, 5, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Kicks a user. #
        elif is_command(self, 6, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Bans a user. #
        elif is_command(self, 7, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_mod(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Configures a group. #
        elif is_command(self, 8, m.content):
            if m.conversation.id > 0:
                return self.bot.send_message(m, self.bot.trans.errors.group_only, extra={'format': 'HTML'})

            if not is_trusted(self.bot, m.sender.id, m.conversation.id):
                return self.bot.send_message(m, self.bot.trans.errors.permission_required, extra={'format': 'HTML'})

            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if first_word(input) == 'add':
                if not gid in self.administration:
                    self.administration[gid]
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.added % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.already_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'remove':
                if gid in self.administration:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.removed % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'alias':
                if gid in self.administration:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'description':
                if gid in self.administration:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rules':
                if gid in self.administration:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            elif first_word(input) == 'rule':
                if str(m.conversation.id) in self.administration:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.set % m.conversation.title, extra={'format': 'HTML'})
                else:
                    return self.bot.send_message(m, self.bot.trans.plugins.administration.strings.not_added % m.conversation.title, extra={'format': 'HTML'})

            else:
                return self.bot.send_message(m, self.bot.trans.errors.no_results, extra={'format': 'HTML'})

            return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})


    def always(self, m):
        # Update group data #
        gid = str(m.conversation.id)
        if m.conversation.id < 0:
            if gid in self.groups:
                self.groups[gid].title = m.conversation.title
                self.groups[gid].messages += 1
            
            else:
                self.groups[gid] = {
                    "title": m.conversation.title,
                    "messages": 1
                }
        self.groups.store_database()

        # Update user data #
        uid = str(m.sender.id)
        if uid in self.users:
            self.users[uid].first_name = m.sender.first_name
            self.users[uid].last_name = m.sender.last_name
            self.users[uid].username = m.sender.username
            self.users[uid].messages += 1
        
        else:
            self.users[uid] = {
                "first_name": m.sender.first_name,
                "last_name": m.sender.last_name,
                "username": m.sender.username,
                "messages": 1
            }
        self.users.store_database()
Пример #28
0
 def __init__(self, bot):
     self.bot = bot
     self.commands = self.bot.trans.plugins.reminders.commands
     self.description = self.bot.trans.plugins.reminders.description
     self.reminders = AutosaveDict("polaris/data/%s.reminders.json" % self.bot.name)
     self.sort_reminders()
Пример #29
0
def del_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)
    tags[target].remove(tag)
    tags.store_database()
Пример #30
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.pins.commands
        self.description = self.bot.trans.plugins.pins.description
        self.pins = AutosaveDict('polaris/data/%s.pins.json' % self.bot.name)
        self.update_triggers()

    # Plugin action #
    def run(self, m):
        input = get_input(m)

        # List all pins #
        if is_command(self, 1, m.content):
            pins = []
            for pin in self.pins:
                if self.pins[pin].creator == m.sender.id:
                    pins.append(pin)

            if len(pins) > 0:
                text = self.bot.trans.plugins.pins.strings.pins % len(pins)
                for pin in pins:
                    text += '\n • #%s' % pin

            else:
                text = self.bot.trans.plugins.pins.strings.no_pins

            # If the message is too long send an error message instead #
            if len(text) < 4096:
                return self.bot.send_message(m, text, extra={'format': 'HTML'})
            else:
                return self.bot.send_message(m, self.bot.trans.errors.unknown, extra={'format': 'HTML'})

        # Add a pin #
        elif is_command(self, 2, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not m.reply:
                return self.bot.send_message(m, self.bot.trans.errors.needs_reply, extra={'format': 'HTML'})

            if input in self.pins:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.already_pinned % input, extra={'format': 'HTML'})

            self.pins[input] = {
                'content': m.reply.content.replace('<','&lt;').replace('>','&gt;'),
                'creator': m.sender.id,
                'type': m.reply.type
            }
            
            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.pinned % input, extra={'format': 'HTML'})

        # Remove a pin #
        elif is_command(self, 3, m.content):
            if not input:
                return self.bot.send_message(m, self.bot.trans.errors.missing_parameter, extra={'format': 'HTML'})

            if input.startswith('#'):
                input = input.lstrip('#')
            input = input.lower()

            if not input in self.pins:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.not_found % input, extra={'format': 'HTML'})

            if not m.sender.id == self.pins[input]['creator']:
                return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.not_creator % input, extra={'format': 'HTML'})

            del(self.pins[input])
            self.pins.store_database()
            self.update_triggers()

            return self.bot.send_message(m, self.bot.trans.plugins.pins.strings.unpinned % input, extra={'format': 'HTML'})

        # Check what pin was triggered #
        else:
            # Finds the first 3 pins of the message and sends them. #
            pins = findall(r"#(\w+)", m.content.lower())
            count = 3

            for pin in pins:
                if pin in self.pins:
                    # You can reply with a pin and the message will reply too. #
                    if m.reply:
                        reply = m.reply.id
                    else:
                        reply = m.id

                    self.bot.send_message(m, self.pins[pin]['content'], self.pins[pin]['type'], extra={'format': 'HTML'}, reply = reply)
                    count -= 1

                if count == 0:
                    return


    def update_triggers(self):
        # Add new triggers #
        for pin, attributes in self.pins.items():
            if not next((i for i,d in enumerate(self.commands) if 'command' in d and d.command == '#' + pin), None):
                self.commands.append({
                    'command': '#' + pin,
                    'hidden': True
                })

        # Remove unused triggers #
        for command in self.commands:
            if 'hidden' in command and command.hidden and not command.command.lstrip('#') in self.pins:
                self.commands.remove(command)
Пример #31
0
class plugin(object):
    # Loads the text strings from the bots language #

    def __init__(self, bot):
        self.bot = bot
        self.commands = self.bot.trans.plugins.reminders.commands
        self.description = self.bot.trans.plugins.reminders.description
        self.reminders = AutosaveDict('polaris/data/%s.reminders.json' %
                                      self.bot.name)
        self.sort_reminders()

    # Plugin action #
    def run(self, m):
        input = get_input(m, ignore_reply=False)
        if not input:
            return self.bot.send_message(
                m,
                self.bot.trans.errors.missing_parameter,
                extra={'format': 'HTML'})

        self.reminders.load_database()
        # Lists all pins #
        delay = first_word(input)
        if delay:
            delaytime = delay[:-1]
            unit = delay[-1:]
            if not is_int(delaytime) or is_int(unit):
                return self.bot.send_message(
                    m, self.bot.trans.plugins.reminders.strings.wrongdelay)

        alarm = time() + self.to_seconds(delaytime, unit)

        text = all_but_first_word(input)
        if not text:
            return self.bot.send_message(
                m, self.bot.trans.plugins.reminders.strings.noreminder)

        reminder = DictObject(OrderedDict())
        reminder.id = '%s:%s' % (m.sender.id, time())
        reminder.alarm = alarm
        reminder.chat_id = m.conversation.id
        reminder.text = text
        reminder.first_name = m.sender.first_name
        reminder.username = m.sender.username

        self.reminders.list.append(reminder)
        self.sort_reminders()
        self.reminders.store_database()

        if unit == 's':
            delay = delay.replace('s', ' segundos')
        if unit == 'm':
            delay = delay.replace('m', ' minutos')
        if unit == 'h':
            delay = delay.replace('h', ' horas')
        if unit == 'd':
            delay = delay.replace('d', ' días')

        message = self.bot.trans.plugins.reminders.strings.added % (
            m.sender.first_name, delay, text)

        return self.bot.send_message(m, message, extra={'format': 'HTML'})

    def cron(self):
        self.reminders.load_database()
        while len(self.reminders.list
                  ) > 0 and self.reminders.list[0].alarm < time():
            reminder = self.reminders.list[0]
            text = '<i>%s</i>\n - %s' % (reminder.text, reminder.first_name)
            if reminder.username:
                text += ' (@%s)' % reminder.username

            m = Message(None, Conversation(reminder.chat_id), None, None)
            self.bot.send_message(m, text, extra={'format': 'HTML'})
            self.reminders.list.remove(reminder)
            self.sort_reminders()

    @staticmethod
    def to_seconds(delaytime, unit):
        if unit == 's':
            return float(delaytime)
        elif unit == 'm':
            return float(delaytime) * 60
        elif unit == 'h':
            return float(delaytime) * 60 * 60
        elif unit == 'd':
            return float(delaytime) * 60 * 60 * 24

    def sort_reminders(self):
        if not 'list' in self.reminders:
            self.reminders.list = []

        if len(self.reminders.list) > 0:
            self.reminders.list = sorted(self.reminders.list,
                                         key=lambda k: k['alarm'])

        self.reminders.store_database()
Пример #32
0
    def bot_config(name):
        config = AutosaveDict('bots/%s.json' % name)

        i = 1
        finished = False
        while not finished:
            text = 'Editing /bots/%s.json\n' % name

            if 'bindings' in config:
                bindings = config['bindings']
            else:
                bindings = 'telegram-bot-api'

            if 'bindings_token' in config:
                bindings_token = config['bindings_token']
            else:
                bindings_token = 'YOUR TELEGRAM BOT TOKEN'

            if 'command_start' in config:
                command_start = config['command_start']
            else:
                command_start = '/'

            if 'owner' in config:
                owner = config['owner']
            else:
                owner = 0

            if 'debug' in config:
                debug = config['debug']
            else:
                debug = False

            if 'language' in config:
                language = config['language']
            else:
                language = 'default'

            if 'plugins' in config:
                plugins = config['plugins']
            else:
                plugins = load_plugin_list()

            if 'api_keys' in config:
                api_keys = config['api_keys']
            else:
                api_keys = {}

            text += '(0) Finish editing\n'
            text += '(1) bindings: %s\n' % bindings
            text += '(2) bindings_token: %s\n' % bindings_token
            text += '(3) command_start: %s\n' % command_start
            text += '(4) owner: %s\n' % owner
            text += '(5) debug: %s\n' % debug
            text += '(6) language: %s\n' % language
            text += '(7) plugins: %s\n' % plugins
            text += '(8) api_keys: %s\n' % api_keys

            option = int(input(text))
            if option == 0:
                print('Saving all values to "bots/%s.json".' % name)
                config.bindings = bindings
                config.bindings_token = bindings_token
                config.command_start = command_start
                config.owner = owner
                config.debug = debug
                config.language = language
                config.plugins = plugins
                config.api_keys = api_keys
                finished = True

            elif option == 1:
                option = input(
                    'What bindings want to use? (Current value: "%s")\n' %
                    bindings)
                config.bindings = option
Пример #33
0
def del_tag(bot, target, tag):
    tags = AutosaveDict('polaris/data/%s.tags.json' % bot.name)
    tags[target].remove(tag)
    tags.store_database()