We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Engagement bot summary doesn't seem to be working
### Context

https://github.com/AlexsLemonade/refinebio/issues/2140

### Problem or idea

Tested today and reported no downloads in the last 7 days.

> **EngagementBot**
> There were no downloads in the last 7 days.

However there were a few that should have been counted:

```
data_refinery=> select id, created_at from data_refinery_common_dataset where is_processed='t' and email_address is not NULL order by created_at desc limit 10;
                  id                  |          created_at           
--------------------------------------+-------------------------------
 381e86b9-aea2-4d9a-8a61-338b111fe54d | 2020-03-29 13:06:28.954778+00
 eb726da7-8006-46c4-95ba-8a3bcecbd6f1 | 2020-03-26 02:26:35.196333+00
 099e7b58-dce6-4d5c-a4b6-f4d049dad866 | 2020-03-25 16:19:14.656207+00
 c4c086ef-6963-4fd8-b4e2-a7cf09c9eb68 | 2020-03-25 16:18:03.158765+00
 0716857b-211f-484c-9e2b-3e447dd5cdaf | 2020-03-25 15:34:20.155269+00
 2e7c1e1c-138b-43b1-9463-0113c64e7edb | 2020-03-25 15:19:23.577922+00
 4a2ac1ef-4e9e-4945-bdf8-00d595f99c4c | 2020-03-25 15:18:21.49652+00
 bbb30f4e-7b5f-4595-a47d-25f8d72e4a7c | 2020-03-25 15:03:55.391917+00
 eff9cbe4-c4f5-43a6-b004-6cd36f10ea15 | 2020-03-24 22:41:51.185922+00
```

### Solution or next step

Investigate why these downloads are not being reported.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `api/data_refinery_api/management/commands/post_downloads_summary.py`
Content:
```
1 import datetime
2 
3 from django.conf import settings
4 from django.core.management.base import BaseCommand
5 from django.utils import timezone
6 
7 import requests
8 
9 from data_refinery_common.models import DatasetAnnotation
10 
11 
12 class Command(BaseCommand):
13     help = "Post downloads summary to slack"
14 
15     def add_arguments(self, parser):
16         parser.add_argument(
17             "--days",
18             type=int,
19             default=7,  # default to a week
20             help=("Number of days in the past for which to build the stats"),
21         )
22         parser.add_argument(
23             "--channel",
24             type=str,
25             default="ccdl-general",
26             help=("Optional parameter to choose the channel where the message will be posted."),
27         )
28 
29     def handle(self, *args, **options):
30         days = options["days"]
31         start_time = timezone.now() - datetime.timedelta(days=-days)
32 
33         annotation_queryset = DatasetAnnotation.objects.filter(
34             created_at__gt=start_time
35         ).prefetch_related("dataset")
36         annotations = [
37             annotation
38             for annotation in annotation_queryset
39             if annotation.data["start"] and should_display_email(annotation.dataset.email_address)
40         ]
41 
42         unique_users = list(set(annotation.dataset.email_address for annotation in annotations))
43         unique_ips = list(set(annotation.data["ip"] for annotation in annotations))
44 
45         if unique_users:
46             fallback_text = "In the last {0} days, {1} users downloaded datasets from {2} locations.".format(
47                 days, len(unique_users), len(unique_ips)
48             )
49         else:
50             fallback_text = "There were no downloads in the last {0} days.".format(days)
51 
52         new_users = ""
53         returning_users = ""
54         for email in unique_users:
55             user_annotations = annotation_queryset.filter(dataset__email_address=email)
56             total_downloads = user_annotations.count()
57             unique_locations = list(set(annotation.data["ip"] for annotation in user_annotations))
58             locations = ", ".join(get_ip_location(ip) for ip in unique_locations)
59             is_new_user = DatasetAnnotation.objects.filter(
60                 created_at__lt=start_time, dataset__email_address=email
61             )
62             text = "{0} | {1} downloads from {2}\n".format(email, total_downloads, locations)
63             if is_new_user:
64                 new_users += text
65             else:
66                 returning_users += text
67 
68         blocks = [
69             {
70                 "type": "section",
71                 "text": {"type": "plain_text", "emoji": True, "text": fallback_text},
72             }
73         ]
74         if new_users:
75             blocks.append(
76                 {
77                     "type": "section",
78                     "text": {"type": "mrkdwn", "text": "*New users* \n" + new_users,},
79                 }
80             )
81         if returning_users:
82             blocks.append(
83                 {
84                     "type": "section",
85                     "text": {"type": "mrkdwn", "text": "*Returning users* \n" + returning_users,},
86                 }
87             )
88 
89         # Post to slack
90         requests.post(
91             settings.ENGAGEMENTBOT_WEBHOOK,
92             json={
93                 "username": "EngagementBot",
94                 "icon_emoji": ":halal:",
95                 "channel": "#" + options["channel"],
96                 "text": fallback_text,
97                 "blocks": blocks,
98             },
99             headers={"Content-Type": "application/json"},
100             timeout=10,
101         )
102 
103 
104 def should_display_email(email: str) -> bool:
105     """ Returns true if the given email is not associated with the CCDL suers """
106     if not email:
107         return False
108 
109     return not (
110         email.startswith("cansav09")
111         or email.startswith("arielsvn")
112         or email.startswith("jaclyn.n.taroni")
113         or email.startswith("kurt.wheeler")
114         or email.startswith("greenescientist")
115         or "@alexslemonade.org" not in email
116         or email.startswith("miserlou")
117         or email.startswith("d.prasad")
118         or email is ("daniel.himmelstein@gmail.com")
119         or email is ("dv.prasad991@gmail.com")
120     )
121 
122 
123 def get_ip_location(remote_ip):
124     try:
125         city = requests.get("https://ipapi.co/" + remote_ip + "/json/", timeout=10).json()["city"]
126     except Exception:
127         city = remote_ip
128     return city
129
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/api/data_refinery_api/management/commands/post_downloads_summary.py b/api/data_refinery_api/management/commands/post_downloads_summary.py
--- a/api/data_refinery_api/management/commands/post_downloads_summary.py
+++ b/api/data_refinery_api/management/commands/post_downloads_summary.py
@@ -28,7 +28,7 @@
 
     def handle(self, *args, **options):
         days = options["days"]
-        start_time = timezone.now() - datetime.timedelta(days=-days)
+        start_time = timezone.now() - datetime.timedelta(days=days)
 
         annotation_queryset = DatasetAnnotation.objects.filter(
             created_at__gt=start_time
@@ -105,16 +105,15 @@
     """ Returns true if the given email is not associated with the CCDL suers """
     if not email:
         return False
-
     return not (
         email.startswith("cansav09")
         or email.startswith("arielsvn")
         or email.startswith("jaclyn.n.taroni")
         or email.startswith("kurt.wheeler")
         or email.startswith("greenescientist")
-        or "@alexslemonade.org" not in email
         or email.startswith("miserlou")
         or email.startswith("d.prasad")
+        or email.endswith("@alexslemonade.org")
         or email is ("daniel.himmelstein@gmail.com")
         or email is ("dv.prasad991@gmail.com")
     )
@@ -122,7 +121,7 @@
 
 def get_ip_location(remote_ip):
     try:
-        city = requests.get("https://ipapi.co/" + remote_ip + "/json/", timeout=10).json()["city"]
+        data = requests.get("https://ipapi.co/" + remote_ip + "/json/", timeout=10).json()
+        return "{0}, {1}".format(data["city"], data["country_name"])
     except Exception:
-        city = remote_ip
-    return city
+        return remote_ip

{"golden_diff": "diff --git a/api/data_refinery_api/management/commands/post_downloads_summary.py b/api/data_refinery_api/management/commands/post_downloads_summary.py\n--- a/api/data_refinery_api/management/commands/post_downloads_summary.py\n+++ b/api/data_refinery_api/management/commands/post_downloads_summary.py\n@@ -28,7 +28,7 @@\n \n     def handle(self, *args, **options):\n         days = options[\"days\"]\n-        start_time = timezone.now() - datetime.timedelta(days=-days)\n+        start_time = timezone.now() - datetime.timedelta(days=days)\n \n         annotation_queryset = DatasetAnnotation.objects.filter(\n             created_at__gt=start_time\n@@ -105,16 +105,15 @@\n     \"\"\" Returns true if the given email is not associated with the CCDL suers \"\"\"\n     if not email:\n         return False\n-\n     return not (\n         email.startswith(\"cansav09\")\n         or email.startswith(\"arielsvn\")\n         or email.startswith(\"jaclyn.n.taroni\")\n         or email.startswith(\"kurt.wheeler\")\n         or email.startswith(\"greenescientist\")\n-        or \"@alexslemonade.org\" not in email\n         or email.startswith(\"miserlou\")\n         or email.startswith(\"d.prasad\")\n+        or email.endswith(\"@alexslemonade.org\")\n         or email is (\"daniel.himmelstein@gmail.com\")\n         or email is (\"dv.prasad991@gmail.com\")\n     )\n@@ -122,7 +121,7 @@\n \n def get_ip_location(remote_ip):\n     try:\n-        city = requests.get(\"https://ipapi.co/\" + remote_ip + \"/json/\", timeout=10).json()[\"city\"]\n+        data = requests.get(\"https://ipapi.co/\" + remote_ip + \"/json/\", timeout=10).json()\n+        return \"{0}, {1}\".format(data[\"city\"], data[\"country_name\"])\n     except Exception:\n-        city = remote_ip\n-    return city\n+        return remote_ip\n", "issue": "Engagement bot summary doesn't seem to be working\n### Context\r\n\r\nhttps://github.com/AlexsLemonade/refinebio/issues/2140\r\n\r\n### Problem or idea\r\n\r\nTested today and reported no downloads in the last 7 days.\r\n\r\n> **EngagementBot**\r\n> There were no downloads in the last 7 days.\r\n\r\nHowever there were a few that should have been counted:\r\n\r\n```\r\ndata_refinery=> select id, created_at from data_refinery_common_dataset where is_processed='t' and email_address is not NULL order by created_at desc limit 10;\r\n                  id                  |          created_at           \r\n--------------------------------------+-------------------------------\r\n 381e86b9-aea2-4d9a-8a61-338b111fe54d | 2020-03-29 13:06:28.954778+00\r\n eb726da7-8006-46c4-95ba-8a3bcecbd6f1 | 2020-03-26 02:26:35.196333+00\r\n 099e7b58-dce6-4d5c-a4b6-f4d049dad866 | 2020-03-25 16:19:14.656207+00\r\n c4c086ef-6963-4fd8-b4e2-a7cf09c9eb68 | 2020-03-25 16:18:03.158765+00\r\n 0716857b-211f-484c-9e2b-3e447dd5cdaf | 2020-03-25 15:34:20.155269+00\r\n 2e7c1e1c-138b-43b1-9463-0113c64e7edb | 2020-03-25 15:19:23.577922+00\r\n 4a2ac1ef-4e9e-4945-bdf8-00d595f99c4c | 2020-03-25 15:18:21.49652+00\r\n bbb30f4e-7b5f-4595-a47d-25f8d72e4a7c | 2020-03-25 15:03:55.391917+00\r\n eff9cbe4-c4f5-43a6-b004-6cd36f10ea15 | 2020-03-24 22:41:51.185922+00\r\n```\r\n\r\n### Solution or next step\r\n\r\nInvestigate why these downloads are not being reported.\r\n\n", "before_files": [{"content": "import datetime\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nimport requests\n\nfrom data_refinery_common.models import DatasetAnnotation\n\n\nclass Command(BaseCommand):\n    help = \"Post downloads summary to slack\"\n\n    def add_arguments(self, parser):\n        parser.add_argument(\n            \"--days\",\n            type=int,\n            default=7,  # default to a week\n            help=(\"Number of days in the past for which to build the stats\"),\n        )\n        parser.add_argument(\n            \"--channel\",\n            type=str,\n            default=\"ccdl-general\",\n            help=(\"Optional parameter to choose the channel where the message will be posted.\"),\n        )\n\n    def handle(self, *args, **options):\n        days = options[\"days\"]\n        start_time = timezone.now() - datetime.timedelta(days=-days)\n\n        annotation_queryset = DatasetAnnotation.objects.filter(\n            created_at__gt=start_time\n        ).prefetch_related(\"dataset\")\n        annotations = [\n            annotation\n            for annotation in annotation_queryset\n            if annotation.data[\"start\"] and should_display_email(annotation.dataset.email_address)\n        ]\n\n        unique_users = list(set(annotation.dataset.email_address for annotation in annotations))\n        unique_ips = list(set(annotation.data[\"ip\"] for annotation in annotations))\n\n        if unique_users:\n            fallback_text = \"In the last {0} days, {1} users downloaded datasets from {2} locations.\".format(\n                days, len(unique_users), len(unique_ips)\n            )\n        else:\n            fallback_text = \"There were no downloads in the last {0} days.\".format(days)\n\n        new_users = \"\"\n        returning_users = \"\"\n        for email in unique_users:\n            user_annotations = annotation_queryset.filter(dataset__email_address=email)\n            total_downloads = user_annotations.count()\n            unique_locations = list(set(annotation.data[\"ip\"] for annotation in user_annotations))\n            locations = \", \".join(get_ip_location(ip) for ip in unique_locations)\n            is_new_user = DatasetAnnotation.objects.filter(\n                created_at__lt=start_time, dataset__email_address=email\n            )\n            text = \"{0} | {1} downloads from {2}\\n\".format(email, total_downloads, locations)\n            if is_new_user:\n                new_users += text\n            else:\n                returning_users += text\n\n        blocks = [\n            {\n                \"type\": \"section\",\n                \"text\": {\"type\": \"plain_text\", \"emoji\": True, \"text\": fallback_text},\n            }\n        ]\n        if new_users:\n            blocks.append(\n                {\n                    \"type\": \"section\",\n                    \"text\": {\"type\": \"mrkdwn\", \"text\": \"*New users* \\n\" + new_users,},\n                }\n            )\n        if returning_users:\n            blocks.append(\n                {\n                    \"type\": \"section\",\n                    \"text\": {\"type\": \"mrkdwn\", \"text\": \"*Returning users* \\n\" + returning_users,},\n                }\n            )\n\n        # Post to slack\n        requests.post(\n            settings.ENGAGEMENTBOT_WEBHOOK,\n            json={\n                \"username\": \"EngagementBot\",\n                \"icon_emoji\": \":halal:\",\n                \"channel\": \"#\" + options[\"channel\"],\n                \"text\": fallback_text,\n                \"blocks\": blocks,\n            },\n            headers={\"Content-Type\": \"application/json\"},\n            timeout=10,\n        )\n\n\ndef should_display_email(email: str) -> bool:\n    \"\"\" Returns true if the given email is not associated with the CCDL suers \"\"\"\n    if not email:\n        return False\n\n    return not (\n        email.startswith(\"cansav09\")\n        or email.startswith(\"arielsvn\")\n        or email.startswith(\"jaclyn.n.taroni\")\n        or email.startswith(\"kurt.wheeler\")\n        or email.startswith(\"greenescientist\")\n        or \"@alexslemonade.org\" not in email\n        or email.startswith(\"miserlou\")\n        or email.startswith(\"d.prasad\")\n        or email is (\"daniel.himmelstein@gmail.com\")\n        or email is (\"dv.prasad991@gmail.com\")\n    )\n\n\ndef get_ip_location(remote_ip):\n    try:\n        city = requests.get(\"https://ipapi.co/\" + remote_ip + \"/json/\", timeout=10).json()[\"city\"]\n    except Exception:\n        city = remote_ip\n    return city\n", "path": "api/data_refinery_api/management/commands/post_downloads_summary.py"}], "after_files": [{"content": "import datetime\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\nimport requests\n\nfrom data_refinery_common.models import DatasetAnnotation\n\n\nclass Command(BaseCommand):\n    help = \"Post downloads summary to slack\"\n\n    def add_arguments(self, parser):\n        parser.add_argument(\n            \"--days\",\n            type=int,\n            default=7,  # default to a week\n            help=(\"Number of days in the past for which to build the stats\"),\n        )\n        parser.add_argument(\n            \"--channel\",\n            type=str,\n            default=\"ccdl-general\",\n            help=(\"Optional parameter to choose the channel where the message will be posted.\"),\n        )\n\n    def handle(self, *args, **options):\n        days = options[\"days\"]\n        start_time = timezone.now() - datetime.timedelta(days=days)\n\n        annotation_queryset = DatasetAnnotation.objects.filter(\n            created_at__gt=start_time\n        ).prefetch_related(\"dataset\")\n        annotations = [\n            annotation\n            for annotation in annotation_queryset\n            if annotation.data[\"start\"] and should_display_email(annotation.dataset.email_address)\n        ]\n\n        unique_users = list(set(annotation.dataset.email_address for annotation in annotations))\n        unique_ips = list(set(annotation.data[\"ip\"] for annotation in annotations))\n\n        if unique_users:\n            fallback_text = \"In the last {0} days, {1} users downloaded datasets from {2} locations.\".format(\n                days, len(unique_users), len(unique_ips)\n            )\n        else:\n            fallback_text = \"There were no downloads in the last {0} days.\".format(days)\n\n        new_users = \"\"\n        returning_users = \"\"\n        for email in unique_users:\n            user_annotations = annotation_queryset.filter(dataset__email_address=email)\n            total_downloads = user_annotations.count()\n            unique_locations = list(set(annotation.data[\"ip\"] for annotation in user_annotations))\n            locations = \", \".join(get_ip_location(ip) for ip in unique_locations)\n            is_new_user = DatasetAnnotation.objects.filter(\n                created_at__lt=start_time, dataset__email_address=email\n            )\n            text = \"{0} | {1} downloads from {2}\\n\".format(email, total_downloads, locations)\n            if is_new_user:\n                new_users += text\n            else:\n                returning_users += text\n\n        blocks = [\n            {\n                \"type\": \"section\",\n                \"text\": {\"type\": \"plain_text\", \"emoji\": True, \"text\": fallback_text},\n            }\n        ]\n        if new_users:\n            blocks.append(\n                {\n                    \"type\": \"section\",\n                    \"text\": {\"type\": \"mrkdwn\", \"text\": \"*New users* \\n\" + new_users,},\n                }\n            )\n        if returning_users:\n            blocks.append(\n                {\n                    \"type\": \"section\",\n                    \"text\": {\"type\": \"mrkdwn\", \"text\": \"*Returning users* \\n\" + returning_users,},\n                }\n            )\n\n        # Post to slack\n        requests.post(\n            settings.ENGAGEMENTBOT_WEBHOOK,\n            json={\n                \"username\": \"EngagementBot\",\n                \"icon_emoji\": \":halal:\",\n                \"channel\": \"#\" + options[\"channel\"],\n                \"text\": fallback_text,\n                \"blocks\": blocks,\n            },\n            headers={\"Content-Type\": \"application/json\"},\n            timeout=10,\n        )\n\n\ndef should_display_email(email: str) -> bool:\n    \"\"\" Returns true if the given email is not associated with the CCDL suers \"\"\"\n    if not email:\n        return False\n    return not (\n        email.startswith(\"cansav09\")\n        or email.startswith(\"arielsvn\")\n        or email.startswith(\"jaclyn.n.taroni\")\n        or email.startswith(\"kurt.wheeler\")\n        or email.startswith(\"greenescientist\")\n        or email.startswith(\"miserlou\")\n        or email.startswith(\"d.prasad\")\n        or email.endswith(\"@alexslemonade.org\")\n        or email is (\"daniel.himmelstein@gmail.com\")\n        or email is (\"dv.prasad991@gmail.com\")\n    )\n\n\ndef get_ip_location(remote_ip):\n    try:\n        data = requests.get(\"https://ipapi.co/\" + remote_ip + \"/json/\", timeout=10).json()\n        return \"{0}, {1}\".format(data[\"city\"], data[\"country_name\"])\n    except Exception:\n        return remote_ip\n", "path": "api/data_refinery_api/management/commands/post_downloads_summary.py"}]}