def rsvp(bot, event, *args):
    """show/claim invite codes"""

    if len(args) == 1:
        yield from _claim_invite(bot, args[0], event.user.id_.chat_id)
    else:
        invites = []
        if bot.memory.exists(["invites"]):
            for invite_id, invite in bot.memory["invites"].items():
                if invite["user_id"] in ("*", event.user.id_.chat_id):
                    if invite["expiry"] > time.time():
                        invites.append(invite)

        if len(invites) > 0:
            lines = []
            lines.append(_("<b>Invites for {}:</b>").format(event.user.full_name))
            for invite in invites:
                conversation_name = get_conv_name(invite["group_id"])
                expiry_in_days = round((invite["expiry"] - time.time()) / 86400, 1)
                lines.append("<b>{}</b> ... {} ({} days left)".format(conversation_name, invite["id"], expiry_in_days))
            lines.append("")
            lines.append(_("<em>To claim an invite, use the rsvp command followed by the invite code</em>"))
            bot.send_html_to_conversation(event.conv_id, "<br />".join(lines))
        else:
            bot.send_html_to_conversation(event.conv_id, _("<em>no invites to display</em>"))
Esempio n. 2
0
def whereami(bot, event, *args):
    """get current conversation id"""

    bot.send_message_parsed(
      event.conv,
      _("You are at <b>{}</b>, conv_id = <i>{}</i>").format(
        get_conv_name(event.conv, truncate=True),
        event.conv.id_))
Esempio n. 3
0
def hangouts(bot, event, *args):
    """list all active hangouts.
    Use '/bot hangouts <keyword>' to search for all hangouts that has keyword in the title.
    """

    text_search = " ".join(args)
    line = "<b>List of hangouts with keyword:</b> \"{}\"<br />".format(text_search)

    for conv in bot.list_conversations():
        conv_name = get_conv_name(conv)
        if text_search.lower() in conv_name.lower(): # For blank keywords, returns True
            line += "<b>{}</b>: <i>{}</i><br />".format(conv_name, conv.id_)

    bot.send_message_parsed(event.conv, line)
def invite(bot, event, *args):
    """create invitations for users
    If the 'to' conv_id is not specified then a new conversation is created
    If the 'from' conv_id is not specified then it is assumed to be the current one
    If users are not specified then all users from 'from' conversation are invited

    /bot invite list # Lists all pending invites
    /bot invite purge # Deletes all pending invites
    """
    everyone = True
    wildcards = 0

    targetconv = False
    sourceconv = False
    list_users = []

    parameters = list(args)

    if parameters[0].isdigit():
        wildcards = int(parameters[0])
        if wildcards > 0 and wildcards < 150:
            # check allows user ids to pass-through
            del (parameters[0])
    elif parameters[0] == "list" or parameters[0] == "purge":
        # List all pending invites
        invites = []
        if bot.memory.exists(["invites"]):
            for invite_id, invite in bot.memory["invites"].items():
                # if invite["user_id"] in ("*", event.user.id_.chat_id):
                if invite["expiry"] > time.time():
                    invites.append(invite)

        if len(invites) > 0:
            lines = []
            for invite in invites:
                conversation_name = get_conv_name(invite["group_id"])
                user_id = invite["user_id"]

                if parameters[0] == "purge":
                    _remove_invite(bot, invite["id"])
                    lines.append(
                        "<b>REMOVED</b> <i>{}</i>'s invite for <b>{}</b><br />".format(user_id, conversation_name)
                    )
                else:
                    expiry_in_days = round((invite["expiry"] - time.time()) / 86400, 1)
                    lines.append(
                        "User <i>{}</i> invited to <b>{}</b> ... {} ({} days left) <br />".format(
                            user_id, conversation_name, invite["id"], expiry_in_days
                        )
                    )

            lines.append("")
            bot.send_html_to_conversation(event.conv_id, "<br />".join(lines))
        else:
            bot.send_html_to_conversation(event.conv_id, _("<em>no invites to list</em>"))
        return

    state = ["users"]
    for parameter in parameters:
        if parameter in ("to", "from", "users"):
            state.append(parameter)
        else:
            if state[-1] == "to":
                targetconv = parameter
                state.pop()
            elif state[-1] == "from":
                sourceconv = parameter
                state.pop()
            elif state[-1] == "users":
                list_users.append(parameter)
                everyone = False  # filter invitees by list_users
                wildcards = 0  # turn off wildcard invites
            else:
                raise ValueError("UNKNOWN STATE: {}".format(state[-1]))

    if not targetconv and not sourceconv:
        bot.send_html_to_conversation(event.conv_id, _("</b>Creating new conversation for invites</b>"))
        sourceconv == event.conv_id

        response = yield from bot._client.createconversation(list(), True)
        new_conversation_id = response["conversation"]["id"]["id"]
        bot.send_html_to_conversation(new_conversation_id, "<i>conversation created</i>")
        targetconv = new_conversation_id

    elif not targetconv:
        if sourceconv == event.conv_id:
            bot.send_html_to_conversation(event.conv_id, _("<b>Creating new conversation for invites</b>"))
            response = yield from bot._client.createconversation(list(), True)
            new_conversation_id = response["conversation"]["id"]["id"]
            bot.send_html_to_conversation(new_conversation_id, "<i>conversation created</i>")
            targetconv = new_conversation_id
        else:
            targetconv = event.conv_id
    elif not sourceconv:
        if len(list_users) == 0:
            if targetconv == event.conv_id:
                bot.send_html_to_conversation(
                    event.conv_id, _('<b>invite: specify "from" or explicit list of "users"</b>')
                )
                return
            else:
                sourceconv = event.conv_id

    invitations = []

    if wildcards > 0:
        invitations.append(("*", targetconv, wildcards))
    else:
        shortlisted = []
        if sourceconv:
            sourceconv_users = bot.get_users_in_conversation(sourceconv)
            for u in sourceconv_users:
                if everyone or u.id_.chat_id in list_users:
                    shortlisted.append(u.id_.chat_id)
        else:
            shortlisted = list_users

        there = bot.get_users_in_conversation(targetconv)
        invited_users = []
        for uid in shortlisted:
            if uid not in there:
                invited_users.append(uid)

        invited_users = list(set(invited_users))

        if len(invited_users) == 0:
            bot.send_html_to_conversation(event.conv_id, _("<em>invite: nobody invited</em>"))
            return

        for uid in invited_users:
            invitations.append((uid, targetconv))

    invitation_ids = []
    for invite in invitations:
        invitation_ids.append(_issue_invite(bot, *invite))

    bot.send_html_to_conversation(
        event.conv_id, _("<em>invite: {} invitations created</em>").format(len(invitation_ids))
    )
Esempio n. 5
0
def broadcast(bot, event, *args):
    """broadcast a message to chats, use with care"""
    if args:
        subcmd = args[0]
        parameters = args[1:]
        if subcmd == "info":
            """display broadcast data such as message and target rooms"""
            conv_info = ["<b>{}</b> ... {}".format(get_conv_name(_), _.id_) for _ in _internal["broadcast"]["conversations"]]
            if not _internal["broadcast"]["message"]:
                bot.send_message_parsed(event.conv, _("broadcast: no message set"))
                return
            if not conv_info:
                bot.send_message_parsed(event.conv, _("broadcast: no conversations available"))
                return
            bot.send_message_parsed(event.conv, _(
                                            "<b>message:</b><br />"
                                            "{}<br />"
                                            "<b>to:</b><br />"
                                            "{}".format(_internal["broadcast"]["message"],
                                                "<br />".join(conv_info))))
        elif subcmd == "message":
            """set broadcast message"""
            message = ' '.join(parameters)
            if message:
                if message.lower().strip().startswith(tuple([_.lower() for _ in bot._handlers.bot_command])):
                    bot.send_message_parsed(event.conv, _("broadcast: message not allowed"))
                    return
                _internal["broadcast"]["message"] = message
            else:
                bot.send_message_parsed(event.conv, _("broadcast: message must be supplied after subcommand"))
        elif subcmd == "add":
            """add conversations to a broadcast"""
            if parameters[0] == "groups":
                """add all groups (chats with users > 2)"""
                for conv in bot.list_conversations():
                    if len(conv.users) > 2:
                        _internal["broadcast"]["conversations"].append(conv)
            elif parameters[0] == "ALL":
                """add EVERYTHING - try not to use this, will message 1-to-1s as well"""
                for conv in bot.list_conversations():
                    _internal["broadcast"]["conversations"].append(conv)
            else:
                """add by wild card search of title or id"""
                search = " ".join(parameters)
                for conv in bot.list_conversations():
                    if search.lower() in get_conv_name(conv).lower() or search in conv.id_:
                        _internal["broadcast"]["conversations"].append(conv)
            _internal["broadcast"]["conversations"] = list(set(_internal["broadcast"]["conversations"]))
            bot.send_message_parsed(event.conv, _("broadcast: {} conversation(s)".format(len(_internal["broadcast"]["conversations"]))))
        elif subcmd == "remove":
            if parameters[0].lower() == "all":
                """remove all conversations from broadcast"""
                _internal["broadcast"]["conversations"] = []
            else:
                """remove by wild card search of title or id"""
                search = " ".join(parameters)
                removed = []
                for conv in _internal["broadcast"]["conversations"]:
                    if search.lower() in get_conv_name(conv).lower() or search in conv.id_:
                        _internal["broadcast"]["conversations"].remove(conv)
                        removed.append("<b>{}</b> ({})".format(get_conv_name(conv), conv.id_))
                if removed:
                    bot.send_message_parsed(event.conv, _("broadcast: removed {}".format(", ".join(removed))))
        elif subcmd == "NOW":
            """send the broadcast - no turning back!"""
            context = { "explicit_relay": True } # prevent echos across syncrooms
            for conv in _internal["broadcast"]["conversations"]:
                bot.send_message_parsed(conv, _internal["broadcast"]["message"], context=context)
            bot.send_message_parsed(event.conv, _("broadcast: message sent to {} chats".format(len(_internal["broadcast"]["conversations"]))))
        else:
            bot.send_message_parsed(event.conv, _("broadcast: /bot broadcast [info|message|add|remove|NOW] ..."))
    else:
        bot.send_message_parsed(event.conv, _("broadcast: /bot broadcast [info|message|add|remove|NOW]"))
Esempio n. 6
0
def quit(bot, event, *args):
    """stop running"""
    print(_('HangupsBot killed by user {} from conversation {}').format(event.user.full_name,
                                                                     get_conv_name(event.conv, truncate=True)))
    yield from bot._client.disconnect()