imapex / ciscosparkbot

Other
5 stars 11 forks source link

Updated code to permit webhook requests for more than just messages:created #18

Open joshand opened 6 years ago

joshand commented 6 years ago

I was in need of a bot that could monitor memberships data, so I extended this one to do that.

With the changes in the PR, the default behavior is still in tact. However, here is an example of how you would monitor memberships data:

In your main code, when you create an instance of the bot, add the "wh_resource" and "wh_event" parameters:

bot = SparkBot(bot_app_name, spark_bot_token=spark_token,
               spark_bot_url=bot_url, spark_bot_email=bot_email, debug=True,
               wh_resource="memberships", wh_event="all")

Then, add a new command for the resource you want to monitor: bot.add_command('memberships', '*', check_memberships)

Finally, add a function to handle that command. For example, I needed the bot (which is assigned to the room as a moderator) to be able to remove anyone from a room who is not in a set of whitelisted domains (i.e., to ensure that a room stays "internal-only"). This function has an additional parameter (sp in my example), which is used to directly access the SparkAPI object.

def check_memberships(sp, incoming_msg):
    wl_dom = os.getenv("WHITELIST_DOMAINS")
    if wl_dom.find("[") <= 0:
        wl_dom = '["' + wl_dom + '"]'
        wl_dom = wl_dom.replace(",", '","')

    if wl_dom and incoming_msg["event"] != "deleted":
        pemail = incoming_msg["data"]["personEmail"]
        pdom = pemail.split("@")[1]
        plist = json.loads(wl_dom)
        print(pemail, pdom, plist)
        if pdom in plist or pemail == bot_email:
            # membership check succeeded
            return ""
        else:
            # membership check failed
            print("membership failed. deleting " + incoming_msg["data"]["id"])
            sp.spark.memberships.delete(incoming_msg["data"]["id"])
            return "'" + pemail + "' was automatically removed from this space; it is restricted to only " \
                                  "internal users."
    else:
        return ""
coveralls commented 6 years ago

Pull Request Test Coverage Report for Build 47


Changes Missing Coverage Covered Lines Changed/Added Lines %
ciscosparkbot/Spark.py 27 32 84.38%
<!-- Total: 27 32 84.38% -->
Totals Coverage Status
Change from base Build 38: -0.8%
Covered Lines: 160
Relevant Lines: 172

💛 - Coveralls
coveralls commented 6 years ago

Pull Request Test Coverage Report for Build 47


Changes Missing Coverage Covered Lines Changed/Added Lines %
ciscosparkbot/Spark.py 27 32 84.38%
<!-- Total: 27 32 84.38% -->
Totals Coverage Status
Change from base Build 38: -0.8%
Covered Lines: 160
Relevant Lines: 172

💛 - Coveralls
joshand commented 5 years ago

@kecorbin Any feedback on this PR?