Ejemplo n.º 1
0
async def addme(bot, event, *args):
    """let a user add himself to a conversation

    Args:
        bot: HangupsBot instance
        event: event.ConversationEvent instance
        args: tuple, additional words passed to the command
    """
    if not args:
        raise commands.Help(_("supply the id of the conversation to join"))

    if args[0] not in bot.conversations:
        raise commands.Help(_("I am not attending this conversation"))

    await addusers(bot, event, *[event.user_id.chat_id, "into", args[0]])
Ejemplo n.º 2
0
def start():
    global client
    if client is not None:
        client.logout()
        del client

    client = imp.Imp()
    client.login(imp.internal_config['discord']['email'], imp.internal_config['discord']['password'])
    client.register_command(commands.Countdown(), 'countdown')
    client.register_command(commands.IsUp(), 'isup')
    client.register_command(commands.PyEval(), 'py')
    client.register_command(commands.Wolfram(), 'wa')
    client.register_command(commands.Calc(), 'calc')
    client.register_command(commands.Reload(), 'reload')
    client.register_command(commands.Me(), "me")
    client.register_command(commands.Ignore(), "ignore")
    client.register_command(commands.Roll(), "roll")
    client.register_command(commands.Everyone(), "everyone")
    client.register_command(commands.Whois(), "whois")
    client.register_command(commands.Ping(), "ping")
    client.register_command(commands.Save(), "save")
    client.register_command(commands.Load(), "load")
    client.register_command(commands.Help(), "help")
    client.register_command(commands.Kill(), "kill")
    client.register_command(commands.Info(), "info")
    client.register_command(commands.Set(), "set")
    client.register_command(commands.Get(), "get")
    client.register_command(commands.Echo(), "echo")
    client.register_command(commands.Awesome(), "awesome")

    updater_thread = updater.GitUpdater()
    updater_thread.start()
    client.run()
Ejemplo n.º 3
0
async def createconversation(bot, dummy, *args):
    """create a new conversation with given users

    Args:
        bot: HangupsBot instance
        dummy: event.ConversationEvent instance
        args: tuple, additional words passed to the command
    """
    user_ids = [chat_id for chat_id in set(args)
                if len(chat_id) == 21 and chat_id.isdigit()]

    if not user_ids:
        raise commands.Help('supply G+ Ids to add')

    logger.info("createconversation: %s", user_ids)

    _response = await bot.create_conversation(
        hangups.hangouts_pb2.CreateConversationRequest(
            request_header=bot.get_request_header(),
            type=hangups.hangouts_pb2.CONVERSATION_TYPE_GROUP,
            client_generated_id=bot.get_client_generated_id(),
            invitee_id=[hangups.hangouts_pb2.InviteeID(gaia_id=chat_id)
                        for chat_id in user_ids]))
    new_conversation_id = _response.conversation.conversation_id.id

    return (new_conversation_id, _("<i>conversation created</i>"))
Ejemplo n.º 4
0
async def addusers(bot, event, *args):
    """add users from a conversation

    Args:
        bot: HangupsBot instance
        event: event.ConversationEvent instance
        args: tuple, additional words passed to the command
    """
    list_add = []
    target_conv = event.conv_id

    state = ["adduser"]

    for parameter in args:
        if parameter == "into":
            state.append("targetconv")
        else:
            if state[-1] == "adduser":
                list_add.append(parameter)
            elif state[-1] == "targetconv":
                target_conv = parameter
                state.pop()
            else:
                raise commands.Help("UNKNOWN STATE: {}".format(state[-1]))

    list_add = list(set(list_add))
    added = 0
    if list_add:
        added = await _batch_add_users(bot, target_conv, list_add)
        logger.info("addusers: %s added to %s", added, target_conv)
Ejemplo n.º 5
0
async def kick(bot, event, *args):
    """refresh the a conversation without certain users

    Args:
        bot: HangupsBot instance
        event: event.ConversationEvent instance
        args: tuple, additional words passed to the command
    """
    parameters = list(args)

    source_conv = event.conv_id
    remove = set()
    test = False
    quietly = False

    for parameter in parameters:
        if parameter in bot.conversations[source_conv]["participants"]:
            remove.add(parameter)
        elif parameter in bot.conversations:
            source_conv = parameter
        elif parameter == _("test"):
            test = True
        elif parameter == _("quietly"):
            quietly = True
        else:
            raise commands.Help(_("supply optional conversation id and valid "
                                  "user ids to kick"))

    if not remove:
        raise commands.Help(_("supply at least one valid user id to kick"))

    arguments = ["refresh", source_conv, "without"] + list(remove)

    if test:
        arguments.append(_("test"))

    if quietly:
        arguments.append(_("quietly"))

    await commands.command.run(bot, event, *arguments)
Ejemplo n.º 6
0
def initialize_commands():
    commands.register(Quit())
    commands.register(Walk())
    commands.register(Walk('north'))
    commands.register(Walk('east'))
    commands.register(Walk('south'))
    commands.register(Walk('west'))
    commands.register(RoomAdd())
    commands.register(RoomAddExit())
    commands.register(RoomFind())
    commands.register(RoomAddEvent())
    commands.register(WorldList())

    commands.register(commands.Help())
Ejemplo n.º 7
0
 def __init__(self):
     self.options = []
     self.globalOptions = {
         "q": commands.QuitGame(),
         "i": commands.Inventory(),
         "f": commands.Fight(),
         "m": commands.Map(),
         "h": commands.Help(),
         "s": commands.Save(),
         "b": commands.Back()
     }
     self.content = False
     self.stats = False
     self.optionWidth = 10
     self.clear = True
     self.name = "no-name"
     self.player = None
Ejemplo n.º 8
0
def parse(cmd):
    if cmd == '':
        return commands.Repeat()

    elif len(cmd) == 1 and cmd.isdigit():
        rank = int(cmd)
        return commands.Frequent(rank)

    elif cmd == 'h':  return commands.Human()
    elif cmd == 'r':  return commands.Rated()
    elif cmd == '/':  return commands.Root()
    elif cmd == '?':  return commands.Help()
    elif cmd == '??': return commands.MoreHelp()
    elif cmd == 't':  return commands.HelpTopic('t')
    elif cmd == 'd':  return commands.HelpTopic('d')
    elif cmd == 'm':  return commands.HelpTopic('m')

    elif _REGEX_UP.fullmatch(cmd):
        return commands.Up(len(cmd))

    elif _REGEX_DAYS.fullmatch(cmd):
        # TODO is there a good way to avoid duplicating the .fullmatch() call?
        days_str = _REGEX_DAYS.fullmatch(cmd).group(1)
        days = int(days_str)
        return commands.Days(days)

    elif _REGEX_MONTHS.fullmatch(cmd):
        months_str = _REGEX_MONTHS.fullmatch(cmd).group(1)
        months = int(months_str)
        return commands.Months(months)

    elif _REGEX_TIME_CONTROL.fullmatch(cmd):
        minutes_str = _REGEX_TIME_CONTROL.fullmatch(cmd).group(1)
        minutes = int(minutes_str)
        return commands.TimeControl(minutes)

    else:  # TODO maybe want a regex for moves?
        return commands.Move(cmd)
Ejemplo n.º 9
0
import pytest


@pytest.mark.parametrize('input,expected', [
    ('', commands.Repeat()),

    ('0', commands.Frequent(0)),
    ('1', commands.Frequent(1)),
    ('5', commands.Frequent(5)),
    ('9', commands.Frequent(9)),
    # but not multiple digits

    ('h', commands.Human()),
    ('r', commands.Rated()),
    ('/', commands.Root()),
    ('?', commands.Help()),
    ('??', commands.MoreHelp()),

    ('-', commands.Up(1)),
    ('--', commands.Up(2)),
    ('-----', commands.Up(5)),

    ('t', commands.HelpTopic('t')),
    ('2t', commands.TimeControl(2)),
    ('20t', commands.TimeControl(20)),

    ('d', commands.HelpTopic('d')),
    ('m', commands.HelpTopic('m')),
    ('3d', commands.Days(3)),
    ('21d', commands.Days(21)),
    ('7m', commands.Months(7)),
Ejemplo n.º 10
0
 def testHelper(self):
     helpCommand = commands.Help()
     expected = 'This is the help with argument query'
     self.assertEqual(expected, helpCommand.execute('query'), "help msg is not the same")
Ejemplo n.º 11
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from bot import Bot
import commands
import filters
import reactions
from mathCommand import Math

bot = Bot("lambotirc", "card.freenode.net", 6666, "#redeclipse", commandSymbol = '!')

bot.registerCommand(commands.Action())
bot.registerCommand(commands.Dice())
bot.registerCommand(commands.Help())
bot.registerCommand(commands.Hug())
bot.registerCommand(commands.Icecream())
bot.registerCommand(commands.Kick())
bot.registerCommand(commands.Pray())
bot.registerCommand(commands.Postfix())
bot.registerCommand(commands.Say())
bot.registerCommand(commands.Shrug())
bot.registerCommand(commands.Surprise())
bot.registerCommand(commands.UUID())

bot.registerCommand(Math())

bot.registerFilter(filters.REDiscord())

bot.registerReaction(reactions.Respond())
Ejemplo n.º 12
0
async def refresh(bot, event, *args):
    """recreate a conversation and remove or add certain users

    Args:
        bot: HangupsBot instance
        event: event.ConversationEvent instance
        args: tuple, additional words passed to the command
    """
    #TODO(das7pad): refactor into smaller functions
    parameters = list(args)

    test = False
    quietly = False
    source_conv = False
    renameold = True
    list_removed = []
    list_added = []

    state = ["conversation"]

    for parameter in parameters:
        if parameter == _("remove") or parameter == _("without"):
            state.append("removeuser")
        elif parameter == _("add") or parameter == _("with"):
            state.append("adduser")
        elif parameter == _("conversation"):
            state.append("conversation")
        elif parameter == _("quietly"):
            quietly = True
            renameold = False
        elif parameter == _("test"):
            test = True
        elif parameter == _("norename"):
            renameold = False
        else:
            if state[-1] == "adduser":
                list_added.append(parameter)
                if parameter in list_removed:
                    list_removed.remove(parameter)

            elif state[-1] == "removeuser":
                list_removed.append(parameter)
                if parameter in list_added:
                    list_added.remove(parameter)

            elif state[-1] == "conversation":
                source_conv = parameter

            else:
                raise commands.Help("UNKNOWN STATE: {}".format(state[-1]))

    list_removed = list(set(list_removed))

    if not source_conv:
        raise commands.Help("conversation id not supplied")

    if source_conv not in bot.conversations:
        raise commands.Help(_("conversation {} not found").format(source_conv))

    if bot.conversations[source_conv]["type"] != "GROUP":
        raise commands.Help(_("conversation %s is not a GROUP") % source_conv)

    new_title = bot.conversations.get_name(source_conv)
    old_title = _("[DEFUNCT] {}".format(new_title))

    text_removed_users = []
    for user in bot.get_users_in_conversation(source_conv):
        if user.id_.chat_id not in list_removed:
            list_added.append(user.id_.chat_id)
        else:
            text_removed_users.append(
                "<i>{}</i> ({})".format(user.full_name, user.id_.chat_id))

    list_added = list(set(list_added))

    logger.debug("refresh: from conversation %s removed %s added %s",
                 source_conv, len(list_removed), len(list_added))

    if test:
        return _("<b>refresh:</b> {}\n"
                 "<b>rename old: {}</b>\n"
                 "<b>removed {}:</b> {}\n"
                 "<b>added {}:</b> {}").format(
                     source_conv,
                     old_title if renameold else _("<em>unchanged</em>"),
                     len(text_removed_users),
                     ", ".join(text_removed_users) or _("<em>none</em>"),
                     len(list_added),
                     " ".join(list_added) or _("<em>none</em>"))

    if len(list_added) <= 1:
        return _("<b>nobody to add in the new conversation</b>")

    _response = await bot.create_conversation(
        hangups.hangouts_pb2.CreateConversationRequest(
            request_header=bot.get_request_header(),
            type=hangups.hangouts_pb2.CONVERSATION_TYPE_GROUP,
            client_generated_id=bot.get_client_generated_id(),
            invitee_id=[]))
    new_conversation_id = _response.conversation.conversation_id.id

    await bot.coro_send_message(new_conversation_id,
                                _("<i>refreshing group...</i>\n"))
    await asyncio.sleep(1)
    await _batch_add_users(bot, new_conversation_id, list_added)
    await bot.coro_send_message(new_conversation_id,
                                _("<i>all users added</i>\n"))
    await asyncio.sleep(1)
    await commands.command.run(
        bot, event, *["convrename", "id:" + new_conversation_id, new_title])

    if renameold:
        await commands.command.run(
            bot, event, *["convrename", "id:" + source_conv, old_title])

    if not quietly:
        await bot.coro_send_message(source_conv,
                                    _("<i>group has been obsoleted</i>"))

    return _("refreshed: <b><pre>{}</pre></b> "
             "(original id: <pre>{}</pre>).\n"
             "new conversation id: <b><pre>{}</pre></b>.\n"
             "removed {}: {}").format(new_title,
                                      source_conv,
                                      new_conversation_id,
                                      len(text_removed_users),
                                      (", ".join(text_removed_users)
                                       or _("<em>none</em>")))