def submit_tip(tip_data): """ Sends the tip to the Changecoin API and returns an output message """ text = tip_data['message'] out = "" bot = SlackBot() response = bot.send_tip(**tip_data) try: if response.get("error_code") == "invalid_sender": out = MESSAGES["get_started"] elif response.get("error_code") == "duplicate_context_uid": out = MESSAGES["duplicate"] elif response.get("error_message"): if response.get("error_code") in [ "tip_limit", "wallet_error", "pocket_error" ]: out = "This tip cannot be completed" else: out = response.get("error_message") elif response.get("state") in ["ok", "accepted"]: tip = response["tip"] if tip["status"] == "out for delivery": out += MESSAGES["out_for_delivery"].format( amount_display=tip["amount_display"], receiver=tip["receiver"]) elif tip["status"] == "finished": out += MESSAGES["finished"].format( amount_display=tip["amount_display"], receiver=tip["receiver"], img_url=tip['meta'].get('tip_img_url', '')) out = append_image_response(text, out) if "+debug" in text: out += "\n```\n%s\n```" % json.dumps(response, indent=2) except Exception as e: if "+debug" in text: return "output formatting error with: {}".format(e) return out
def pipeline(city, slackbot, export, sitedata, sitedata_format, cdrdata, cdrdata_format, net_analysis, vis, sampling, sample_size): logging.config.dictConfig(logger_config) # --------------------------------------- # Get Params and Constants, Load data # --------------------------------------- nest = DataHandler(city, slackbot, export, sitedata, sitedata_format, cdrdata, cdrdata_format, net_analysis, vis, sampling, sample_size) if nest.click_params.sitedata: # ----------------------- # Preprocess Museum data # ----------------------- site_data = MuseumDataPreProcess(click_params=nest.click_params, params=nest.params, site_raw_data=nest.site_raw_data) # --------------------------------------- # Site Data Analysis # --------------------------------------- SiteAnalysis(click_params=nest.click_params, params=nest.params, data_feature_extracted=site_data.data_feature_extracted) if nest.click_params.net_analysis: # --------------------------------------- # Network Analysis # --------------------------------------- network_analysis = NetworkAnalysis( params=nest.params, data=site_data.data_feature_extracted) if nest.click_params.vis: # -------------------------------------------- # Create Fountain Visualization of museum data # -------------------------------------------- FountainViz(network_analysis=network_analysis, museum_data=site_data) if nest.click_params.cdrdata: # -------------------- # Preprocess Cdr data # -------------------- cdr_data = CDRPreProcess(click_params=nest.click_params, params=nest.params, cdr_raw_data=nest.cdr_raw_data) # --------------------------------------- # CDR Data Analysis # --------------------------------------- CDRAnalysis(params=nest.params, data_feature_extracted=cdr_data.data_feature_extracted) if slackbot: SlackBot(nest, network_analysis, channel='city-flows-bot')
def tip(request): user_name = request.POST.get("user_name") # TODO tagging for usernames # Create SlackUser. This is used for tagging SlackUser.objects.get_or_create( name=user_name, team_id=request.POST.get("team_id"), user_id=request.POST.get("user_id"), ) text = request.POST.get("text", "") # Check for mention in the format of @userId123-_. (only grab first) mention_match = re.search('@([A-Za-z0-9-_.]+)', text) if not mention_match: # Do they want help? if "help" in text: return JsonResponse({ "text": MESSAGES["help"].format(user_name=user_name), "response_type": "in_channel" }) else: # Temporarily commenting out the following because Cleverbot now has ads # # Say something clever # response = get_clever_response(user_id, text) # response = append_image_response(text, response) # return JsonResponse({"text": response, "username": "******"}) return JsonResponse({ "text": MESSAGES["help"].format(user_name=user_name), "response_type": "in_channel" }) receiver = mention_match.group(1) # Submit the tip team_domain = request.POST.get("team_domain") tip_data = { "sender": "%s@%s" % (user_name, team_domain), "receiver": "%s@%s" % (receiver, team_domain), "message": text, "context_uid": SlackBot().unique_id(request.POST.copy()), "meta": {} } for meta_field in [ "token", "team_id", "channel_id", "channel_name", "user_id", "user_name", "command" ]: tip_data["meta"][meta_field] = request.POST.get(meta_field) out = submit_tip(tip_data) return JsonResponse({"text": out, "response_type": "in_channel"})
def test_unique_id(self): bot = SlackBot() post_data = { "token": "madeuptoken", "team_id": "T0001", "channel_id": "C2147483705", "channel_name": "test", "user_id": "U2147483697", "user_name": "Steve", "command": "/tip", "text": "@tippee $1" } hash1 = bot.unique_id(post_data) hash2 = bot.unique_id(post_data) self.assertEqual(hash1, hash2) post_data["text"] = "@tippee $2" hash3 = bot.unique_id(post_data) self.assertNotEqual(hash1, hash3)
def submit_tip(tip_data): """ Sends the tip to the Changecoin API and returns an output message """ text = tip_data['message'] out = "" bot = SlackBot() response = bot.send_tip(**tip_data) try: if response.get("error_code") == "invalid_sender": out = MESSAGES["get_started"] elif response.get("error_code") == "duplicate_context_uid": out = MESSAGES["duplicate"] elif response.get("error_message"): if response.get("error_code") in ["tip_limit", "wallet_error", "pocket_error"]: out = "This tip cannot be completed" else: out = response.get("error_message") elif response.get("state") in ["ok", "accepted"]: tip = response["tip"] if tip["status"] == "out for delivery": out += MESSAGES["out_for_delivery"].format(amount_display=tip["amount_display"], receiver=tip["receiver"]) elif tip["status"] == "finished": out += MESSAGES["finished"].format(amount_display=tip["amount_display"], receiver=tip["receiver"], img_url=tip['meta'].get('tip_img_url', '')) out = append_image_response(text, out) if "+debug" in text: out += "\n```\n%s\n```" % json.dumps(response, indent=2) except Exception as e: if "+debug" in text: return "output formatting error with: {}".format(e) return out
def command_webhook(request): """ Handle data from a webhook """ print(json.dumps(request.POST.copy(), indent=2)) # Do we have this user? user_name = request.POST.get("user_name") user_id = request.POST.get("user_id") slack_sender, created = SlackUser.objects.get_or_create( name=user_name, team_id=request.POST.get("team_id"), user_id=request.POST.get("user_id"), ) if created: return JsonResponse({"text": MESSAGES["greeting"].format(user_name=user_name, get_started=MESSAGES["get_started"])}) text = request.POST.get("text", "") # Check for mention in the format of <@$userid> (only grab first) mention_match = re.search('<@(U[A-Z0-9]+)>', text) if not mention_match: # Do they want help? if "help" in text: return JsonResponse({"text": MESSAGES["help"].format(user_name=user_name)}) else: # Say something clever response = get_clever_response(user_id, text) response = append_image_response(text, response) return JsonResponse({"text": response, "username": "******"}) slack_receiver = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=mention_match.group(1)).first() if not slack_receiver: return JsonResponse({"text": MESSAGES["unknown_receiver"].format(user_name=user_name)}) # Substitute the @username back in (for each mention) for at_user_id in re.findall('(<@U[A-Z0-9]+>)', text): user_id_match = re.search('<@(U[A-Z0-9]+)>', at_user_id) if not user_id_match: continue user_id = user_id_match.group(1) if not user_id: continue slack_user = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=user_id).first() if not slack_user: continue text = text.replace(at_user_id, '@%s' % slack_user.name) # Submit the tip bot = SlackBot() team_domain = request.POST.get("team_domain") tip_data = { "sender": "%s@%s" % (slack_sender.name, team_domain), "receiver": "%s@%s" % (slack_receiver.name, team_domain), "message": text, "context_uid": bot.unique_id(request.POST.copy()), "meta": {} } for meta_field in ["token", "team_id", "channel_id", "channel_name", "user_id", "user_name", "command"]: tip_data["meta"][meta_field] = request.POST.get(meta_field) if request.POST.get("noop"): return JsonResponse({"text": "Hi!"}) response = bot.send_tip(**tip_data) try: out = "" if response.get("error_code") == "invalid_sender": out = MESSAGES["get_started"] elif response.get("error_code") == "duplicate_context_uid": out = MESSAGES["duplicate"] elif response.get("error_message"): if response.get("error_code") in ["tip_limit", "wallet_error", "pocket_error"]: out = "This tip cannot be completed" else: out = response.get("error_message") elif response.get("state") in ["ok", "accepted"]: tip = response["tip"] if tip["status"] == "out for delivery": out += MESSAGES["out_for_delivery"].format(amount_display=tip["amount_display"], receiver=tip["receiver"]) elif tip["status"] == "finished": out += MESSAGES["finished"].format(amount_display=tip["amount_display"], receiver=tip["receiver"], img_url=tip['meta'].get('tip_img_url', '')) out = append_image_response(text, out) if "+debug" in text: out += "\n```\n%s\n```" % json.dumps(response, indent=2) except Exception as e: if "+debug" in text: return JsonResponse({"text": "output formatting error with: {}".format(e)}) return JsonResponse({"text": out})
def command_webhook(request): """ Handle data from a webhook """ print(json.dumps(request.POST.copy(), indent=2)) # Do we have this user? user_name = request.POST.get("user_name") user_id = request.POST.get("user_id") slack_sender, created = SlackUser.objects.get_or_create( name=user_name, team_id=request.POST.get("team_id"), user_id=request.POST.get("user_id"), ) if created: return JsonResponse({ "text": MESSAGES["greeting"].format(user_name=user_name, get_started=MESSAGES["get_started"]) }) text = request.POST.get("text", "") # Check for mention in the format of <@$userid> (only grab first) mention_match = re.search('<@(U[A-Z0-9]+)>', text) if not mention_match: # Do they want help? if "help" in text: return JsonResponse( {"text": MESSAGES["help"].format(user_name=user_name)}) else: # Say something clever response = get_clever_response(user_id, text) response = append_image_response(text, response) return JsonResponse({ "text": response, "username": "******" }) slack_receiver = SlackUser.objects.filter( team_id=slack_sender.team_id, user_id=mention_match.group(1)).first() if not slack_receiver: return JsonResponse( {"text": MESSAGES["unknown_receiver"].format(user_name=user_name)}) # Substitute the @username back in (for each mention) for at_user_id in re.findall('(<@U[A-Z0-9]+>)', text): user_id_match = re.search('<@(U[A-Z0-9]+)>', at_user_id) if not user_id_match: continue user_id = user_id_match.group(1) if not user_id: continue slack_user = SlackUser.objects.filter(team_id=slack_sender.team_id, user_id=user_id).first() if not slack_user: continue text = text.replace(at_user_id, '@%s' % slack_user.name) # Submit the tip bot = SlackBot() team_domain = request.POST.get("team_domain") tip_data = { "sender": "%s@%s" % (slack_sender.name, team_domain), "receiver": "%s@%s" % (slack_receiver.name, team_domain), "message": text, "context_uid": bot.unique_id(request.POST.copy()), "meta": {} } for meta_field in [ "token", "team_id", "channel_id", "channel_name", "user_id", "user_name", "command" ]: tip_data["meta"][meta_field] = request.POST.get(meta_field) if request.POST.get("noop"): return JsonResponse({"text": "Hi!"}) response = bot.send_tip(**tip_data) try: out = "" if response.get("error_code") == "invalid_sender": out = MESSAGES["get_started"] elif response.get("error_code") == "duplicate_context_uid": out = MESSAGES["duplicate"] elif response.get("error_message"): if response.get("error_code") in [ "tip_limit", "wallet_error", "pocket_error" ]: out = "This tip cannot be completed" else: out = response.get("error_message") elif response.get("state") in ["ok", "accepted"]: tip = response["tip"] if tip["status"] == "out for delivery": out += MESSAGES["out_for_delivery"].format( amount_display=tip["amount_display"], receiver=tip["receiver"]) elif tip["status"] == "finished": out += MESSAGES["finished"].format( amount_display=tip["amount_display"], receiver=tip["receiver"], img_url=tip['meta'].get('tip_img_url', '')) out = append_image_response(text, out) if "+debug" in text: out += "\n```\n%s\n```" % json.dumps(response, indent=2) except Exception as e: if "+debug" in text: return JsonResponse( {"text": "output formatting error with: {}".format(e)}) return JsonResponse({"text": out})
def outgoing_webhook(request): # Do we have this user? user_name = request.POST.get("user_name") user_id = request.POST.get("user_id") slack_sender, created = SlackUser.objects.get_or_create( name=user_name, team_id=request.POST.get("team_id"), user_id=request.POST.get("user_id"), ) def formatted_response(response_text): if random.random() < .2: # Every 5th message or so will encourage users to upgrade to Slash commands response_text += " " response_text += MESSAGES['upgrade_to_slash_commands'] return JsonResponse({"text": response_text, "response_type": "in_channel"}) if created: return formatted_response(MESSAGES["greeting"].format(user_name=user_name, get_started=MESSAGES["get_started"])) text = request.POST.get("text", "") # Check for mention in the format of <@$userid> (only grab first) mention_match = re.search('<@(U[A-Z0-9]+)>', text) if not mention_match: # Do they want help? if "help" in text: return formatted_response(MESSAGES["help_webhooks"].format(user_name=user_name)) else: return formatted_response(MESSAGES["help_webhooks"].format(user_name=user_name)) # Temporarily commenting out the following because Cleverbot now has ads # # Say something clever # response = get_clever_response(user_id, text) # response = append_image_response(text, response) # return JsonResponse({"text": response, "username": "******"}) slack_receiver = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=mention_match.group(1)).first() if not slack_receiver: return formatted_response(MESSAGES["unknown_receiver"].format(user_name=user_name)) # Substitute the @username back in (for each mention) for at_user_id in re.findall('(<@U[A-Z0-9]+>)', text): user_id_match = re.search('<@(U[A-Z0-9]+)>', at_user_id) if not user_id_match: continue user_id = user_id_match.group(1) if not user_id: continue slack_user = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=user_id).first() if not slack_user: continue text = text.replace(at_user_id, '@%s' % slack_user.name) # Submit the tip team_domain = request.POST.get("team_domain") tip_data = { "sender": "%s@%s" % (slack_sender.name, team_domain), "receiver": "%s@%s" % (slack_receiver.name, team_domain), "message": text, "context_uid": SlackBot().unique_id(request.POST.copy()), "meta": {} } for meta_field in ["token", "team_id", "channel_id", "channel_name", "user_id", "user_name", "command"]: tip_data["meta"][meta_field] = request.POST.get(meta_field) out = submit_tip(tip_data) return formatted_response(out)
from bot import SlackBot token = 'yourtoken' # Slack token, obtainable via https://api.slack.com/tokens if __name__ == '__main__': sb = SlackBot(token) sb.run()
def command_webhook(request): """ Handle data from a webhook """ print(json.dumps(request.POST.copy(), indent=2)) # Do we have this user? user_name = request.POST.get("user_name") slack_sender, created = SlackUser.objects.get_or_create( name=user_name, team_id=request.POST.get("team_id"), user_id=request.POST.get("user_id"), ) if created: return JsonResponse({"text": MESSAGES["greeting"].format(user_name=user_name, get_started=MESSAGES["get_started"])}) text = request.POST.get("text", "") # Check for mention in the format of <@$userid> mention_match = re.search('<@(U[A-Z0-9]+)>', text) if not mention_match: # Do they want help? if "help" in text: return JsonResponse({"text": MESSAGES["help"].format(user_name=user_name)}) else: # Say something clever cb = cleverbot.Cleverbot() response = cb.ask(text.replace('changetip', '')) return JsonResponse({"text": response, "username": "******"}) slack_receiver = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=mention_match.group(1)).first() if not slack_receiver: return JsonResponse({"text": MESSAGES["unknown_receiver"].format(user_name=user_name)}) # Substitute the @username back in text = text.replace(mention_match.group(0), '@%s' % slack_receiver.name) # Submit the tip bot = SlackBot() team_domain = request.POST.get("team_domain") tip_data = { "sender": "%s@%s" % (slack_sender.name, team_domain), "receiver": "%s@%s" % (slack_receiver.name, team_domain), "message": text, "context_uid": bot.unique_id(request.POST.copy()), "meta": {} } for meta_field in ["token", "team_id", "channel_id", "channel_name", "user_id", "user_name", "command"]: tip_data["meta"][meta_field] = request.POST.get(meta_field) if request.POST.get("noop"): return JsonResponse({"text": "Hi!"}) response = bot.send_tip(**tip_data) out = "" if response.get("error_code") == "invalid_sender": out = MESSAGES["get_started"] elif response.get("error_code") == "duplicate_context_uid": out = MESSAGES["duplicate"] elif response.get("error_message"): out = response.get("error_message") elif response.get("state") in ["ok", "accepted"]: tip = response["tip"] if tip["status"] == "out for delivery": out += MESSAGES["out_for_delivery"].format(amount_display=tip["amount_display"], receiver=tip["receiver"]) elif tip["status"] == "finished": out += MESSAGES["finished"].format(amount_display=tip["amount_display"], receiver=tip["receiver"]) if "+debug" in text: out += "\n```\n%s\n```" % json.dumps(response, indent=2) return JsonResponse({"text": out})