From d061ab1c138c7cecf8d138226990bdcf0761a5db Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Wed, 19 May 2021 13:13:57 +0530 Subject: Add active field to OffTopicChannelName model. --- .../apps/api/migrations/0070_auto_20210519_0545.py | 23 ++++++++++++++++++++++ .../apps/api/models/bot/off_topic_channel_name.py | 7 ++++++- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 pydis_site/apps/api/migrations/0070_auto_20210519_0545.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0070_auto_20210519_0545.py b/pydis_site/apps/api/migrations/0070_auto_20210519_0545.py new file mode 100644 index 00000000..dbd7ac91 --- /dev/null +++ b/pydis_site/apps/api/migrations/0070_auto_20210519_0545.py @@ -0,0 +1,23 @@ +# Generated by Django 3.0.14 on 2021-05-19 05:45 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0069_documentationlink_validators'), + ] + + operations = [ + migrations.AddField( + model_name='offtopicchannelname', + name='active', + field=models.BooleanField(default=True, help_text='Whether or not this name should be considered for naming channels.'), + ), + migrations.AlterField( + model_name='offtopicchannelname', + name='used', + field=models.BooleanField(default=False, help_text='Whether or not this name has already been used during this rotation.'), + ), + ] diff --git a/pydis_site/apps/api/models/bot/off_topic_channel_name.py b/pydis_site/apps/api/models/bot/off_topic_channel_name.py index 403c7465..582c069e 100644 --- a/pydis_site/apps/api/models/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/models/bot/off_topic_channel_name.py @@ -18,7 +18,12 @@ class OffTopicChannelName(ModelReprMixin, models.Model): used = models.BooleanField( default=False, - help_text="Whether or not this name has already been used during this rotation", + help_text="Whether or not this name has already been used during this rotation.", + ) + + active = models.BooleanField( + default=True, + help_text="Whether or not this name should be considered for naming channels." ) def __str__(self): -- cgit v1.2.3 From 8232b1115bdc308c7ca12f477c704957ec3e3ed1 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Wed, 19 May 2021 13:15:53 +0530 Subject: Serialize name and active attribute. --- pydis_site/apps/api/serializers.py | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index f47bedca..8f61073e 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -207,18 +207,7 @@ class OffTopicChannelNameSerializer(ModelSerializer): """Metadata defined for the Django REST Framework.""" model = OffTopicChannelName - fields = ('name',) - - def to_representation(self, obj: OffTopicChannelName) -> str: - """ - Return the representation of this `OffTopicChannelName`. - - This only returns the name of the off topic channel name. As the model - only has a single attribute, it is unnecessary to create a nested dictionary. - Additionally, this allows off topic channel name routes to simply return an - array of names instead of objects, saving on bandwidth. - """ - return obj.name + fields = ('name', 'active') class ReminderSerializer(ModelSerializer): -- cgit v1.2.3 From b2819a4cfe04b893d5cd638407e48ff6bd501a20 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Wed, 19 May 2021 13:16:21 +0530 Subject: Use ModelViewSet to add support for PUT and PATCH request. --- pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py index 826ad25e..194e96d2 100644 --- a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py @@ -3,16 +3,15 @@ from django.db.models.query import QuerySet from django.http.request import HttpRequest from django.shortcuts import get_object_or_404 from rest_framework.exceptions import ParseError -from rest_framework.mixins import DestroyModelMixin from rest_framework.response import Response from rest_framework.status import HTTP_201_CREATED -from rest_framework.viewsets import ViewSet +from rest_framework.viewsets import ModelViewSet from pydis_site.apps.api.models.bot.off_topic_channel_name import OffTopicChannelName from pydis_site.apps.api.serializers import OffTopicChannelNameSerializer -class OffTopicChannelNameViewSet(DestroyModelMixin, ViewSet): +class OffTopicChannelNameViewSet(ModelViewSet): """ View of off-topic channel names used by the bot to rotate our off-topic names on a daily basis. @@ -73,7 +72,7 @@ class OffTopicChannelNameViewSet(DestroyModelMixin, ViewSet): """Returns a queryset that covers the entire OffTopicChannelName table.""" return OffTopicChannelName.objects.all() - def create(self, request: HttpRequest) -> Response: + def create(self, request: HttpRequest, *args, **kwargs) -> Response: """ DRF method for creating a new OffTopicChannelName. @@ -91,7 +90,7 @@ class OffTopicChannelNameViewSet(DestroyModelMixin, ViewSet): 'name': ["This query parameter is required."] }) - def list(self, request: HttpRequest) -> Response: + def list(self, request: HttpRequest, *args, **kwargs) -> Response: """ DRF method for listing OffTopicChannelName entries. @@ -133,6 +132,4 @@ class OffTopicChannelNameViewSet(DestroyModelMixin, ViewSet): serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) - queryset = self.get_queryset() - serialized = self.serializer_class(queryset, many=True) - return Response(serialized.data) + return super().list(self, request) -- cgit v1.2.3 From 69f4dc119af4a8d46295abc2551bad24bee96066 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Mon, 31 May 2021 15:27:54 +0530 Subject: Return a list of ot-names only for GET request only to bot/off-topic-channel-names --- pydis_site/apps/api/serializers.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index 8f61073e..1acb4fb8 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -1,4 +1,6 @@ """Converters from Django models to data interchange formats and back.""" +from typing import List + from django.db.models.query import QuerySet from django.db.utils import IntegrityError from rest_framework.exceptions import NotFound @@ -200,14 +202,29 @@ class ExpandedInfractionSerializer(InfractionSerializer): return ret +class OffTopicChannelNameListSerializer(ListSerializer): + def update(self, instance, validated_data): + pass + + def to_representation(self, objects: List[OffTopicChannelName]) -> List[str]: + """ + Return the representation of this `OffTopicChannelName`. + This only returns the name of the off topic channel name. As the model + only has a single attribute, it is unnecessary to create a nested dictionary. + Additionally, this allows off topic channel name routes to simply return an + array of names instead of objects, saving on bandwidth. + """ + return [obj.name for obj in objects] + + class OffTopicChannelNameSerializer(ModelSerializer): """A class providing (de-)serialization of `OffTopicChannelName` instances.""" class Meta: """Metadata defined for the Django REST Framework.""" - + list_serializer_class = OffTopicChannelNameListSerializer model = OffTopicChannelName - fields = ('name', 'active') + fields = ('name', 'used', 'active') class ReminderSerializer(ModelSerializer): -- cgit v1.2.3 From 87e25f77cbc900024e86d439abd9fde71181800d Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Fri, 4 Jun 2021 21:46:54 +0530 Subject: Query off topic names based on Active attribute. --- .../apps/api/viewsets/bot/off_topic_channel_name.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py index 194e96d2..0caf8088 100644 --- a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py @@ -1,9 +1,11 @@ +import json + from django.db.models import Case, Value, When from django.db.models.query import QuerySet -from django.http.request import HttpRequest from django.shortcuts import get_object_or_404 from rest_framework.exceptions import ParseError from rest_framework.response import Response +from rest_framework.request import Request from rest_framework.status import HTTP_201_CREATED from rest_framework.viewsets import ModelViewSet @@ -68,11 +70,11 @@ class OffTopicChannelNameViewSet(ModelViewSet): name = self.kwargs[self.lookup_field] return get_object_or_404(queryset, name=name) - def get_queryset(self) -> QuerySet: + def get_queryset(self, active=True) -> QuerySet: """Returns a queryset that covers the entire OffTopicChannelName table.""" - return OffTopicChannelName.objects.all() + return OffTopicChannelName.objects.filter(active=True) - def create(self, request: HttpRequest, *args, **kwargs) -> Response: + def create(self, request: Request, *args, **kwargs) -> Response: """ DRF method for creating a new OffTopicChannelName. @@ -90,7 +92,7 @@ class OffTopicChannelNameViewSet(ModelViewSet): 'name': ["This query parameter is required."] }) - def list(self, request: HttpRequest, *args, **kwargs) -> Response: + def list(self, request: Request, *args, **kwargs) -> Response: """ DRF method for listing OffTopicChannelName entries. @@ -132,4 +134,6 @@ class OffTopicChannelNameViewSet(ModelViewSet): serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) - return super().list(self, request) + queryset = self.get_queryset(active=bool(request.query_params.get("active", True))) + serialized = self.serializer_class(queryset, many=True) + return Response(serialized.data) -- cgit v1.2.3 From da1056f36f77d98783b8fb53152fd4ebbc19c019 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 10 Jun 2021 02:08:54 +0530 Subject: Lint file and remove update() method declaration from OffTopicChannelNameListSerializer. --- pydis_site/apps/api/serializers.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index 1acb4fb8..0d505675 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -203,12 +203,12 @@ class ExpandedInfractionSerializer(InfractionSerializer): class OffTopicChannelNameListSerializer(ListSerializer): - def update(self, instance, validated_data): - pass + """Custom ListSerializer to override to_representation() when list views are triggered.""" def to_representation(self, objects: List[OffTopicChannelName]) -> List[str]: """ Return the representation of this `OffTopicChannelName`. + This only returns the name of the off topic channel name. As the model only has a single attribute, it is unnecessary to create a nested dictionary. Additionally, this allows off topic channel name routes to simply return an @@ -222,6 +222,7 @@ class OffTopicChannelNameSerializer(ModelSerializer): class Meta: """Metadata defined for the Django REST Framework.""" + list_serializer_class = OffTopicChannelNameListSerializer model = OffTopicChannelName fields = ('name', 'used', 'active') -- cgit v1.2.3 From f0534b8e1ed55c18416372f23bb5a1f2e0862e38 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 10 Jun 2021 02:09:22 +0530 Subject: Fix bug: Do not force active param. --- .../apps/api/viewsets/bot/off_topic_channel_name.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py index 0caf8088..18ee84ea 100644 --- a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py @@ -1,11 +1,9 @@ -import json - from django.db.models import Case, Value, When from django.db.models.query import QuerySet from django.shortcuts import get_object_or_404 from rest_framework.exceptions import ParseError -from rest_framework.response import Response from rest_framework.request import Request +from rest_framework.response import Response from rest_framework.status import HTTP_201_CREATED from rest_framework.viewsets import ModelViewSet @@ -70,9 +68,9 @@ class OffTopicChannelNameViewSet(ModelViewSet): name = self.kwargs[self.lookup_field] return get_object_or_404(queryset, name=name) - def get_queryset(self, active=True) -> QuerySet: + def get_queryset(self, **kwargs) -> QuerySet: """Returns a queryset that covers the entire OffTopicChannelName table.""" - return OffTopicChannelName.objects.filter(active=True) + return OffTopicChannelName.objects.filter(**kwargs) def create(self, request: Request, *args, **kwargs) -> Response: """ @@ -134,6 +132,11 @@ class OffTopicChannelNameViewSet(ModelViewSet): serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) - queryset = self.get_queryset(active=bool(request.query_params.get("active", True))) + params = {} + + if active_param := request.query_params.get("active"): + params["active"] = active_param.lower() == "true" + + queryset = self.get_queryset(**params) serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) -- cgit v1.2.3 From 832880cfac4206aaba0e7de8f005c6425da7a8f3 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 10 Jun 2021 02:11:40 +0530 Subject: Add tests for active params. --- .../apps/api/tests/test_off_topic_channel_names.py | 38 +++++++++++++++++++--- 1 file changed, 34 insertions(+), 4 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_off_topic_channel_names.py b/pydis_site/apps/api/tests/test_off_topic_channel_names.py index 3ab8b22d..a407654c 100644 --- a/pydis_site/apps/api/tests/test_off_topic_channel_names.py +++ b/pydis_site/apps/api/tests/test_off_topic_channel_names.py @@ -65,8 +65,15 @@ class EmptyDatabaseTests(APISubdomainTestCase): class ListTests(APISubdomainTestCase): @classmethod def setUpTestData(cls): - cls.test_name = OffTopicChannelName.objects.create(name='lemons-lemonade-stand', used=False) - cls.test_name_2 = OffTopicChannelName.objects.create(name='bbq-with-bisk', used=True) + cls.test_name = OffTopicChannelName.objects.create( + name='lemons-lemonade-stand', used=False, active=True + ) + cls.test_name_2 = OffTopicChannelName.objects.create( + name='bbq-with-bisk', used=True, active=True + ) + cls.test_name_3 = OffTopicChannelName.objects.create( + name="frozen-with-iceman", used=True, active=False + ) def test_returns_name_in_list(self): """Return all off-topic channel names.""" @@ -78,7 +85,8 @@ class ListTests(APISubdomainTestCase): response.json(), [ self.test_name.name, - self.test_name_2.name + self.test_name_2.name, + self.test_name_3.name ] ) @@ -97,7 +105,29 @@ class ListTests(APISubdomainTestCase): response = self.client.get(f'{url}?random_items=2') self.assertEqual(response.status_code, 200) - self.assertEqual(response.json(), [self.test_name.name, self.test_name_2.name]) + self.assertEqual(response.json(), [self.test_name.name, self.test_name_3.name]) + + def test_returns_inactive_ot_names(self): + """Return inactive off topic names.""" + url = reverse('bot:offtopicchannelname-list', host="api") + response = self.client.get(f"{url}?active=false") + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json(), + [self.test_name_3.name] + ) + + def test_returns_active_ot_names(self): + """Return active off topic names.""" + url = reverse('bot:offtopicchannelname-list', host="api") + response = self.client.get(f"{url}?active=true") + + self.assertEqual(response.status_code, 200) + self.assertEqual( + response.json(), + [self.test_name.name, self.test_name_2.name] + ) class CreationTests(APISubdomainTestCase): -- cgit v1.2.3 From 3795b6d6de005f0ed00c37cf042eaca01d0a4769 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 10 Jun 2021 02:32:17 +0530 Subject: Use assertListEqual where applicable instead of assertEqual. --- .../apps/api/tests/test_off_topic_channel_names.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_off_topic_channel_names.py b/pydis_site/apps/api/tests/test_off_topic_channel_names.py index a407654c..ebb1224a 100644 --- a/pydis_site/apps/api/tests/test_off_topic_channel_names.py +++ b/pydis_site/apps/api/tests/test_off_topic_channel_names.py @@ -69,7 +69,7 @@ class ListTests(APISubdomainTestCase): name='lemons-lemonade-stand', used=False, active=True ) cls.test_name_2 = OffTopicChannelName.objects.create( - name='bbq-with-bisk', used=True, active=True + name='bbq-with-bisk', used=False, active=True ) cls.test_name_3 = OffTopicChannelName.objects.create( name="frozen-with-iceman", used=True, active=False @@ -81,7 +81,7 @@ class ListTests(APISubdomainTestCase): response = self.client.get(url) self.assertEqual(response.status_code, 200) - self.assertEqual( + self.assertListEqual( response.json(), [ self.test_name.name, @@ -90,22 +90,24 @@ class ListTests(APISubdomainTestCase): ] ) - def test_returns_single_item_with_random_items_param_set_to_1(self): + def test_returns_two_items_with_random_items_param_set_to_2(self): """Return not-used name instead used.""" url = reverse('bot:offtopicchannelname-list', host='api') - response = self.client.get(f'{url}?random_items=1') + response = self.client.get(f'{url}?random_items=2') self.assertEqual(response.status_code, 200) - self.assertEqual(len(response.json()), 1) - self.assertEqual(response.json(), [self.test_name.name]) + self.assertEqual(len(response.json()), 2) + self.assertEqual(response.json(), [self.test_name.name, self.test_name_2.name]) def test_running_out_of_names_with_random_parameter(self): """Reset names `used` parameter to `False` when running out of names.""" url = reverse('bot:offtopicchannelname-list', host='api') - response = self.client.get(f'{url}?random_items=2') + response = self.client.get(f'{url}?random_items=3') self.assertEqual(response.status_code, 200) - self.assertEqual(response.json(), [self.test_name.name, self.test_name_3.name]) + self.assertListEqual( + response.json(), [self.test_name.name, self.test_name_2.name, self.test_name_3.name] + ) def test_returns_inactive_ot_names(self): """Return inactive off topic names.""" -- cgit v1.2.3 From 8fdabfb4c08931b1e2352e98b307b3bfa3a121f1 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 10 Jun 2021 02:45:55 +0530 Subject: Use sets to compare 2 un-ordered lists. --- .../apps/api/tests/test_off_topic_channel_names.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_off_topic_channel_names.py b/pydis_site/apps/api/tests/test_off_topic_channel_names.py index ebb1224a..34dde7c6 100644 --- a/pydis_site/apps/api/tests/test_off_topic_channel_names.py +++ b/pydis_site/apps/api/tests/test_off_topic_channel_names.py @@ -81,13 +81,13 @@ class ListTests(APISubdomainTestCase): response = self.client.get(url) self.assertEqual(response.status_code, 200) - self.assertListEqual( - response.json(), - [ + self.assertEqual( + set(response.json()), + { self.test_name.name, self.test_name_2.name, self.test_name_3.name - ] + } ) def test_returns_two_items_with_random_items_param_set_to_2(self): @@ -97,7 +97,7 @@ class ListTests(APISubdomainTestCase): self.assertEqual(response.status_code, 200) self.assertEqual(len(response.json()), 2) - self.assertEqual(response.json(), [self.test_name.name, self.test_name_2.name]) + self.assertEqual(set(response.json()), {self.test_name.name, self.test_name_2.name}) def test_running_out_of_names_with_random_parameter(self): """Reset names `used` parameter to `False` when running out of names.""" @@ -105,8 +105,9 @@ class ListTests(APISubdomainTestCase): response = self.client.get(f'{url}?random_items=3') self.assertEqual(response.status_code, 200) - self.assertListEqual( - response.json(), [self.test_name.name, self.test_name_2.name, self.test_name_3.name] + self.assertEqual( + set(response.json()), + {self.test_name.name, self.test_name_2.name, self.test_name_3.name} ) def test_returns_inactive_ot_names(self): @@ -127,8 +128,8 @@ class ListTests(APISubdomainTestCase): self.assertEqual(response.status_code, 200) self.assertEqual( - response.json(), - [self.test_name.name, self.test_name_2.name] + set(response.json()), + {self.test_name.name, self.test_name_2.name} ) -- cgit v1.2.3 From e7b4da7955c100d42536e298ffc9966dd9f95c48 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Thu, 22 Jul 2021 13:51:28 +0530 Subject: Update docstring. --- pydis_site/apps/api/serializers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index 0d505675..957c85f3 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -207,7 +207,7 @@ class OffTopicChannelNameListSerializer(ListSerializer): def to_representation(self, objects: List[OffTopicChannelName]) -> List[str]: """ - Return the representation of this `OffTopicChannelName`. + Return a list representing a list of `OffTopicChannelName`. This only returns the name of the off topic channel name. As the model only has a single attribute, it is unnecessary to create a nested dictionary. -- cgit v1.2.3 From d52f21c1fefbb396762dd74609b9957ae029dfc3 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Sat, 24 Jul 2021 19:26:36 +0530 Subject: fix CommandError: Conflicting migrations detected. --- pydis_site/apps/api/migrations/0072_merge_20210724_1354.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 pydis_site/apps/api/migrations/0072_merge_20210724_1354.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0072_merge_20210724_1354.py b/pydis_site/apps/api/migrations/0072_merge_20210724_1354.py new file mode 100644 index 00000000..f12efab5 --- /dev/null +++ b/pydis_site/apps/api/migrations/0072_merge_20210724_1354.py @@ -0,0 +1,14 @@ +# Generated by Django 3.0.14 on 2021-07-24 13:54 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0071_increase_message_content_4000'), + ('api', '0070_auto_20210519_0545'), + ] + + operations = [ + ] -- cgit v1.2.3 From a77d115e3fa04aa7f452c56ed9ae7712ed41cd2b Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Fri, 24 Sep 2021 00:13:51 +0100 Subject: Direct appeals to the appeals server Rather than mentioning the apeals email address, we now direct users to the appeal server, which will now be used for ban appeals. --- pydis_site/apps/content/resources/code-of-conduct.md | 2 +- pydis_site/apps/content/resources/rules.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/code-of-conduct.md b/pydis_site/apps/content/resources/code-of-conduct.md index 6302438e..56050230 100644 --- a/pydis_site/apps/content/resources/code-of-conduct.md +++ b/pydis_site/apps/content/resources/code-of-conduct.md @@ -77,8 +77,8 @@ You may report in the following ways: If you wish to appeal a decision or action taken by the moderation team, you can do so in one of the following ways: -* By sending an email to [appeals@pythondiscord.com](mailto:appeals@pythondiscord.com) * By sending a direct message (DM) to ModMail from our Discord server. +* Joining our [ban appeals server](https://discord.gg/WXrCJxWBnm) and sending a direct message (DM) to the Ban Appeals bot. Please provide all relevant information in your appeal, including: diff --git a/pydis_site/apps/content/resources/rules.md b/pydis_site/apps/content/resources/rules.md index 05d0e93a..ef6cc4d1 100644 --- a/pydis_site/apps/content/resources/rules.md +++ b/pydis_site/apps/content/resources/rules.md @@ -43,4 +43,7 @@ The possible actions we take based on infractions can include the following: While we do discuss more serious matters internally before handing out a punishment, simpler infractions are dealt with directly by individual staffers and the punishment they hand out is left to their own discretion. -If you receive an infraction and would like to appeal it, send an e-mail to [appeals@pythondiscord.com](mailto:appeals@pythondiscord.com). +If you wish to appeal a decision or action taken by the moderation team, you can do so in one of the following ways: + +* By sending a direct message (DM) to ModMail from our Discord server. +* Joining our [ban appeals server](https://discord.gg/WXrCJxWBnm) and sending a direct message (DM) to the Ban Appeals bot. -- cgit v1.2.3 From e9c4cdf56e2efd65786a4cf4aee0bb4e4e56bc95 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Sun, 10 Oct 2021 01:28:39 +0300 Subject: Adds Django Distill To Project Adds django-distill to dependencies, and lays the basic groundwork to start building static routes. Adds a poetry task to help with testing. --- manage.py | 31 +++++++++++++++++++++++++++++++ poetry.lock | 17 ++++++++++++++++- pydis_site/settings.py | 21 ++++++++++++++++----- pyproject.toml | 2 ++ 4 files changed, 65 insertions(+), 6 deletions(-) (limited to 'pydis_site') diff --git a/manage.py b/manage.py index 578f4748..357134ec 100755 --- a/manage.py +++ b/manage.py @@ -1,6 +1,8 @@ #!/usr/bin/env python import os +import platform import sys +from pathlib import Path import django from django.contrib.auth import get_user_model @@ -147,6 +149,22 @@ class SiteManager: gunicorn.app.wsgiapp.run() +def clean_up_static_files(build_folder: Path) -> None: + """Recursively loop over the build directory and fix links.""" + for file in build_folder.iterdir(): + if file.is_dir(): + clean_up_static_files(file) + elif file.name.endswith(".html"): + # Fix parent host url + new = file.read_text(encoding="utf-8").replace(f"//{os.getenv('PARENT_HOST')}", "") + + # Fix windows paths if on windows + if platform.system() == "Windows": + new = new.replace("%5C", "/") + + file.write_text(new, encoding="utf-8") + + def main() -> None: """Entry point for Django management script.""" # Use the custom site manager for launching the server @@ -155,8 +173,21 @@ def main() -> None: # Pass any others directly to standard management commands else: + if _static_build := "distill" in sys.argv[1]: + # Build a static version of the site with no databases and API support + os.environ["STATIC_BUILD"] = "True" + if not os.getenv("PARENT_HOST"): + os.environ["PARENT_HOST"] = "REPLACE_THIS.HOST" + execute_from_command_line(sys.argv) + if _static_build: + # Clean up parent host in generated files + for arg in sys.argv[2:]: + if not arg.startswith("-"): + clean_up_static_files(Path(arg)) + break + if __name__ == '__main__': main() diff --git a/poetry.lock b/poetry.lock index c6724cfc..eac58fdb 100644 --- a/poetry.lock +++ b/poetry.lock @@ -137,6 +137,18 @@ sqlparse = ">=0.2.2" argon2 = ["argon2-cffi (>=16.1.0)"] bcrypt = ["bcrypt"] +[[package]] +name = "django-distill" +version = "2.9.0" +description = "Static site renderer and publisher for Django." +category = "main" +optional = false +python-versions = "*" + +[package.dependencies] +django = "*" +requests = "*" + [[package]] name = "django-environ" version = "0.4.5" @@ -757,7 +769,7 @@ brotli = ["brotli"] [metadata] lock-version = "1.1" python-versions = "3.9.*" -content-hash = "ed7da8dbc905d4f2c47e01301b49c4aed0083bee269da0ee5ebcc3abee4ab1a0" +content-hash = "9f0c069c14e2dbff63d58474702693f0c02b8cfd30e5af38303975a73b71bcfd" [metadata.files] asgiref = [ @@ -858,6 +870,9 @@ django = [ {file = "Django-3.0.14-py3-none-any.whl", hash = "sha256:9bc7aa619ed878fedba62ce139abe663a147dccfd20e907725ec11e02a1ca225"}, {file = "Django-3.0.14.tar.gz", hash = "sha256:d58d8394036db75a81896037d757357e79406e8f68816c3e8a28721c1d9d4c11"}, ] +django-distill = [ + {file = "django-distill-2.9.0.tar.gz", hash = "sha256:08f31dcde2e79e73c0bc4f36941830603a811cc89472be11f79f14affb460d84"}, +] django-environ = [ {file = "django-environ-0.4.5.tar.gz", hash = "sha256:6c9d87660142608f63ec7d5ce5564c49b603ea8ff25da595fd6098f6dc82afde"}, {file = "django_environ-0.4.5-py2.py3-none-any.whl", hash = "sha256:c57b3c11ec1f319d9474e3e5a79134f40174b17c7cc024bbb2fad84646b120c4"}, diff --git a/pydis_site/settings.py b/pydis_site/settings.py index d7b87f33..d38c298b 100644 --- a/pydis_site/settings.py +++ b/pydis_site/settings.py @@ -25,7 +25,8 @@ from pydis_site.constants import GIT_SHA env = environ.Env( DEBUG=(bool, False), SITE_DSN=(str, ""), - BUILDING_DOCKER=(bool, False) + BUILDING_DOCKER=(bool, False), + STATIC_BUILD=(bool, False), ) sentry_sdk.init( @@ -65,10 +66,14 @@ else: SECRET_KEY = env('SECRET_KEY') # Application definition -INSTALLED_APPS = [ +NON_STATIC_APPS = [ 'pydis_site.apps.api', - 'pydis_site.apps.home', 'pydis_site.apps.staff', +] if not env("STATIC_BUILD") else [] + +INSTALLED_APPS = [ + *NON_STATIC_APPS, + 'pydis_site.apps.home', 'pydis_site.apps.resources', 'pydis_site.apps.content', 'pydis_site.apps.events', @@ -86,14 +91,20 @@ INSTALLED_APPS = [ 'django_simple_bulma', 'rest_framework', 'rest_framework.authtoken', + + 'django_distill', ] if not env("BUILDING_DOCKER"): INSTALLED_APPS.append("django_prometheus") +NON_STATIC_MIDDLEWARE = [ + 'django_prometheus.middleware.PrometheusBeforeMiddleware', +] if not env("STATIC_BUILD") else [] + # Ensure that Prometheus middlewares are first and last here. MIDDLEWARE = [ - 'django_prometheus.middleware.PrometheusBeforeMiddleware', + *NON_STATIC_MIDDLEWARE, 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', @@ -134,7 +145,7 @@ WSGI_APPLICATION = 'pydis_site.wsgi.application' DATABASES = { 'default': env.db(), 'metricity': env.db('METRICITY_DB_URL'), -} +} if not env("STATIC_BUILD") else {} # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators diff --git a/pyproject.toml b/pyproject.toml index d0beb632..2f1322e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,7 @@ sentry-sdk = "~=0.19" markdown = "~=3.3.4" python-frontmatter = "~=1.0" django-prometheus = "~=2.1" +django-distill = "~=2.9.0" [tool.poetry.dev-dependencies] coverage = "~=5.0" @@ -53,3 +54,4 @@ test = "coverage run manage.py test" report = "coverage report -m" lint = "pre-commit run --all-files" precommit = "pre-commit install" +static = "python mange.py distill-local build --traceback --force" -- cgit v1.2.3 From 247c4ba220f9ee73767f4aac2737e520e7ec4b07 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Sun, 10 Oct 2021 01:30:06 +0300 Subject: Adds Static Route Configurations Adds configuration which specifies how routes should be handled when building a static preview. --- pydis_site/apps/content/urls.py | 43 +++++++++++++++++++++++++++++++++++--- pydis_site/apps/events/urls.py | 35 ++++++++++++++++++++++++++++--- pydis_site/apps/home/urls.py | 6 +++--- pydis_site/apps/home/views/home.py | 26 ++++++++++++++++------- pydis_site/apps/resources/urls.py | 22 ++++++++++++++++--- pydis_site/urls.py | 11 ++++++++-- 6 files changed, 122 insertions(+), 21 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/urls.py b/pydis_site/apps/content/urls.py index c11b222a..fe7c2852 100644 --- a/pydis_site/apps/content/urls.py +++ b/pydis_site/apps/content/urls.py @@ -1,9 +1,46 @@ -from django.urls import path +import typing +from pathlib import Path + +from django_distill import distill_path from . import views app_name = "content" + + +def __get_all_files(root: Path, folder: typing.Optional[Path] = None) -> list[str]: + """Find all folders and markdown files recursively starting from `root`.""" + if not folder: + folder = root + + results = [] + + for item in folder.iterdir(): + name = item.relative_to(root).__str__().replace("\\", "/") + + if item.is_dir(): + results.append(name) + results.extend(__get_all_files(root, item)) + else: + path, extension = name.rsplit(".", maxsplit=1) + if extension == "md": + results.append(path) + + return results + + +def get_all_pages() -> typing.Iterator[dict[str, str]]: + """Yield a dict of all pag categories.""" + for location in __get_all_files(Path("pydis_site", "apps", "content", "resources")): + yield {"location": location} + + urlpatterns = [ - path("", views.PageOrCategoryView.as_view(), name='pages'), - path("/", views.PageOrCategoryView.as_view(), name='page_category'), + distill_path("", views.PageOrCategoryView.as_view(), name='pages'), + distill_path( + "/", + views.PageOrCategoryView.as_view(), + name='page_category', + distill_func=get_all_pages + ), ] diff --git a/pydis_site/apps/events/urls.py b/pydis_site/apps/events/urls.py index 9a65cf1f..7ea65a31 100644 --- a/pydis_site/apps/events/urls.py +++ b/pydis_site/apps/events/urls.py @@ -1,9 +1,38 @@ -from django.urls import path +import typing +from pathlib import Path + +from django_distill import distill_path from pydis_site.apps.events.views import IndexView, PageView app_name = "events" + + +def __get_all_files(root: Path, folder: typing.Optional[Path] = None) -> list[str]: + """Find all folders and HTML files recursively starting from `root`.""" + if not folder: + folder = root + + results = [] + + for sub_folder in folder.iterdir(): + results.append( + sub_folder.relative_to(root).__str__().replace("\\", "/").replace(".html", "") + ) + + if sub_folder.is_dir(): + results.extend(__get_all_files(root, sub_folder)) + + return results + + +def get_all_events() -> typing.Iterator[dict[str, str]]: + """Yield a dict of all event pages.""" + for file in __get_all_files(Path("pydis_site", "templates", "events", "pages")): + yield {"path": file} + + urlpatterns = [ - path("", IndexView.as_view(), name="index"), - path("/", PageView.as_view(), name="page"), + distill_path("", IndexView.as_view(), name="index"), + distill_path("/", PageView.as_view(), name="page", distill_func=get_all_events), ] diff --git a/pydis_site/apps/home/urls.py b/pydis_site/apps/home/urls.py index 57abc942..30321ece 100644 --- a/pydis_site/apps/home/urls.py +++ b/pydis_site/apps/home/urls.py @@ -1,9 +1,9 @@ -from django.urls import path +from django_distill import distill_path from .views import HomeView, timeline app_name = 'home' urlpatterns = [ - path('', HomeView.as_view(), name='home'), - path('timeline/', timeline, name="timeline"), + distill_path('', HomeView.as_view(), name='home'), + distill_path('timeline/', timeline, name="timeline"), ] diff --git a/pydis_site/apps/home/views/home.py b/pydis_site/apps/home/views/home.py index 401c768f..e28a3a00 100644 --- a/pydis_site/apps/home/views/home.py +++ b/pydis_site/apps/home/views/home.py @@ -8,6 +8,7 @@ from django.shortcuts import render from django.utils import timezone from django.views import View +from pydis_site import settings from pydis_site.apps.home.models import RepositoryMetadata from pydis_site.constants import GITHUB_TOKEN, TIMEOUT_PERIOD @@ -32,7 +33,10 @@ class HomeView(View): def __init__(self): """Clean up stale RepositoryMetadata.""" - RepositoryMetadata.objects.exclude(repo_name__in=self.repos).delete() + self._static_build = settings.env("STATIC_BUILD") + + if not self._static_build: + RepositoryMetadata.objects.exclude(repo_name__in=self.repos).delete() # If no token is defined (for example in local development), then # it does not make sense to pass the Authorization header. More @@ -91,10 +95,13 @@ class HomeView(View): def _get_repo_data(self) -> List[RepositoryMetadata]: """Build a list of RepositoryMetadata objects that we can use to populate the front page.""" # First off, load the timestamp of the least recently updated entry. - last_update = ( - RepositoryMetadata.objects.values_list("last_updated", flat=True) - .order_by("last_updated").first() - ) + if self._static_build: + last_update = None + else: + last_update = ( + RepositoryMetadata.objects.values_list("last_updated", flat=True) + .order_by("last_updated").first() + ) # If we did not retrieve any results here, we should import them! if last_update is None: @@ -104,7 +111,7 @@ class HomeView(View): api_repositories = self._get_api_data() # Create all the repodata records in the database. - return RepositoryMetadata.objects.bulk_create( + data = [ RepositoryMetadata( repo_name=api_data["full_name"], description=api_data["description"], @@ -113,7 +120,12 @@ class HomeView(View): language=api_data["language"], ) for api_data in api_repositories.values() - ) + ] + + if settings.env("STATIC_BUILD"): + return data + else: + return RepositoryMetadata.objects.bulk_create(data) # If the data is stale, we should refresh it. if (timezone.now() - last_update).seconds > self.repository_cache_ttl: diff --git a/pydis_site/apps/resources/urls.py b/pydis_site/apps/resources/urls.py index 19142081..10eda132 100644 --- a/pydis_site/apps/resources/urls.py +++ b/pydis_site/apps/resources/urls.py @@ -1,9 +1,25 @@ -from django.urls import path +import typing +from pathlib import Path + +from django_distill import distill_path from pydis_site.apps.resources import views app_name = "resources" + + +def get_all_resources() -> typing.Iterator[dict[str, str]]: + """Yield a dict of all resource categories.""" + for category in Path("pydis_site", "apps", "resources", "resources").iterdir(): + yield {"category": category.name} + + urlpatterns = [ - path("", views.ResourcesView.as_view(), name="index"), - path("/", views.ResourcesListView.as_view(), name="resources") + distill_path("", views.ResourcesView.as_view(), name="index"), + distill_path( + "/", + views.ResourcesListView.as_view(), + name="resources", + distill_func=get_all_resources + ), ] diff --git a/pydis_site/urls.py b/pydis_site/urls.py index 891dbdcc..51ef4214 100644 --- a/pydis_site/urls.py +++ b/pydis_site/urls.py @@ -1,8 +1,9 @@ from django.contrib import admin from django.urls import include, path +from pydis_site import settings -urlpatterns = ( +NON_STATIC_PATTERNS = [ path('admin/', admin.site.urls), # External API ingress (over the net) @@ -14,9 +15,15 @@ urlpatterns = ( # from wildcard matching all requests to `pages/...`. path('', include('pydis_site.apps.redirect.urls')), path('', include('django_prometheus.urls')), + + path('staff/', include('pydis_site.apps.staff.urls', namespace='staff')), +] if not settings.env("STATIC_BUILD") else [] + + +urlpatterns = ( + *NON_STATIC_PATTERNS, path('pages/', include('pydis_site.apps.content.urls', namespace='content')), path('resources/', include('pydis_site.apps.resources.urls')), path('events/', include('pydis_site.apps.events.urls', namespace='events')), - path('staff/', include('pydis_site.apps.staff.urls', namespace='staff')), path('', include('pydis_site.apps.home.urls', namespace='home')), ) -- cgit v1.2.3 From a7e9bdd9dbf086094dd138feb9464b7e7fe8b08b Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Sun, 10 Oct 2021 22:19:26 +0300 Subject: Adds Redirects To Static Builds Dynamically adds static HTML redirects for static builds. Signed-off-by: Hassan Abouelela --- pydis_site/apps/redirect/redirects.yaml | 2 +- pydis_site/apps/redirect/urls.py | 114 ++++++++++++++++++++++++++++---- pydis_site/urls.py | 16 +++-- 3 files changed, 112 insertions(+), 20 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/redirect/redirects.yaml b/pydis_site/apps/redirect/redirects.yaml index def4154b..9bcf3afd 100644 --- a/pydis_site/apps/redirect/redirects.yaml +++ b/pydis_site/apps/redirect/redirects.yaml @@ -182,7 +182,7 @@ events_game_jams_twenty_twenty_rules_redirect: redirect_arguments: ["game-jams/2020/rules"] events_game_jams_twenty_twenty_technical_requirements_redirect: - original_path: pages/events/game-jam-2020/technical-requirements + original_path: pages/events/game-jam-2020/technical-requirements/ redirect_route: "events:page" redirect_arguments: ["game-jams/2020/technical-requirements"] diff --git a/pydis_site/apps/redirect/urls.py b/pydis_site/apps/redirect/urls.py index 6187af17..f7ddf45b 100644 --- a/pydis_site/apps/redirect/urls.py +++ b/pydis_site/apps/redirect/urls.py @@ -1,19 +1,105 @@ +import dataclasses +import re + import yaml -from django.conf import settings -from django.urls import path +from django import conf +from django.urls import URLPattern, path +from django_distill import distill_path +from pydis_site import settings +from pydis_site.apps.content import urls as pages_urls from pydis_site.apps.redirect.views import CustomRedirectView +from pydis_site.apps.resources import urls as resources_urls app_name = "redirect" -urlpatterns = [ - path( - data["original_path"], - CustomRedirectView.as_view( - pattern_name=data["redirect_route"], - static_args=tuple(data.get("redirect_arguments", ())), - prefix_redirect=data.get("prefix_redirect", False) - ), - name=name - ) - for name, data in yaml.safe_load(settings.REDIRECTIONS_PATH.read_text()).items() -] + + +__PARAMETER_REGEX = re.compile(r"<\w+:\w+>") +REDIRECT_TEMPLATE = "" + + +@dataclasses.dataclass(frozen=True) +class Redirect: + """Metadata about a redirect route.""" + + original_path: str + redirect_route: str + redirect_arguments: tuple[str] = tuple() + + prefix_redirect: bool = False + + +def map_redirect(name: str, data: Redirect) -> list[URLPattern]: + """Return a pattern using the Redirects app, or a static HTML redirect for static builds.""" + if not settings.env("STATIC_BUILD"): + # Normal dynamic redirect + return [path( + data.original_path, + CustomRedirectView.as_view( + pattern_name=data.redirect_route, + static_args=tuple(data.redirect_arguments), + prefix_redirect=data.prefix_redirect + ), + name=name + )] + + # Create static HTML redirects for static builds + new_app_name = data.redirect_route.split(":")[0] + + if __PARAMETER_REGEX.search(data.original_path): + # Redirects for paths which accept parameters + # We generate an HTML redirect file for all possible entries + paths = [] + + class RedirectFunc: + def __init__(self, new_url: str, _name: str): + self.result = REDIRECT_TEMPLATE.format(url=new_url) + self.__qualname__ = _name + + def __call__(self, *args, **kwargs): + return self.result + + if new_app_name == resources_urls.app_name: + items = resources_urls.get_all_resources() + elif new_app_name == pages_urls.app_name: + items = pages_urls.get_all_pages() + else: + raise ValueError(f"Unknown app in redirect: {new_app_name}") + + for item in items: + entry = list(item.values())[0] + + # Replace dynamic redirect with concrete path + concrete_path = __PARAMETER_REGEX.sub(entry, data.original_path) + new_redirect = f"/{new_app_name}/{entry}" + pattern_name = f"{name}_{entry}" + + paths.append(distill_path( + concrete_path, + RedirectFunc(new_redirect, pattern_name), + name=pattern_name + )) + + return paths + + else: + redirect_path_name = "pages" if new_app_name == "content" else new_app_name + if len(data.redirect_arguments) > 0: + redirect_arg = data.redirect_arguments[0] + else: + redirect_arg = "resources/" + new_redirect = f"/{redirect_path_name}/{redirect_arg}" + + if new_redirect == "/resources/resources/": + new_redirect = "/resources/" + + return [distill_path( + data.original_path, + lambda *args: REDIRECT_TEMPLATE.format(url=new_redirect), + name=name, + )] + + +urlpatterns = [] +for _name, _data in yaml.safe_load(conf.settings.REDIRECTIONS_PATH.read_text()).items(): + urlpatterns.extend(map_redirect(_name, Redirect(**_data))) diff --git a/pydis_site/urls.py b/pydis_site/urls.py index 51ef4214..6cd31f26 100644 --- a/pydis_site/urls.py +++ b/pydis_site/urls.py @@ -11,19 +11,25 @@ NON_STATIC_PATTERNS = [ # Internal API ingress (cluster local) path('pydis-api/', include('pydis_site.apps.api.urls', namespace='internal_api')), - # This must be mounted before the `content` app to prevent Django - # from wildcard matching all requests to `pages/...`. - path('', include('pydis_site.apps.redirect.urls')), path('', include('django_prometheus.urls')), - - path('staff/', include('pydis_site.apps.staff.urls', namespace='staff')), ] if not settings.env("STATIC_BUILD") else [] urlpatterns = ( *NON_STATIC_PATTERNS, + + # This must be mounted before the `content` app to prevent Django + # from wildcard matching all requests to `pages/...`. + path('', include('pydis_site.apps.redirect.urls')), + path('pages/', include('pydis_site.apps.content.urls', namespace='content')), path('resources/', include('pydis_site.apps.resources.urls')), path('events/', include('pydis_site.apps.events.urls', namespace='events')), path('', include('pydis_site.apps.home.urls', namespace='home')), ) + + +if not settings.env("STATIC_BUILD"): + urlpatterns += ( + path('staff/', include('pydis_site.apps.staff.urls', namespace='staff')), + ) -- cgit v1.2.3 From 455dc792d38766156747a156e14b75d28c211525 Mon Sep 17 00:00:00 2001 From: Boris Muratov <8bee278@gmail.com> Date: Sun, 17 Oct 2021 15:06:38 +0300 Subject: Restructure bot contributing guide (#591) * Restructure bot contributing guide Restructures the bot guide to focus on getting users "through the door" first, and slowly adding additional information and options. The guide is built in terms of showing ways to run the bot and how to achieve it, rather than listing all of the information for each configuration and environment variable right away. That said, the attempt was to still present the reader with the full information they need, and to still be able to use as a quick reference for contributors who are already familiar with the project. As a style choice, this guide incorporates collapsible elements, which required some CSS and JS additions. This could be resolved with the bulma-collapsible extension, but it doesn't seem to function well inside django templates. The guide includes an optional config.yml to use with the test server template. This is a temporary measure until we get the bootstrapping application going. This guide additionally splits the bot account creation and obtaining Discord ID's guides and they didn't seem related. The original file is kept for now as it is used by other guides at the moment. --- .../guides/pydis-guides/contributing/bot.md | 735 +++++++++++++++++---- .../contributing/creating-bot-account.md | 17 + .../contributing/obtaining-discord-ids.md | 42 ++ pydis_site/static/css/content/page.css | 13 + .../content/contributing/pycharm_run_module.png | Bin 0 -> 38758 bytes pydis_site/static/js/content/page.js | 13 + pydis_site/templates/content/base.html | 1 + 7 files changed, 681 insertions(+), 140 deletions(-) create mode 100644 pydis_site/apps/content/resources/guides/pydis-guides/contributing/creating-bot-account.md create mode 100644 pydis_site/apps/content/resources/guides/pydis-guides/contributing/obtaining-discord-ids.md create mode 100644 pydis_site/static/images/content/contributing/pycharm_run_module.png create mode 100644 pydis_site/static/js/content/page.js (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md index 7419858e..4c09165d 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md @@ -2,206 +2,661 @@ title: Contributing to Bot description: A guide to setting up and configuring Bot. icon: fab fa-github -toc: 1 +toc: 3 --- - -# Requirements -* [Python 3.9](https://www.python.org/downloads/) -* [Poetry](https://github.com/python-poetry/poetry#installation) - * `pip install poetry` -* [Git](https://git-scm.com/downloads) - * [Windows](https://git-scm.com/download/win) - * [MacOS](https://git-scm.com/download/mac) or `brew install git` - * [Linux](https://git-scm.com/download/linux) -* A running webserver for the [site](../site) - * Follow the linked guide only if you don't want to use Docker or if you plan to do development on the site project too. - -## Using Docker - -Both the site and the bot can be started using Docker. -Using Docker is generally recommended (but not strictly required) because it abstracts away some additional set up work, especially for the site. -However, if you plan to attach a debugger to either the site or the bot, run the respective project directly on your system (AKA the _host_) instead. - -The requirements for Docker are: - -* [Docker CE](https://docs.docker.com/install/) -* [Docker Compose](https://docs.docker.com/compose/install/) (This already comes bundled on macOS and Windows, so you shouldn't need to install it) - * `pip install docker-compose` +The purpose of this guide is to get you a running local version of [the Python bot](https://github.com/python-discord/bot). +This page will focus on the quickest steps one can take, with mentions of alternatives afterwards. + +### Clone The Repository +First things first, to run the bot's code and make changes to it, you need a local version of it (on your computer). + +
+ +
+
+

If you don't have Git on your computer already, install it. You can additionally install a Git GUI such as GitKraken, or the GitHub CLI.

+

To learn more about Git, you can look into our guides, as well as this cheatsheet, Learn Git Branching, and otherwise any guide you can find on the internet. Once you got the basic idea though, the best way to learn Git is to use it.

+

Creating a copy of a repository under your own account is called a fork. This is where all your changes and commits will be pushed to, and from where your pull requests will originate from.

+

Learn about forking a project.

+
+
+
+
+ +You will need to create a fork of [the project](https://github.com/python-discord/bot), and clone the fork. +Once this is done, you will have completed the first step towards having a running version of the bot. + +#### Working on the Repository Directly +If you are a member of the organisation (a member of [this list](https://github.com/orgs/python-discord/people), or in our particular case, server staff), you can clone the project repository without creating a fork, and work on a feature branch instead. --- -# Fork the project -You will need access to a copy of the git repository of your own that will allow you to edit the code and push your commits to. -Creating a copy of a repository under your own account is called a _fork_. - -* [Learn how to create a fork of the repository here.](../forking-repository) -This is where all your changes and commits will be pushed to, and from where your PRs will originate from. +### Set Up a Test Server +The Python bot is tightly coupled with the Python Discord server, so to have a functional version of the bot you need a server with channels it can use. +It's possible to set the bot to use a single channel for all cogs, but that will cause extreme spam and will be difficult to work with. -For any staff member, since you have write permissions already to the original repository, you can just create a feature branch to push your commits to instead. - ---- -# Development environment -1. [Clone your fork to a local project directory](../cloning-repository/) -2. [Install the project's dependencies](../installing-project-dependencies/) +You can start your own server and set up channels as you see fit, but for your convenience we have a template for a development server you can use: [https://discord.new/zmHtscpYN9E3](https://discord.new/zmHtscpYN9E3). +Keep in mind that this is not a mirror of the Python server, but a reduced version for testing purposes. A lot of the channels in the Python server were merged. --- -# Test server and bot account -You will need your own test server and bot account on Discord to test your changes to the bot. -* [**Create a test server**](../setting-test-server-and-bot-account#setting-up-a-test-server) -* [**Create a bot account**](../setting-test-server-and-bot-account#setting-up-a-bot-account) -* Invite it to the server you just created. +### Set Up a Bot Account +You will need your own bot account on Discord to test your changes to the bot. +See [here](../creating-bot-account) for help with setting up a bot account. Once you have a bot account, invite it to the test server you created in the previous section. -### Privileged Intents +#### Privileged Intents -With `discord.py` 1.5 and later, it is now necessary to explicitly request that your Discord bot receives certain gateway events. +It is necessary to explicitly request that your Discord bot receives certain gateway events. The Python bot requires the `Server Member Intent` to function. In order to enable it, visit the [Developer Portal](https://discord.com/developers/applications/) (from where you copied your bot's login token) and scroll down to the `Privileged Gateway Intents` section. The `Presence Intent` is not necessary and can be left disabled. If your bot fails to start with a `PrivilegedIntentsRequired` exception, this indicates that the required intent was not enabled. -### Server Setup - -Setup categories, channels, emojis, roles, and webhooks in your server. To see what needs to be added, please refer to the following sections in the `config-default.yml` file: +--- -* `style.emojis` +### Configure the Bot +You now have both the bot's code and a server to run it on. It's time you to connect the two by changing the bot's configurations. + +#### config.yml +Entering the directory of the cloned code, you will find a file named `config-default.yml`. +This file contains the various configurations we use to make the bot run on the Python Discord server, such as channel and role IDs, and the emojis it works with. +It also contains configurations such as how long it takes for a help channel to time out, and how many messages a user needs to voice-verify. + +To run the bot in your test server, you will need to override some of those configurations. +Create and open a new file in the directory called `config.yml`. Alternatively, copy the `config-default.yml` file and rename the copy to `config.yml`. +The bot will first look at the items in `config.yml`, and will fall back to `config-default.yml` only if necessary. Note that you don't have to specify all items in `config.yml`, just the ones you want to override such as channel IDs. + +See [here](../obtaining-discord-ids) for help with obtaining Discord IDs. + +
+ +
+
+

If you used the provided server template, and you're not sure which channels belong where in the config file, you can use the config below. Pay attention to the comments with several # symbols, and replace the characters with the right IDs.

+
+                
+bot:
+    prefix:      "!"
+
+    redis:
+        host:  "redis"
+        password: null
+        port:  6379
+        use_fakeredis: true
+
+    stats:
+        presence_update_timeout: 300
+        statsd_host: "graphite.default.svc.cluster.local"
+
+urls:
+    # PyDis site vars
+    site:        &DOMAIN       "web:8000"
+    site_api:    &API    !JOIN [*DOMAIN, "/api"]
+    site_api_schema:           "http://"
+    site_paste:  &PASTE  !JOIN ["paste.", "pythondiscord.com"]
+    site_schema: &SCHEMA       "http://"
+    site_staff:  &STAFF  !JOIN [*DOMAIN, "/staff"]
+
+    paste_service:                      !JOIN ["https://", *PASTE, "/{key}"]
+    site_logs_view:                     !JOIN [*SCHEMA, *STAFF, "/bot/logs"]
+
+    # Snekbox
+    snekbox_eval_api: "http://localhost:8060/eval"
+
+##### <<  Replace the following � characters with the channel IDs in your test server  >> #####
+#  This assumes the template was used: https://discord.new/zmHtscpYN9E3
+dev_guild:
+    id: &DEV_GUILD_ID   �
+
+    categories:
+        logs:           &DEV_LOGS               �
+        help_available: &DEV_HELP_AVAILABLE     �
+        help_occupied:  &DEV_HELP_OCCUPIED      �
+        help_dormant:   &DEV_HELP_DORMANT       �
+        voice:          &DEV_VOICE              �
+
+    channels:
+        # Staff
+        admins_mods:            &DEV_ADMINS_MODS            �
+        lounge_helpers_org:     &DEV_LOUNGE_HELPERS_ORG     �
+        defcon:                 &DEV_DEFCON                 �
+        incidents:              &DEV_INCIDENTS              �
+        incidents_archive:      &DEV_INCIDENTS_ARCHIVE      �
+        staff_announcements:    &DEV_STAFF_ANNOUNCEMENTS    �
+        dev_logs:               &DEV_DEV_LOGS               �
+
+        # Logs
+        all_logs:   &DEV_ALL_LOGS   �
+        bb_logs:    &DEV_BB_LOGS    �
+        duck_pond:  &DEV_DUCK_POND  �
+
+        # Available Help Channels
+        how_to_get_help:    &DEV_HTGH   �
+
+        # Miscellaneous
+        bot_commands:       &DEV_BOT_CMD    �
+        general_meta_voice: &DEV_GMV        �
+        dev_core_contrib:   &DEV_DEV        �
+
+        # Voice
+        voice-verification: &DEV_VOICE_VER      �
+        vc:                 &DEV_VC             �
+        staff_voice:        &DEV_STAFF_VOICE    �
+
+        # News
+        announcements:  &DEV_ANNOUNCEMENTS  �
+        py_news:        &DEV_PY_NEWS        �
+
+        # Off-topic
+        off_topic_0: &DEV_OT_0  �
+        off_topic_1: &DEV_OT_1  �
+        off_topic_2: &DEV_OT_2  �
+
+guild:
+    ##### <<  Replace the following � characters with the role and webhook IDs in your test server  >> #####
+    roles:
+        announcements:                          �
+        contributors:                           �
+        help_cooldown:                          �
+        muted:              &MUTED_ROLE         �
+        partners:           &PY_PARTNER_ROLE    �
+        python_community:   &PY_COMMUNITY_ROLE  �
+        voice_verified:                         �
+
+        # Staff
+        admins:             &ADMINS_ROLE    �
+        core_developers:                    �
+        devops:                             �
+        domain_leads:                       �
+        helpers:            &HELPERS_ROLE   �
+        moderators:         &MODS_ROLE      �
+        mod_team:           &MOD_TEAM_ROLE  �
+        owners:             &OWNERS_ROLE    �
+        code_jam_event_team:                �
+        project_leads:                      �
+
+        # Code Jam
+        team_leaders:   �
+
+        # Streaming
+        video: �
+
+    webhooks:
+        big_brother:                            �
+        dev_log:                                �
+        duck_pond:                              �
+        incidents_archive:                      �
+        python_news:        &PYNEWS_WEBHOOK     �
+        talent_pool:                            �
+
+    ##### <<  At this point your test bot should be able to mostly work with your test server  >> #####
+    #  The following is the actual configs the bot uses, don't delete these.
+    id: *DEV_GUILD_ID
+    invite: "https://discord.gg/python"
+
+    categories:
+        help_available:                     *DEV_HELP_AVAILABLE
+        help_dormant:                       *DEV_HELP_DORMANT
+        help_in_use:                        *DEV_HELP_OCCUPIED
+        logs:                               *DEV_LOGS
+        voice:                              *DEV_VOICE
+
+    channels:
+        # Public announcement and news channels
+        announcements:  *DEV_ANNOUNCEMENTS
+        change_log:     *DEV_ANNOUNCEMENTS
+        mailing_lists:  *DEV_ANNOUNCEMENTS
+        python_events:  *DEV_ANNOUNCEMENTS
+        python_news:    *DEV_PY_NEWS
+
+        # Development
+        dev_contrib:        *DEV_DEV
+        dev_core:           *DEV_DEV
+        dev_log:            *DEV_DEV_LOGS
+
+        # Discussion
+        meta:                               *DEV_GMV
+        python_general:     *DEV_GMV
+
+        # Python Help: Available
+        cooldown:           *DEV_HTGH
+        how_to_get_help:    *DEV_HTGH
+
+        # Topical
+        discord_py:         *DEV_GMV
+
+        # Logs
+        attachment_log:     *DEV_ALL_LOGS
+        message_log:        *DEV_ALL_LOGS
+        mod_log:            *DEV_ALL_LOGS
+        user_log:           *DEV_ALL_LOGS
+        voice_log:          *DEV_ALL_LOGS
+
+        # Off-topic
+        off_topic_0:    *DEV_OT_0
+        off_topic_1:    *DEV_OT_1
+        off_topic_2:    *DEV_OT_2
+
+        # Special
+        bot_commands:       *DEV_BOT_CMD
+        voice_gate:         *DEV_VOICE_VER
+        code_jam_planning:  *DEV_ADMINS_MODS
+
+        # Staff
+        admins:             *DEV_ADMINS_MODS
+        admin_spam:         *DEV_ADMINS_MODS
+        defcon:             *DEV_DEFCON
+        duck_pond:          *DEV_DUCK_POND
+        helpers:            *DEV_LOUNGE_HELPERS_ORG
+        incidents:                          *DEV_INCIDENTS
+        incidents_archive:                  *DEV_INCIDENTS_ARCHIVE
+        mods:               *DEV_ADMINS_MODS
+        mod_alerts:                         *DEV_ADMINS_MODS
+        mod_meta:           *DEV_ADMINS_MODS
+        mod_spam:           *DEV_ADMINS_MODS
+        mod_tools:          *DEV_ADMINS_MODS
+        organisation:       *DEV_LOUNGE_HELPERS_ORG
+        staff_lounge:       *DEV_LOUNGE_HELPERS_ORG
+
+        # Staff announcement channels
+        admin_announcements:    *DEV_STAFF_ANNOUNCEMENTS
+        mod_announcements:      *DEV_STAFF_ANNOUNCEMENTS
+        staff_announcements:    *DEV_STAFF_ANNOUNCEMENTS
+
+        # Voice Channels
+        admins_voice:       *DEV_STAFF_VOICE
+        code_help_voice_1:  *DEV_VC
+        code_help_voice_2:  *DEV_VC
+        general_voice:      *DEV_VC
+        staff_voice:        *DEV_STAFF_VOICE
+
+        # Voice Chat
+        code_help_chat_1:                   *DEV_GMV
+        code_help_chat_2:                   *DEV_GMV
+        staff_voice_chat:                   *DEV_ADMINS_MODS
+        voice_chat:                         *DEV_GMV
+
+        # Watch
+        big_brother_logs:                   *DEV_BB_LOGS
+
+    moderation_categories:
+        - *DEV_LOGS
+
+    moderation_channels:
+        - *DEV_ADMINS_MODS
+
+    # Modlog cog ignores events which occur in these channels
+    modlog_blacklist:
+        - *DEV_ADMINS_MODS
+        - *DEV_ALL_LOGS
+        - *DEV_STAFF_VOICE
+
+    reminder_whitelist:
+        - *DEV_BOT_CMD
+        - *DEV_DEV
+
+    moderation_roles:
+        - *ADMINS_ROLE
+        - *MODS_ROLE
+        - *MOD_TEAM_ROLE
+        - *OWNERS_ROLE
+
+    staff_roles:
+        - *ADMINS_ROLE
+        - *HELPERS_ROLE
+        - *MODS_ROLE
+        - *OWNERS_ROLE
+
+##### <<  The bot shouldn't fail without these, but commands adding specific emojis won't work.  >> #####
+#  You should at least set the trashcan. Set the incidents emojis if relevant.
+style:
+    emojis:
+        badge_bug_hunter: "<:bug_hunter_lvl1:�>"
+        badge_bug_hunter_level_2: "<:bug_hunter_lvl2:�>"
+        badge_early_supporter: "<:early_supporter:�>"
+        badge_hypesquad: "<:hypesquad_events:�>"
+        badge_hypesquad_balance: "<:hypesquad_balance:�>"
+        badge_hypesquad_bravery: "<:hypesquad_bravery:�>"
+        badge_hypesquad_brilliance: "<:hypesquad_brilliance:�>"
+        badge_partner: "<:partner:�>"
+        badge_staff: "<:discord_staff:�>"
+        badge_verified_bot_developer: "<:verified_bot_dev:�>"
+
+        defcon_shutdown:    "<:defcondisabled:�>"
+        defcon_unshutdown:  "<:defconenabled:�>"
+        defcon_update:      "<:defconsettingsupdated:�>"
+
+        failmail: "<:failmail:�>"
+
+        #incident_actioned:      "<:incident_actioned:�>"
+        incident_investigating: "<:incident_investigating:�>"
+        incident_unactioned:    "<:incident_unactioned:�>"
+
+        status_dnd:     "<:status_dnd:�>"
+        status_idle:    "<:status_idle:�>"
+        status_offline: "<:status_offline:�>"
+        status_online:  "<:status_online:�>"
+
+        trashcan: "<:trashcan:�>"
+
+##### <<  Optional - If you don't care about the filtering and help channel cogs, ignore the rest of this file  >> #####
+filter:
+    # What do we filter?
+    filter_domains:        true
+    filter_everyone_ping:  true
+    filter_invites:        true
+    filter_zalgo:          false
+    watch_regex:           true
+    watch_rich_embeds:     true
+
+    # Notify user on filter?
+    # Notifications are not expected for "watchlist" type filters
+    notify_user_domains:        false
+    notify_user_everyone_ping:  true
+    notify_user_invites:        true
+    notify_user_zalgo:          false
+
+    # Filter configuration
+    offensive_msg_delete_days: 7     # How many days before deleting an offensive message?
+    ping_everyone:             true
+
+    # Censor doesn't apply to these
+    channel_whitelist:
+        - *DEV_ADMINS_MODS
+        - *DEV_BB_LOGS
+        - *DEV_ALL_LOGS
+        - *DEV_LOUNGE_HELPERS_ORG
+
+    role_whitelist:
+        - *ADMINS_ROLE
+        - *HELPERS_ROLE
+        - *MODS_ROLE
+        - *OWNERS_ROLE
+        - *PY_COMMUNITY_ROLE
+        - *PY_PARTNER_ROLE
+
+help_channels:
+    enable: true
+
+    # Minimum interval before allowing a certain user to claim a new help channel
+    claim_minutes: 1
+
+    # Roles which are allowed to use the command which makes channels dormant
+    cmd_whitelist:
+        - *HELPERS_ROLE
+
+    # Allowed duration of inactivity before making a channel dormant
+    idle_minutes: 1
+
+    # Allowed duration of inactivity when channel is empty (due to deleted messages)
+    # before message making a channel dormant
+    deleted_idle_minutes: 1
+
+    # Maximum number of channels to put in the available category
+    max_available: 2
+
+    # Maximum number of channels across all 3 categories
+    # Note Discord has a hard limit of 50 channels per category, so this shouldn't be > 50
+    max_total_channels: 20
+
+    # Prefix for help channel names
+    name_prefix: 'help-'
+
+    # Notify if more available channels are needed but there are no more dormant ones
+    notify: true
+
+    # Channel in which to send notifications
+    notify_channel: *DEV_LOUNGE_HELPERS_ORG
+
+    # Minimum interval between helper notifications
+    notify_minutes: 5
+
+    # Mention these roles in notifications
+    notify_roles:
+        - *HELPERS_ROLE
+
+##### <<  Add any additional sections you need to override from config-default.yml  >> #####
+            
+          
+
+
+ +If you don't wish to use the provided `config.yml` above, these are the main sections in `config-default.yml` that need overriding: + +* `guild.id` * `guild.categories` * `guild.channels` * `guild.roles` * `guild.webhooks` +* `style.emojis` -We understand this is tedious and are working on a better solution for setting up test servers. -In the meantime, [here](https://discord.new/zmHtscpYN9E3) is a template for you to use.
+Additionally: ---- -# Configure the bot -You will need to copy IDs of the test Discord server, as well as the created channels and roles to paste in the config file. -If you're not sure how to do this, [check out the information over here.](../setting-test-server-and-bot-account#obtain-the-ids) - -1. Create a copy of `config-default.yml` named `config.yml` in the same directory. -2. Set `guild.id` to your test servers's ID. -3. Change the IDs in the [sections](#server-setup) mentioned earlier to match the ones in your test server. -4. Set `urls.site_schema` and `urls.site_api_schema` to `"http://"`. -5. Set `urls.site`: - - If running the webserver in Docker, set it to `"web:8000"`. - - If the site container is running separately (i.e. started from a clone of the site repository), then [COMPOSE_PROJECT_NAME](../docker/#compose-project-names) has to be set to use this domain. If you choose not to set it, the domain in the following step can be used instead. - - If running the webserver locally and the hosts file has been configured, set it to `"pythondiscord.local:8000"`. - - Otherwise, use whatever domain corresponds to the server where the site is being hosted. -6. Set `urls.site_api` to whatever value you assigned to `urls.site` with `api` prefixed to it, for example if you set `urls.site` to `web:8000` then set `urls.site_api` to `api.web:8000`. -7. Setup the environment variables listed in the section below. - -### Environment variables - -These contain various settings used by the bot. -To learn how to set environment variables, read [this page](../configure-environment-variables) first. +* At this stage, set `bot.redis.use_fakeredis` to `true`. If you're looking for instructions for working with Redis, see [Working with Redis](#optional-working-with-redis). +* Set `urls.site_api` to `!JOIN [*DOMAIN, "/api]`. +* Set `urls.site_schema` and `urls.site_api_schema` to `"http://"`. -The following is a list of all available environment variables used by the bot: +We understand this is tedious and are working on a better solution for setting up test servers. -| Variable | Required | Description | -| -------- | -------- | -------- | -| `BOT_TOKEN` | Always | Your Discord bot account's token (see [Test server and bot account](#test-server-and-bot-account)). | -| `BOT_API_KEY` | When running bot without Docker | Used to authenticate with the site's API. When using Docker to run the bot, this is automatically set. By default, the site will always have the API key shown in the example below. | -| `BOT_SENTRY_DSN` | When connecting the bot to sentry | The DSN of the sentry monitor. | -| `BOT_TRACE_LOGGERS ` | When you wish to see specific or all trace logs | Comma separated list that specifies which loggers emit trace logs through the listed names. If the ! prefix is used, all of the loggers except the listed ones are set to the trace level. If * is used, the root logger is set to the trace level. | -| `REDIS_PASSWORD` | When not using FakeRedis | The password to connect to the redis database. *Leave empty if you're not using REDIS.* | +
+ +
+
+ While it's technically possible to edit config-default.yml to match your server, it is heavily discouraged. + This file's purpose is to provide the configurations the Python bot needs to run in the Python server in production, and should remain as such. + In contrast, the config.yml file can remain in your local copy of the code, and will be ignored by commits via the project's .gitignore. +
+
+
+
+ +#### .env +The second file you need to create is the one containing the environment variables, and needs to be named `.env`. +Inside, add the line `BOT_TOKEN=YourDiscordBotTokenHere`. See [here](../creating-bot-account) for help with obtaining the bot token. + +The `.env` file will be ignored by commits. --- -If you are running on the host, while not required, we advise you set `use_fakeredis` to `true` in your `config.yml` file during development to avoid the need of setting up a Redis server. -It does mean you may lose persistent data on restart but this is non-critical. -Otherwise, you should set up a Redis instance and fill in the necessary config. -{: .notification .is-warning } +### Run it! +#### With Docker +You are now almost ready to run the Python bot. The simplest way to do so is with Docker. + +
+ +
+
+ The requirements for Docker are: +
    +
  • Docker CE
  • +
  • Docker Compose. If you're using macOS and Windows, this already comes bundled with the previous installation. Otherwise, you can download it either from the website, or by running pip install docker-compose.
  • +
+

If you get any Docker related errors, reference the Possible Issue section of the Docker page.

+
+
+
+
+ +In your `config.yml` file: + +* Set `urls.site` to `"web:8000"`. +* If you wish to work with snekbox set `urls.snekbox_eval_api` to `"http://snekbox:8060/eval"`. + +Assuming you have Docker installed **and running**, enter the cloned repo in the command line and type `docker-compose up`. + +After pulling the images and building the containers, your bot will start. Enter your server and type `!help` (or whatever prefix you chose instead of `!`). + +Your bot is now running, but this method makes debugging with an IDE a fairly involved process. For additional running methods, continue reading the following sections. + +#### With the Bot Running Locally +The advantage of this method is that you can run the bot's code in your preferred editor, with debugger and all, while keeping all the setup of the bot's various dependencies inside Docker. + +* Append the following line to your `.env` file: `BOT_API_KEY=badbot13m0n8f570f942013fc818f234916ca531`. +* In your `config.yml` file, set `urls.site` to `"localhost:8000"`. If you wish to keep using `web:8000`, then [COMPOSE_PROJECT_NAME](../docker/#compose-project-names) has to be set. +* To work with snekbox, set `urls.snekbox_eval_api` to `"http://localhost:8060/eval"` + +You will need to start the services separately, but if you got the previous section with Docker working, that's pretty simple: + +* `docker-compose up web` to start the site container. This is required. +* `docker-compose up snekbox` to start the snekbox container. You only need this if you're planning on working on the snekbox cog. +* `docker-compose up redis` to start the Redis container. You only need this if you're not using fakeredis. For more info refer to [Working with Redis](#optional-working-with-redis). + +You can start several services together: `docker-compose up web snekbox redis`. + +##### Setting Up a Development Environment +The bot's code is Python code like any other. To run it locally, you will need the right version of Python with the necessary packages installed: + +1. Make sure you have [Python 3.9](https://www.python.org/downloads/) installed. It helps if it is your system's default Python version. +2. [Install Poetry](https://github.com/python-poetry/poetry#installation). +3. [Install the dependencies](../installing-project-dependencies). + +With at least the site running in Docker already (see the previous section on how to start services separately), you can now start the bot locally through the command line, or through your preferred IDE. +
+ +
+
+ Notice that the bot is started as a module. There are several ways to do so: +
    +
  • Through the command line, inside the bot directory, with either poetry run task start, or directly python -m bot.
  • +
  • If using PyCharm, enter Edit Configurations and set everything according to this image:
  • +
  • If using Visual Studio Code, set the interpreter to the poetry environment you created. In launch.json create a new Python configuration, and set the name of the program to be run to bot. VSC will correctly run it as a module.
  • +
+
+
+
+
+ +#### With More Things Running Locally +You can run additional services on the host, but this guide won't go over how to install and start them in this way. +If possible, prefer to start the services through Docker to replicate the production environment as much as possible. + +The site, however, is a mandatory service for the bot. +Refer to the [previous section](#with-the-bot-running-locally) and the [site contributing guide](../site) to learn how to start it on the host, in which case you will need to change `urls.site` in `config.yml` to wherever the site is being hosted. --- +### Development Tips +Now that you have everything setup, it is finally time to make changes to the bot! -Example `.env` file: +#### Working with Git -```shell -BOT_TOKEN=YourDiscordBotTokenHere -BOT_API_KEY=badbot13m0n8f570f942013fc818f234916ca531 -REDDIT_CLIENT_ID=YourRedditClientIDHere -REDDIT_SECRET=YourRedditSecretHere -``` +If you have not yet [read the contributing guidelines](../contributing-guidelines), now is a good time. +Contributions that do not adhere to the guidelines may be rejected. ---- -# Run the project +Notably, version control of our projects is done using Git and Github. +It can be intimidating at first, so feel free to ask for any help in the server. -The bot can run with or without Docker. -When using Docker, the site, which is a prerequisite, can be automatically set up too. -If you don't use Docker, you have to first follow [the site guide](../site/) to set it up yourself. -The bot and site can be started using independent methods. -For example, the site could run with Docker and the bot could run directly on your system (AKA the _host_) or vice versa. +[**Click here to see the basic Git workflow when contributing to one of our projects.**](../working-with-git/) -## Run with Docker +#### Running tests -The following sections describe how to start either the site, bot, or both using Docker. -If you are not interested in using Docker, see [this page](../site/) for setting up the site and [this section](#run-on-the-host) for running the bot. +[This section](https://github.com/python-discord/bot/blob/main/tests/README.md#tools) of the README in the `tests` repository will explain how to run tests. +The whole document explains how unittesting works, and how it fits in the context of our project. -If you get any Docker related errors, reference the [Possible Issues](../docker#possible-issues) section of the Docker page. +Make sure to run tests *before* pushing code. -### Site and bot +Even if you run the bot through Docker, you might want to [setup a development environment](#setting-up-a-development-environment) in order to run the tests locally. -This method will start both the site and the bot using Docker. +#### Lint before you push +As mentioned in the [contributing guidelines](../contributing-guidelines), you should make sure your code passes linting for each commit you make. -Start the containers using Docker Compose while inside the root of the project directory: +For ease of development, you can install the pre-commit hook with `poetry run task precommit`, which will check your code every time you try to commit it. +For that purpose, even if you run the bot through Docker, you might want to [setup a development environment](#setting-up-a-development-environment), as otherwise the hook installation will fail. -```shell -docker-compose up -``` +#### Reloading parts of the bot +If you make changes to an extension, you might not need to restart the entire bot for the changes to take effect. The command `!ext reload ` re-imports the files associated with the extension. +Invoke `!ext list` for a full list of the available extensions. In this bot in particular, cogs are defined inside extensions. -The `-d` option can be appended to the command to run in detached mode. -This runs the containers in the background so the current terminal session is available for use with other things. +Note that if you changed code that is not associated with a particular extension, such as utilities, converters, and constants, you will need to restart the bot. -### Site only +#### Adding new statistics -This method will start only the site using Docker. +Details on how to add new statistics can be found on the [statistic infrastructure page](https://blog.pythondiscord.com/statistics-infrastructure). +We are always open to more statistics so add as many as you can! -```shell -docker-compose up site -``` +--- -See [this section](#run-on-the-host) for how to start the bot on the host. +### Optional: Working with Redis +In [Configure the Bot](#configyml) you were asked to set `bot.redis.use_fakeredis` to `true`. If you do not need to work on features that rely on Redis, this is enough. Fakeredis will give the illusion that features relying on Redis are saving information properly, but restarting the bot or the specific cog will wipe that information. -### Bot only +If you are working on a feature that relies on Redis, you will need to enable Redis to make sure persistency is achieved for the feature across restarts. The first step towards that is going to `config.yml` and setting `bot.redis.use_fakeredis` to `false`. -This method will start only the bot using Docker. -The site has to have been started somehow beforehand. +#### Starting Redis in Docker (Recommended) +If you're using the Docker image provided in the project's Docker Compose, open your `config.yml` file, set `bot.redis.host` to `redis`, and `bot.redis.password` to `null`. -Start the bot using Docker Compose while inside the root of the project directory: +#### Starting Redis Using Other Methods +You can run your own instance of Redis, but in that case you will need to correctly set `bot.redis.host` and `bot.redis.port`, and the `bot.redis.password` value in `config-default.yml` should not be overridden. Then, enter the `.env` file, and set `REDIS_PASSWORD` to whatever password you set. -```shell -docker-compose up --no-deps bot -``` +--- -## Run on the host +### Optional: Working with Metricity +[Metricity](https://github.com/python-discord/metricity) is our home-grown bot for collecting metrics on activity within the server, such as what users are present, and IDs of the messages they've sent. +Certain features in the Python bot rely on querying the Metricity database for information such as the number of messages a user has sent, most notably the voice verification system. -Running on the host is particularly useful if you wish to debug the bot. -The site has to have been started somehow beforehand. +If you wish to work on a feature that relies on Metricity, for your convenience we've made the process of using it relatively painless with Docker: Enter the `.env` file you've written for the Python bot, and append the line `USE_METRICITY=true`. +Note that if you don't need Metricity, there's no reason to have it enabled as it is just unnecessary overhead. -```shell -poetry run task start +To make the Metricity bot work with your test server, you will need to override its configurations similarly to the Python bot. +You can see the various configurations in [the Metricity repo](https://github.com/python-discord/metricity), but the bare minimum is the guild ID setting. +In your local version of the Python bot repo, create a file called `metricity-config.toml` and insert the following lines: +```yaml +[bot] +guild_id = replace_with_your_guild_id ``` +To properly replicate production behavior, set the `staff_role_id`, `staff_categories`, and `ignore_categories` fields as well. ---- -## Working with Git -Now that you have everything setup, it is finally time to make changes to the bot! -If you have not yet [read the contributing guidelines](../contributing-guidelines), now is a good time. -Contributions that do not adhere to the guidelines may be rejected. +Now, `docker-compose up` will also start Metricity. -Notably, version control of our projects is done using Git and Github. -It can be intimidating at first, so feel free to ask for any help in the server. +If you want to run the bot locally, you can run `docker-compose up metricity` instead. -[**Click here to see the basic Git workflow when contributing to one of our projects.**](../working-with-git/) +--- -## Adding new statistics +### Issues? +If you have any issues with setting up the bot, come discuss it with us on the [#dev-contrib](https://discord.gg/2h3qBv8Xaa) channel on our server. -Details on how to add new statistics can be found on the [statistic infrastructure page](https://blog.pythondiscord.com/statistics-infrastructure). -We are always open to more statistics so add as many as you can! +If you find any bugs in the bot or would like to request a feature, feel free to open an issue on the repository. -## Running tests +--- -[This section](https://github.com/python-discord/bot/blob/main/tests/README.md#tools) of the README in the `tests` repository will explain how to run tests. -The whole document explains how unittesting works, and how it fits in the context of our project. +### Appendix: Full ENV File Options +The following is a list of all available environment variables used by the bot: + +| Variable | Required | Description | +| -------- | -------- | -------- | +| `BOT_TOKEN` | Always | Your Discord bot account's token (see [Set Up a Bot Account](##set-up-a-bot-account)). | +| `BOT_API_KEY` | When running bot without Docker | Used to authenticate with the site's API. When using Docker to run the bot, this is automatically set. By default, the site will always have the API key shown in the example below. | +| `BOT_SENTRY_DSN` | When connecting the bot to sentry | The DSN of the sentry monitor. | +| `BOT_TRACE_LOGGERS ` | When you wish to see specific or all trace logs | Comma separated list that specifies which loggers emit trace logs through the listed names. If the ! prefix is used, all of the loggers except the listed ones are set to the trace level. If * is used, the root logger is set to the trace level. | +| `BOT_DEBUG` | In production | `true` or `false`, depending on whether to enable debug mode, affecting the behavior of certain features. `true` by default. +| `REDIS_PASSWORD` | When not using FakeRedis | The password to connect to the Redis database (see [Optional: Working with Redis](#optional-working-with-redis)). | +| `USE_METRICITY` | When using Metricity | `true` or `false`, depending on whether to enable metrics collection using Metricity (see [Optional: Working with Metricity](#optional-working-with-metricity)). `false` by default. | +| `GITHUB_API_KEY` | When you wish to interact with GitHub | The API key to interact with GitHub, for example to download files for the branding manager. +| `METABASE_USERNAME` | When you wish to interact with Metabase | The username for a Metabase admin account. +| `METABASE_PASSWORD` | When you wish to interact with Metabase | The password for a Metabase admin account. Have fun! diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/creating-bot-account.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/creating-bot-account.md new file mode 100644 index 00000000..ee38baa3 --- /dev/null +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/creating-bot-account.md @@ -0,0 +1,17 @@ +--- +title: Setting up a Bot Account +description: How to set up a bot account. +icon: fab fa-discord +--- +1. Go to the [Discord Developers Portal](https://discordapp.com/developers/applications/). +2. Click on the `New Application` button, enter your desired bot name, and click `Create`. +3. In your new application, go to the `Bot` tab, click `Add Bot`, and confirm `Yes, do it!` +4. Change your bot's `Public Bot` setting off so only you can invite it, save, and then get your **Bot Token** with the `Copy` button. +> **Note:** **DO NOT** post your bot token anywhere public. If you do it can and will be compromised. +5. Save your **Bot Token** somewhere safe to use in the project settings later. +6. In the `General Information` tab, grab the **Client ID**. +7. Replace `` in the following URL and visit it in the browser to invite your bot to your new test server. +```plaintext +https://discordapp.com/api/oauth2/authorize?client_id=&permissions=8&scope=bot +``` +Optionally, you can generate your own invite url in the `OAuth` tab, after selecting `bot` as the scope. diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/obtaining-discord-ids.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/obtaining-discord-ids.md new file mode 100644 index 00000000..afa07b5a --- /dev/null +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/obtaining-discord-ids.md @@ -0,0 +1,42 @@ +--- +title: Obtaining Discord IDs +description: How to obtain Discord IDs to set up the bots. +icon: fab fa-discord +--- +First, enable developer mode in your client so you can easily copy IDs. + +1. Go to your `User Settings` and click on the `Appearance` tab. +2. Under `Advanced`, enable `Developer Mode`. + +#### Guild ID + +Right click the server icon and click `Copy ID`. + +#### Channel ID + +Right click a channel name and click `Copy ID`. + +#### Role ID + +Right click a role and click `Copy ID`. +The easiest way to do this is by going to the role list in the guild's settings. + +#### Emoji ID + +Insert the emoji into the Discord text box, then add a backslash (`\`) right before the emoji and send the message. +The result should be similar to the following + +```plaintext +<:bbmessage:511950877733552138> +``` + +The long number you see, in this case `511950877733552138`, is the emoji's ID. + +#### Webhook ID + +Once a [webhook](https://support.discordapp.com/hc/en-us/articles/228383668-Intro-to-Webhooks) is created, the ID is found in the penultimate part of the URL. +For example, in the following URL, `661995360146817053` is the ID of the webhook. + +```plaintext +https://discordapp.com/api/webhooks/661995360146817053/t-9mI2VehOGcPuPS_F8R-6mB258Ob6K7ifhtoxerCvWyM9VEQug-anUr4hCHzdbhzfbz +``` diff --git a/pydis_site/static/css/content/page.css b/pydis_site/static/css/content/page.css index d831f86d..2d4bd325 100644 --- a/pydis_site/static/css/content/page.css +++ b/pydis_site/static/css/content/page.css @@ -77,3 +77,16 @@ ul.menu-list.toc { li img { margin-top: 0.5em; } + +.collapsible { + cursor: pointer; + width: 100%; + border: none; + outline: none; +} + +.collapsible-content { + overflow: hidden; + max-height: 0; + transition: max-height 0.2s ease-out; +} diff --git a/pydis_site/static/images/content/contributing/pycharm_run_module.png b/pydis_site/static/images/content/contributing/pycharm_run_module.png new file mode 100644 index 00000000..c5030519 Binary files /dev/null and b/pydis_site/static/images/content/contributing/pycharm_run_module.png differ diff --git a/pydis_site/static/js/content/page.js b/pydis_site/static/js/content/page.js new file mode 100644 index 00000000..366a033c --- /dev/null +++ b/pydis_site/static/js/content/page.js @@ -0,0 +1,13 @@ +document.addEventListener("DOMContentLoaded", () => { + const headers = document.getElementsByClassName("collapsible"); + for (const header of headers) { + header.addEventListener("click", () => { + var content = header.nextElementSibling; + if (content.style.maxHeight){ + content.style.maxHeight = null; + } else { + content.style.maxHeight = content.scrollHeight + "px"; + } + }); + } +}); diff --git a/pydis_site/templates/content/base.html b/pydis_site/templates/content/base.html index 21895479..00f4fce4 100644 --- a/pydis_site/templates/content/base.html +++ b/pydis_site/templates/content/base.html @@ -7,6 +7,7 @@ + {% endblock %} {% block content %} -- cgit v1.2.3 From 827337292544cb331bc7f1f70760a2d564e9cd9f Mon Sep 17 00:00:00 2001 From: Boris Muratov <8bee278@gmail.com> Date: Sun, 17 Oct 2021 15:21:28 +0300 Subject: Fix typo in bot guide --- .../apps/content/resources/guides/pydis-guides/contributing/bot.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md index 4c09165d..27c67e37 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md @@ -444,7 +444,7 @@ If you don't wish to use the provided `config.yml` above, these are the main sec Additionally: * At this stage, set `bot.redis.use_fakeredis` to `true`. If you're looking for instructions for working with Redis, see [Working with Redis](#optional-working-with-redis). -* Set `urls.site_api` to `!JOIN [*DOMAIN, "/api]`. +* Set `urls.site_api` to `!JOIN [*DOMAIN, "/api"]`. * Set `urls.site_schema` and `urls.site_api_schema` to `"http://"`. We understand this is tedious and are working on a better solution for setting up test servers. -- cgit v1.2.3 From 29425c2466a5d6fb5f8c332aff5a0a3a61ced677 Mon Sep 17 00:00:00 2001 From: Boris Muratov <8bee278@gmail.com> Date: Sun, 17 Oct 2021 15:55:32 +0300 Subject: Remove stray `#` in bot guide --- .../apps/content/resources/guides/pydis-guides/contributing/bot.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md index 27c67e37..183f1505 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md @@ -648,7 +648,7 @@ The following is a list of all available environment variables used by the bot: | Variable | Required | Description | | -------- | -------- | -------- | -| `BOT_TOKEN` | Always | Your Discord bot account's token (see [Set Up a Bot Account](##set-up-a-bot-account)). | +| `BOT_TOKEN` | Always | Your Discord bot account's token (see [Set Up a Bot Account](#set-up-a-bot-account)). | | `BOT_API_KEY` | When running bot without Docker | Used to authenticate with the site's API. When using Docker to run the bot, this is automatically set. By default, the site will always have the API key shown in the example below. | | `BOT_SENTRY_DSN` | When connecting the bot to sentry | The DSN of the sentry monitor. | | `BOT_TRACE_LOGGERS ` | When you wish to see specific or all trace logs | Comma separated list that specifies which loggers emit trace logs through the listed names. If the ! prefix is used, all of the loggers except the listed ones are set to the trace level. If * is used, the root logger is set to the trace level. | -- cgit v1.2.3 From 594312fd90bf612895ca4bf4ae3c52186831d224 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Sun, 17 Oct 2021 21:13:24 +0800 Subject: FAQ: Update reference to #dev-branding Ref: https://discord.com/channels/267624335836053506/429409067623251969/896753201645232169 I think it should be updated so newer members won't get confused when they don't see a #media-branding. --- pydis_site/apps/content/resources/frequently-asked-questions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/frequently-asked-questions.md b/pydis_site/apps/content/resources/frequently-asked-questions.md index a9a092fe..1c9c3f6d 100644 --- a/pydis_site/apps/content/resources/frequently-asked-questions.md +++ b/pydis_site/apps/content/resources/frequently-asked-questions.md @@ -119,7 +119,7 @@ You can also open an issue on our meta repo on GitHub, which can be found [here] While we love our blurple Python logo, we also enjoy celebrating other events throughout the year, like Advent of Code, Pride Month, Black History Month, Valentine's Day, Diwali, and more! In the spirit of those celebrations, we like to have some fun and change our icon instead. If you're wondering why it's changed this time, check out `#changelog` on the server, as the reasoning for the recent change will be there. -If you'd like to contribute and create a Python Discord server icon for us to use, check out [our branding repo](https://github.com/python-discord/branding) for what we currently have and talk to us in the `#media-branding` channel in the server. +If you'd like to contribute and create a Python Discord server icon for us to use, check out [our branding repo](https://github.com/python-discord/branding) for what we currently have and talk to us in the `#dev-branding` channel in the server. ## Misc -- cgit v1.2.3 From 569c2c2d2540fda797ade699c7acb67e402114e5 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Sun, 17 Oct 2021 21:29:53 +0800 Subject: Fix typos across codebase ./pydis_site/apps/resources/resources/tools/ides/thonny.yaml:1: specifically ./pydis_site/apps/content/resources/guides/pydis-guides/helping-others.md:115: considered ./pydis_site/apps/content/resources/guides/pydis-guides/contributing/issues.md:59 labels ./pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md:99: recommend ./pydis_site/apps/content/resources/guides/pydis-guides/contributing/site.md:111: particularly ./pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md:29: Integer ./pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md:67: calculating ./pydis_site/apps/api/tests/test_off_topic_channel_names.py:157: response I didn't touch the code jam and game jam typos because I'm not sure if they should be preserved as is. There were a few 'seperated' typos which I didn't change because I *think* it's just another way of spelling it? In the offensive words test there was a keyword argument named `fied` which I didn't touch because I wasn't sure where that was from. --- pydis_site/apps/api/tests/test_off_topic_channel_names.py | 2 +- .../apps/content/resources/guides/pydis-guides/contributing/issues.md | 2 +- .../resources/guides/pydis-guides/contributing/sir-lancebot.md | 2 +- .../pydis-guides/contributing/sir-lancebot/env-var-reference.md | 4 ++-- .../apps/content/resources/guides/pydis-guides/contributing/site.md | 2 +- .../apps/content/resources/guides/pydis-guides/helping-others.md | 2 +- pydis_site/apps/resources/resources/tools/ides/thonny.yaml | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_off_topic_channel_names.py b/pydis_site/apps/api/tests/test_off_topic_channel_names.py index 63993978..1825f6e6 100644 --- a/pydis_site/apps/api/tests/test_off_topic_channel_names.py +++ b/pydis_site/apps/api/tests/test_off_topic_channel_names.py @@ -154,7 +154,7 @@ class DeletionTests(AuthenticatedAPITestCase): cls.test_name_2 = OffTopicChannelName.objects.create(name='bbq-with-bisk') def test_deleting_unknown_name_returns_404(self): - """Return 404 reponse when trying to delete unknown name.""" + """Return 404 response when trying to delete unknown name.""" url = reverse('api:bot:offtopicchannelname-detail', args=('unknown-name',)) response = self.client.delete(url) diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/issues.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/issues.md index 9151e5e3..0c6d3513 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/issues.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/issues.md @@ -56,7 +56,7 @@ Definitely try to: Labels allow us to better organise Issues by letting us view what type of Issue it is, how it might impact the codebase and at what stage it's at. -In our repositories, we try to prefix labels belonging to the same group, for example the label groups `status` or `type`. We will be trying to keep to the same general structure across our project repositories, but just have a look at the full lables list in the respective repository to get a clear idea what's available. +In our repositories, we try to prefix labels belonging to the same group, for example the label groups `status` or `type`. We will be trying to keep to the same general structure across our project repositories, but just have a look at the full labels list in the respective repository to get a clear idea what's available. If you're a contributor, you can add relevant labels yourself to any new Issue ticket you create. diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md index 60169c01..a0d3d463 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md @@ -96,7 +96,7 @@ Otherwise, please see the below linked guide for Redis related variables. --- # Run the project -The sections below describe the two ways you can run this project. We recomend Docker as it requires less setup. +The sections below describe the two ways you can run this project. We recommend Docker as it requires less setup. ## Run with Docker Make sure to have Docker running, then use the Docker command `docker-compose up` in the project root. diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md index eba737ad..9ad014a2 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md @@ -26,7 +26,7 @@ Additionally, you may find the following environment variables useful during dev | `BOT_DEBUG` | Debug mode of the bot | False | | `PREFIX` | The bot's invocation prefix | `.` | | `CYCLE_FREQUENCY` | Amount of days between cycling server icon | 3 | -| `MONTH_OVERRIDE` | Interger in range `[0, 12]`, overrides current month w.r.t. seasonal decorators | +| `MONTH_OVERRIDE` | Integer in range `[0, 12]`, overrides current month w.r.t. seasonal decorators | | `REDIS_HOST` | The address to connect to for the Redis database. | | `REDIS_PORT` | | | `REDIS_PASSWORD` | | @@ -64,7 +64,7 @@ These variables might come in handy while working on certain cogs: | Advent of Code | `AOC_LEADERBOARDS` | List of leaderboards seperated by `::`. Each entry should have an `id,session cookie,join code` seperated by commas in that order. | | Advent of Code | `AOC_STAFF_LEADERBOARD_ID` | Integer ID of the staff leaderboard. | | Advent of Code | `AOC_ROLE_ID` | ID of the advent of code role. -| Advent of Code | `AOC_IGNORED_DAYS` | Comma seperated list of days to ignore while calulating score. | +| Advent of Code | `AOC_IGNORED_DAYS` | Comma seperated list of days to ignore while calculating score. | | Advent of Code | `AOC_YEAR` | Debug variable to change the year used for AoC. | | Advent of Code | `AOC_CHANNEL_ID` | The ID of the #advent-of-code channel | | Advent of Code | `AOC_COMMANDS_CHANNEL_ID` | The ID of the #advent-of-code-commands channel | diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/site.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/site.md index df75e81a..f2c3bd95 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/site.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/site.md @@ -108,7 +108,7 @@ If you get any Docker related errors, reference the [Possible Issues](https://py ## Run on the host -Running on the host is particularily useful if you wish to debug the site. The [environment variables](#2-environment-variables) shown in a previous section need to have been configured. +Running on the host is particularly useful if you wish to debug the site. The [environment variables](#2-environment-variables) shown in a previous section need to have been configured. ### Database diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/helping-others.md b/pydis_site/apps/content/resources/guides/pydis-guides/helping-others.md index d126707d..a7f1ce1d 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/helping-others.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/helping-others.md @@ -112,7 +112,7 @@ Presenting a solution that is considered a bad practice might be useful in certa > for i in range(len(your_list)): > print(your_list[i]) > -> The second replier gave a valid solution, but it's important that he clarifies that it is concidered a bad practice in Python, and that the first solution should usually be used in this case. +> The second replier gave a valid solution, but it's important that he clarifies that it is considered a bad practice in Python, and that the first solution should usually be used in this case. ## It's OK to Step Away diff --git a/pydis_site/apps/resources/resources/tools/ides/thonny.yaml b/pydis_site/apps/resources/resources/tools/ides/thonny.yaml index 3581e1cd..d7f03a74 100644 --- a/pydis_site/apps/resources/resources/tools/ides/thonny.yaml +++ b/pydis_site/apps/resources/resources/tools/ides/thonny.yaml @@ -1,4 +1,4 @@ -description: A Python IDE specifially aimed at learning programming. Has a lot of +description: A Python IDE specifically aimed at learning programming. Has a lot of helpful features to help you understand your code. name: Thonny title_url: https://thonny.org/ -- cgit v1.2.3 From b3a5c661e179fbddb2081346aff7a77169df7676 Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Sun, 17 Oct 2021 18:46:53 +0400 Subject: Fixes Test Paths For Windows (#596) Fixes a test that fails on Windows due to differing path separators. This is currently the only failing test. Signed-off-by: Hassan Abouelela --- pydis_site/apps/content/tests/test_views.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/tests/test_views.py b/pydis_site/apps/content/tests/test_views.py index b6e752d6..eadad7e3 100644 --- a/pydis_site/apps/content/tests/test_views.py +++ b/pydis_site/apps/content/tests/test_views.py @@ -167,11 +167,16 @@ class PageOrCategoryViewTests(MockPagesTestCase, SimpleTestCase, TestCase): self.ViewClass.dispatch(request, location="category/subcategory/with_metadata") context = self.ViewClass.get_context_data() + + # Convert to paths to avoid dealing with non-standard path separators + for item in context["breadcrumb_items"]: + item["path"] = Path(item["path"]) + self.assertEquals( context["breadcrumb_items"], [ - {"name": PARSED_CATEGORY_INFO["title"], "path": "."}, - {"name": PARSED_CATEGORY_INFO["title"], "path": "category"}, - {"name": PARSED_CATEGORY_INFO["title"], "path": "category/subcategory"}, + {"name": PARSED_CATEGORY_INFO["title"], "path": Path(".")}, + {"name": PARSED_CATEGORY_INFO["title"], "path": Path("category")}, + {"name": PARSED_CATEGORY_INFO["title"], "path": Path("category/subcategory")}, ] ) -- cgit v1.2.3 From 5972560e59f98fced0c56d70039b0d0ba15532d0 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Mon, 18 Oct 2021 08:57:54 +0800 Subject: Fix typo 'fied' in apps/api/tests/test_offensive_message.py --- pydis_site/apps/api/tests/test_offensive_message.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_offensive_message.py b/pydis_site/apps/api/tests/test_offensive_message.py index 9b79b38c..3cf95b75 100644 --- a/pydis_site/apps/api/tests/test_offensive_message.py +++ b/pydis_site/apps/api/tests/test_offensive_message.py @@ -58,7 +58,7 @@ class CreationTests(AuthenticatedAPITestCase): ) for field, invalid_value in cases: - with self.subTest(fied=field, invalid_value=invalid_value): + with self.subTest(field=field, invalid_value=invalid_value): test_data = data.copy() test_data.update({field: invalid_value}) -- cgit v1.2.3 From 01db2676c43994755ab18b7609943dae8982c822 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Mon, 18 Oct 2021 09:26:29 +0800 Subject: Fix typos in contributing guides - succint -> succinct - seperated -> separated --- .../pydis-guides/contributing/sir-lancebot/env-var-reference.md | 4 ++-- .../guides/pydis-guides/contributing/working-with-git/cli.md | 2 +- .../guides/pydis-guides/contributing/working-with-git/pycharm.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md index 9ad014a2..51587aac 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot/env-var-reference.md @@ -61,10 +61,10 @@ These variables might come in handy while working on certain cogs: | Cog | Environment Variable | Description | | -------- | -------- | -------- | -| Advent of Code | `AOC_LEADERBOARDS` | List of leaderboards seperated by `::`. Each entry should have an `id,session cookie,join code` seperated by commas in that order. | +| Advent of Code | `AOC_LEADERBOARDS` | List of leaderboards separated by `::`. Each entry should have an `id,session cookie,join code` separated by commas in that order. | | Advent of Code | `AOC_STAFF_LEADERBOARD_ID` | Integer ID of the staff leaderboard. | | Advent of Code | `AOC_ROLE_ID` | ID of the advent of code role. -| Advent of Code | `AOC_IGNORED_DAYS` | Comma seperated list of days to ignore while calculating score. | +| Advent of Code | `AOC_IGNORED_DAYS` | Comma separated list of days to ignore while calculating score. | | Advent of Code | `AOC_YEAR` | Debug variable to change the year used for AoC. | | Advent of Code | `AOC_CHANNEL_ID` | The ID of the #advent-of-code channel | | Advent of Code | `AOC_COMMANDS_CHANNEL_ID` | The ID of the #advent-of-code-commands channel | diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/cli.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/cli.md index 5f196837..94f94d57 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/cli.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/cli.md @@ -27,7 +27,7 @@ If you use SSH, use `git@github.com:python-discord/sir-lancebot.git` for the ups You will be committing your changes to a new branch rather than to `main`. Using branches allows you to work on muiltiple pull requests without conflicts. -You can name your branch whatever you want, but it's recommended to name it something succint and relevant to the changes you will be making. +You can name your branch whatever you want, but it's recommended to name it something succinct and relevant to the changes you will be making. Run the following commands to create a new branch. Replace `branch_name` with the name you wish to give your branch. ```sh diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/pycharm.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/pycharm.md index 3f7fefa0..e0b2e33c 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/pycharm.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/working-with-git/pycharm.md @@ -27,7 +27,7 @@ The following will use the [Sir-Lancebot](https://github.com/python-discord/sir- ## Creating a New Branch > You will be committing your changes to a new branch rather than to `main`. Using branches allows you to work on multiple pull requests at the same time without conflicts. -> You can name your branch whatever you want, but it's recommended to name it something succint and relevant to the changes you will be making. +> You can name your branch whatever you want, but it's recommended to name it something succinct and relevant to the changes you will be making. > Before making new branches, be sure to checkout the `main` branch and ensure it's up to date. -- cgit v1.2.3 From 99de765b0fb5af4f5313cd23682d94466e1f31fd Mon Sep 17 00:00:00 2001 From: Boris Muratov <8bee278@gmail.com> Date: Sat, 23 Oct 2021 15:29:02 +0300 Subject: Correct redis config instructions in bot guide --- .../apps/content/resources/guides/pydis-guides/contributing/bot.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md index 183f1505..b9589def 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/bot.md @@ -607,7 +607,7 @@ In [Configure the Bot](#configyml) you were asked to set `bot.redis.use_fakeredi If you are working on a feature that relies on Redis, you will need to enable Redis to make sure persistency is achieved for the feature across restarts. The first step towards that is going to `config.yml` and setting `bot.redis.use_fakeredis` to `false`. #### Starting Redis in Docker (Recommended) -If you're using the Docker image provided in the project's Docker Compose, open your `config.yml` file, set `bot.redis.host` to `redis`, and `bot.redis.password` to `null`. +If you're using the Docker image provided in the project's Docker Compose, open your `config.yml` file. If you're running the bot in Docker, set `bot.redis.host` to `redis`, and if you're running it on the host set it to `localhost`. Set `bot.redis.password` to `null`. #### Starting Redis Using Other Methods You can run your own instance of Redis, but in that case you will need to correctly set `bot.redis.host` and `bot.redis.port`, and the `bot.redis.password` value in `config-default.yml` should not be overridden. Then, enter the `.env` file, and set `REDIS_PASSWORD` to whatever password you set. -- cgit v1.2.3 From 367c01a7b3cd5cc5ee25644ae92f917ceb00562c Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Fri, 29 Oct 2021 03:19:37 +0400 Subject: Adds Failures Field To Reminders Adds an integer field to reminders, to keep track of how many failed attempts at delivering the reminder were made. Updates documentation and serialization. Signed-off-by: Hassan Abouelela --- .../apps/api/migrations/0074_reminder_failures.py | 18 ++++++++++++++++++ pydis_site/apps/api/models/bot/reminder.py | 4 ++++ pydis_site/apps/api/serializers.py | 10 +++++++++- pydis_site/apps/api/viewsets/bot/reminder.py | 13 ++++++++----- 4 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 pydis_site/apps/api/migrations/0074_reminder_failures.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0074_reminder_failures.py b/pydis_site/apps/api/migrations/0074_reminder_failures.py new file mode 100644 index 00000000..2860046e --- /dev/null +++ b/pydis_site/apps/api/migrations/0074_reminder_failures.py @@ -0,0 +1,18 @@ +# Generated by Django 3.0.14 on 2021-10-27 17:44 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0073_otn_allow_GT_and_LT'), + ] + + operations = [ + migrations.AddField( + model_name='reminder', + name='failures', + field=models.IntegerField(default=0, help_text='Number of times we attempted to send the reminder and failed.'), + ), + ] diff --git a/pydis_site/apps/api/models/bot/reminder.py b/pydis_site/apps/api/models/bot/reminder.py index 7d968a0e..173900ee 100644 --- a/pydis_site/apps/api/models/bot/reminder.py +++ b/pydis_site/apps/api/models/bot/reminder.py @@ -59,6 +59,10 @@ class Reminder(ModelReprMixin, models.Model): blank=True, help_text="IDs of roles or users to ping with the reminder." ) + failures = models.IntegerField( + default=0, + help_text="Number of times we attempted to send the reminder and failed." + ) def __str__(self): """Returns some info on the current reminder, for display purposes.""" diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index f47bedca..3e213d43 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -231,7 +231,15 @@ class ReminderSerializer(ModelSerializer): model = Reminder fields = ( - 'active', 'author', 'jump_url', 'channel_id', 'content', 'expiration', 'id', 'mentions' + 'active', + 'author', + 'jump_url', + 'channel_id', + 'content', + 'expiration', + 'id', + 'mentions', + 'failures' ) diff --git a/pydis_site/apps/api/viewsets/bot/reminder.py b/pydis_site/apps/api/viewsets/bot/reminder.py index 111660d9..78d7cb3b 100644 --- a/pydis_site/apps/api/viewsets/bot/reminder.py +++ b/pydis_site/apps/api/viewsets/bot/reminder.py @@ -42,7 +42,8 @@ class ReminderViewSet( ... 'expiration': '5018-11-20T15:52:00Z', ... 'id': 11, ... 'channel_id': 634547009956872193, - ... 'jump_url': "https://discord.com/channels///" + ... 'jump_url': "https://discord.com/channels///", + ... 'failures': 3 ... }, ... ... ... ] @@ -67,7 +68,8 @@ class ReminderViewSet( ... 'expiration': '5018-11-20T15:52:00Z', ... 'id': 11, ... 'channel_id': 634547009956872193, - ... 'jump_url': "https://discord.com/channels///" + ... 'jump_url': "https://discord.com/channels///", + ... 'failures': 3 ... } #### Status codes @@ -80,7 +82,7 @@ class ReminderViewSet( #### Request body >>> { ... 'author': int, - ... 'mentions': List[int], + ... 'mentions': list[int], ... 'content': str, ... 'expiration': str, # ISO-formatted datetime ... 'channel_id': int, @@ -98,9 +100,10 @@ class ReminderViewSet( #### Request body >>> { - ... 'mentions': List[int], + ... 'mentions': list[int], ... 'content': str, - ... 'expiration': str # ISO-formatted datetime + ... 'expiration': str, # ISO-formatted datetime + ... 'failures': int ... } #### Status codes -- cgit v1.2.3 From e981db620f9f7ee05d4f42ad8b4ebb4fcff57f14 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Thu, 4 Nov 2021 13:04:46 +0800 Subject: Improve Gitpod section in Sir Lancebot contributing guide - Add newlines so it's not a big unfriendly paragraph - Fix gitpod workspace link - Clarification on terminal commands - Clarification on test server and bot - Add links for that ^ and for environment variables --- .../resources/guides/pydis-guides/contributing/sir-lancebot.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md index a0d3d463..53674063 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md @@ -18,12 +18,17 @@ toc: 1 ## Using Gitpod Sir Lancebot can be edited and tested on Gitpod. Gitpod will automatically install the correct dependencies and Python version, so you can get straight to coding. -To do this, you will need a Gitpod account, which you can get [here](https://www.gitpod.io/#get-started), and a fork of Sir Lancebot. This guide covers forking the repository [here](#fork-the-project). Afterwards, either click the button on Sir Lancebot's README or go to [https://gitpod.io/#/python-discord/sir-lancebot]() and run the following commands in the terminal: + +To do this, you will need a Gitpod account, which you can get [here](https://www.gitpod.io/#get-started), and a fork of Sir Lancebot. This guide covers forking the repository [here](#fork-the-project). + +Afterwards, click on this link: [https://gitpod.io/#/python-discord/sir-lancebot](https://gitpod.io/#/python-discord/sir-lancebot) to spin up a new workspace for Sir Lancebot. Then run the following commands in the terminal after the existing tasks have finished running: ```sh git remote rename origin upstream git add remote origin https://github.com/{your_username}/sir-lancebot ``` -Make sure you replace `{your_username}` with your Github username. These commands will set Python Discord as the parent repository, and your branch as the fork. This means you can easily grab new changes from the parent repository. Once you set your environment variables to test your code, you are ready to begin contributing to Sir Lancebot. +Make sure you replace `{your_username}` with your Github username. These commands will set the Sir Lancebot repository as the secondary remote, and your fork as the primary remote. This means you can easily grab new changes from the main Sir Lancebot repository. + +Once you've set up [a test server and bot account](#test-server-and-bot-account) and your [environment variables](#environment-variables), you are ready to begin contributing to Sir Lancebot! ## Using Docker Sir Lancebot can be started using Docker. Using Docker is generally recommended (but not strictly required) because it abstracts away some additional set up work. -- cgit v1.2.3 From 8faaddceb37cd71d9c11ec827a71b3b67521fbe0 Mon Sep 17 00:00:00 2001 From: Hedy Li Date: Thu, 4 Nov 2021 13:18:38 +0800 Subject: Fix gitpod link in Sir Lancebot contributing guide --- .../content/resources/guides/pydis-guides/contributing/sir-lancebot.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md index 53674063..e3cd8f0c 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/sir-lancebot.md @@ -21,7 +21,7 @@ Sir Lancebot can be edited and tested on Gitpod. Gitpod will automatically insta To do this, you will need a Gitpod account, which you can get [here](https://www.gitpod.io/#get-started), and a fork of Sir Lancebot. This guide covers forking the repository [here](#fork-the-project). -Afterwards, click on this link: [https://gitpod.io/#/python-discord/sir-lancebot](https://gitpod.io/#/python-discord/sir-lancebot) to spin up a new workspace for Sir Lancebot. Then run the following commands in the terminal after the existing tasks have finished running: +Afterwards, click on [this link](https://gitpod.io/#/github.com/python-discord/sir-lancebot) to spin up a new workspace for Sir Lancebot. Then run the following commands in the terminal after the existing tasks have finished running: ```sh git remote rename origin upstream git add remote origin https://github.com/{your_username}/sir-lancebot -- cgit v1.2.3 From 2b95db672e649d9fc1159b3e2211dcb72560d8f6 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Fri, 5 Nov 2021 10:49:30 +0530 Subject: Fix: Conflicting migrations. --- pydis_site/apps/api/migrations/0074_merge_20211105_0518.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 pydis_site/apps/api/migrations/0074_merge_20211105_0518.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0074_merge_20211105_0518.py b/pydis_site/apps/api/migrations/0074_merge_20211105_0518.py new file mode 100644 index 00000000..ebf5ae15 --- /dev/null +++ b/pydis_site/apps/api/migrations/0074_merge_20211105_0518.py @@ -0,0 +1,14 @@ +# Generated by Django 3.0.14 on 2021-11-05 05:18 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0072_merge_20210724_1354'), + ('api', '0073_otn_allow_GT_and_LT'), + ] + + operations = [ + ] -- cgit v1.2.3 From 876daaf6eb34e620710473c0311e23f36fd4e7eb Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Fri, 5 Nov 2021 10:55:09 +0530 Subject: Update test cases to adhere to recent changes made that removed hosts. --- pydis_site/apps/api/tests/test_off_topic_channel_names.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_off_topic_channel_names.py b/pydis_site/apps/api/tests/test_off_topic_channel_names.py index 354cda9c..2d273756 100644 --- a/pydis_site/apps/api/tests/test_off_topic_channel_names.py +++ b/pydis_site/apps/api/tests/test_off_topic_channel_names.py @@ -112,7 +112,7 @@ class ListTests(AuthenticatedAPITestCase): def test_returns_inactive_ot_names(self): """Return inactive off topic names.""" - url = reverse('bot:offtopicchannelname-list') + url = reverse('api:bot:offtopicchannelname-list') response = self.client.get(f"{url}?active=false") self.assertEqual(response.status_code, 200) @@ -123,7 +123,7 @@ class ListTests(AuthenticatedAPITestCase): def test_returns_active_ot_names(self): """Return active off topic names.""" - url = reverse('bot:offtopicchannelname-list') + url = reverse('api:bot:offtopicchannelname-list') response = self.client.get(f"{url}?active=true") self.assertEqual(response.status_code, 200) -- cgit v1.2.3 From 41ec1fd7e3d5bd7b0c16a32b5977d46ce5b3e89e Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Fri, 5 Nov 2021 10:56:01 +0530 Subject: Eliminate usage of typing module and update docstrings. --- pydis_site/apps/api/serializers.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index 957c85f3..9b351be2 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -1,6 +1,4 @@ """Converters from Django models to data interchange formats and back.""" -from typing import List - from django.db.models.query import QuerySet from django.db.utils import IntegrityError from rest_framework.exceptions import NotFound @@ -205,12 +203,12 @@ class ExpandedInfractionSerializer(InfractionSerializer): class OffTopicChannelNameListSerializer(ListSerializer): """Custom ListSerializer to override to_representation() when list views are triggered.""" - def to_representation(self, objects: List[OffTopicChannelName]) -> List[str]: + def to_representation(self, objects: list[OffTopicChannelName]) -> list[str]: """ - Return a list representing a list of `OffTopicChannelName`. + Return a list with all `OffTopicChannelName`s in the database. - This only returns the name of the off topic channel name. As the model - only has a single attribute, it is unnecessary to create a nested dictionary. + This returns the list of off topic channel names. We want to only return + the name attribute, hence it is unnecessary to create a nested dictionary. Additionally, this allows off topic channel name routes to simply return an array of names instead of objects, saving on bandwidth. """ -- cgit v1.2.3 From 6e1d38d6ceb97f287f0d347e974bc795dda38ffe Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Fri, 5 Nov 2021 10:56:34 +0530 Subject: Use framework defination of method. --- pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py index 7151d29b..27eabec9 100644 --- a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py @@ -70,7 +70,7 @@ class OffTopicChannelNameViewSet(ModelViewSet): def get_queryset(self, **kwargs) -> QuerySet: """Returns a queryset that covers the entire OffTopicChannelName table.""" - return OffTopicChannelName.objects.filter(**kwargs) + return OffTopicChannelName.objects.all() def create(self, request: Request, *args, **kwargs) -> Response: """ @@ -137,6 +137,6 @@ class OffTopicChannelNameViewSet(ModelViewSet): if active_param := request.query_params.get("active"): params["active"] = active_param.lower() == "true" - queryset = self.get_queryset(**params) + queryset = self.get_queryset().filter(**params) serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) -- cgit v1.2.3 From 4377c6d960e3fbf3a416230d1ad7de972019898e Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Sat, 6 Nov 2021 14:43:17 +0530 Subject: Remove get_queryset() and add new class variable . --- pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py index 27eabec9..78f8c340 100644 --- a/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py +++ b/pydis_site/apps/api/viewsets/bot/off_topic_channel_name.py @@ -57,6 +57,7 @@ class OffTopicChannelNameViewSet(ModelViewSet): lookup_field = 'name' serializer_class = OffTopicChannelNameSerializer + queryset = OffTopicChannelName.objects.all() def get_object(self) -> OffTopicChannelName: """ @@ -64,11 +65,10 @@ class OffTopicChannelNameViewSet(ModelViewSet): If it doesn't, a HTTP 404 is returned by way of throwing an exception. """ - queryset = self.get_queryset() name = self.kwargs[self.lookup_field] - return get_object_or_404(queryset, name=name) + return get_object_or_404(self.queryset, name=name) - def get_queryset(self, **kwargs) -> QuerySet: + def get_queryset(self) -> QuerySet: """Returns a queryset that covers the entire OffTopicChannelName table.""" return OffTopicChannelName.objects.all() @@ -108,13 +108,13 @@ class OffTopicChannelNameViewSet(ModelViewSet): 'random_items': ["Must be a positive integer."] }) - queryset = self.get_queryset().order_by('used', '?')[:random_count] + queryset = self.queryset.order_by('used', '?')[:random_count] # When any name is used in our listing then this means we reached end of round # and we need to reset all other names `used` to False if any(offtopic_name.used for offtopic_name in queryset): # These names that we just got have to be excluded from updating used to False - self.get_queryset().update( + self.queryset.update( used=Case( When( name__in=(offtopic_name.name for offtopic_name in queryset), @@ -125,7 +125,7 @@ class OffTopicChannelNameViewSet(ModelViewSet): ) else: # Otherwise mark selected names `used` to True - self.get_queryset().filter( + self.queryset.filter( name__in=(offtopic_name.name for offtopic_name in queryset) ).update(used=True) @@ -137,6 +137,6 @@ class OffTopicChannelNameViewSet(ModelViewSet): if active_param := request.query_params.get("active"): params["active"] = active_param.lower() == "true" - queryset = self.get_queryset().filter(**params) + queryset = self.queryset.filter(**params) serialized = self.serializer_class(queryset, many=True) return Response(serialized.data) -- cgit v1.2.3 From 7353e1ed7003a1198fb00a1e40251b95cf2fdf7e Mon Sep 17 00:00:00 2001 From: Hassan Abouelela Date: Wed, 17 Nov 2021 14:27:45 +0400 Subject: Adds Redirect Filter List Adds a new filter list for URLs which should be treated as redirects and unfurled. Signed-off-by: Hassan Abouelela --- .../apps/api/migrations/0075_add_redirects_filter.py | 18 ++++++++++++++++++ pydis_site/apps/api/models/bot/filter_list.py | 1 + pydis_site/apps/api/viewsets/bot/filter_list.py | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 pydis_site/apps/api/migrations/0075_add_redirects_filter.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0075_add_redirects_filter.py b/pydis_site/apps/api/migrations/0075_add_redirects_filter.py new file mode 100644 index 00000000..23dc176f --- /dev/null +++ b/pydis_site/apps/api/migrations/0075_add_redirects_filter.py @@ -0,0 +1,18 @@ +# Generated by Django 3.0.14 on 2021-11-17 10:24 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0074_reminder_failures'), + ] + + operations = [ + migrations.AlterField( + model_name='filterlist', + name='type', + field=models.CharField(choices=[('GUILD_INVITE', 'Guild Invite'), ('FILE_FORMAT', 'File Format'), ('DOMAIN_NAME', 'Domain Name'), ('FILTER_TOKEN', 'Filter Token'), ('REDIRECT', 'Redirect')], help_text='The type of allowlist this is on.', max_length=50), + ), + ] diff --git a/pydis_site/apps/api/models/bot/filter_list.py b/pydis_site/apps/api/models/bot/filter_list.py index d279e137..d30f7213 100644 --- a/pydis_site/apps/api/models/bot/filter_list.py +++ b/pydis_site/apps/api/models/bot/filter_list.py @@ -12,6 +12,7 @@ class FilterList(ModelTimestampMixin, ModelReprMixin, models.Model): 'FILE_FORMAT ' 'DOMAIN_NAME ' 'FILTER_TOKEN ' + 'REDIRECT ' ) type = models.CharField( max_length=50, diff --git a/pydis_site/apps/api/viewsets/bot/filter_list.py b/pydis_site/apps/api/viewsets/bot/filter_list.py index 2cb21ab9..4b05acee 100644 --- a/pydis_site/apps/api/viewsets/bot/filter_list.py +++ b/pydis_site/apps/api/viewsets/bot/filter_list.py @@ -59,7 +59,8 @@ class FilterListViewSet(ModelViewSet): ... ["GUILD_INVITE","Guild Invite"], ... ["FILE_FORMAT","File Format"], ... ["DOMAIN_NAME","Domain Name"], - ... ["FILTER_TOKEN","Filter Token"] + ... ["FILTER_TOKEN","Filter Token"], + ... ["REDIRECT", "Redirect"] ... ] #### Status codes -- cgit v1.2.3 From 855bf5e7c7e54e9f8e4544545026c47092b52a11 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Mon, 22 Nov 2021 20:36:21 +0000 Subject: Only calc activity blocks when <1k messages We only truly care about how many activity blocks a user has when they have a small number of messages, as we only use this for the voice gate. If a user has more than say 1k messages, then we really don't need to calculate their activity blocks, as it's quite an expensive query with many messages. --- pydis_site/apps/api/viewsets/bot/user.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/user.py b/pydis_site/apps/api/viewsets/bot/user.py index 22d13dc4..ed661323 100644 --- a/pydis_site/apps/api/viewsets/bot/user.py +++ b/pydis_site/apps/api/viewsets/bot/user.py @@ -271,9 +271,15 @@ class UserViewSet(ModelViewSet): with Metricity() as metricity: try: data = metricity.user(user.id) + data["total_messages"] = metricity.total_messages(user.id) + if data["total_messages"] < 1000: + # Only calculate and return activity_blocks if the user has a small amount + # of messages, as calculating activity_blocks is expensive. + # 1000 message chosen as an arbitrarily large number. + data["activity_blocks"] = metricity.total_message_blocks(user.id) + data["voice_banned"] = voice_banned - data["activity_blocks"] = metricity.total_message_blocks(user.id) return Response(data, status=status.HTTP_200_OK) except NotFoundError: return Response(dict(detail="User not found in metricity"), -- cgit v1.2.3 From c8d1513b8f8cb21482180ce19d69a107adefe4e2 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Mon, 22 Nov 2021 20:38:41 +0000 Subject: Make metricity test order insensitive We only actually care that thee key:value pairs are equal, the order of them isn't actually important. The naming of `assertCountEqual` is a little misleading, since it actually tests that the first sequence contains the same elements as second, regardless of their order. See https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertCountEqual --- pydis_site/apps/api/tests/test_users.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_users.py b/pydis_site/apps/api/tests/test_users.py index 295bcf64..550c7240 100644 --- a/pydis_site/apps/api/tests/test_users.py +++ b/pydis_site/apps/api/tests/test_users.py @@ -408,7 +408,7 @@ class UserMetricityTests(AuthenticatedAPITestCase): in_guild=True, ) - def test_get_metricity_data(self): + def test_get_metricity_data_under_1k(self): # Given joined_at = "foo" total_messages = 1 @@ -421,7 +421,7 @@ class UserMetricityTests(AuthenticatedAPITestCase): # Then self.assertEqual(response.status_code, 200) - self.assertEqual(response.json(), { + self.assertCountEqual(response.json(), { "joined_at": joined_at, "total_messages": total_messages, "voice_banned": False, -- cgit v1.2.3 From 78b2f3b8ed46d23015ab2f765504572f672f4567 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Mon, 22 Nov 2021 20:38:58 +0000 Subject: Add metricity test for users >1k messages --- pydis_site/apps/api/tests/test_users.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_users.py b/pydis_site/apps/api/tests/test_users.py index 550c7240..81bfd43b 100644 --- a/pydis_site/apps/api/tests/test_users.py +++ b/pydis_site/apps/api/tests/test_users.py @@ -428,6 +428,25 @@ class UserMetricityTests(AuthenticatedAPITestCase): "activity_blocks": total_blocks }) + def test_get_metricity_data_over_1k(self): + # Given + joined_at = "foo" + total_messages = 1001 + total_blocks = 1001 + self.mock_metricity_user(joined_at, total_messages, total_blocks, []) + + # When + url = reverse('api:bot:user-metricity-data', args=[0]) + response = self.client.get(url) + + # Then + self.assertEqual(response.status_code, 200) + self.assertCountEqual(response.json(), { + "joined_at": joined_at, + "total_messages": total_messages, + "voice_banned": False, + }) + def test_no_metricity_user(self): # Given self.mock_no_metricity_user() -- cgit v1.2.3 From 5b1bb82165d188a571c8999f17ef52f3856c9518 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Tue, 23 Nov 2021 16:29:06 +0000 Subject: Alter message query to leverage index Previously this query would convert each row to an array just to check if it matched or not. By changing EXCLUDE_CHANNELS to a tuple instead of a list, it doesn't get passed as an array, so we can do a simple NOT IN check. This will also allow us to add an index with this condition to speed it up further. --- pydis_site/apps/api/models/bot/metricity.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/models/bot/metricity.py b/pydis_site/apps/api/models/bot/metricity.py index 33fb7ad7..901f191a 100644 --- a/pydis_site/apps/api/models/bot/metricity.py +++ b/pydis_site/apps/api/models/bot/metricity.py @@ -4,10 +4,10 @@ from django.db import connections BLOCK_INTERVAL = 10 * 60 # 10 minute blocks -EXCLUDE_CHANNELS = [ +EXCLUDE_CHANNELS = ( "267659945086812160", # Bot commands "607247579608121354" # SeasonalBot commands -] +) class NotFoundError(Exception): @@ -46,12 +46,12 @@ class Metricity: self.cursor.execute( """ SELECT - COUNT(*) + COUNT(*) FROM messages WHERE - author_id = '%s' - AND NOT is_deleted - AND NOT %s::varchar[] @> ARRAY[channel_id] + author_id = '%s' + AND NOT is_deleted + AND channel_id NOT IN %s """, [user_id, EXCLUDE_CHANNELS] ) @@ -79,7 +79,7 @@ class Metricity: WHERE author_id='%s' AND NOT is_deleted - AND NOT %s::varchar[] @> ARRAY[channel_id] + AND channel_id NOT IN %s GROUP BY interval ) block_query; """, -- cgit v1.2.3 From 61f9daed8d71046351e60c57ccdbf34443085561 Mon Sep 17 00:00:00 2001 From: Izan Date: Wed, 10 Nov 2021 22:44:20 +0000 Subject: Add `dm_sent` field to infractions model & serializer --- .../apps/api/migrations/0075_infraction_dm_sent.py | 18 ++++++++++++++++++ pydis_site/apps/api/models/bot/infraction.py | 4 ++++ pydis_site/apps/api/serializers.py | 2 +- 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 pydis_site/apps/api/migrations/0075_infraction_dm_sent.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0075_infraction_dm_sent.py b/pydis_site/apps/api/migrations/0075_infraction_dm_sent.py new file mode 100644 index 00000000..c0ac709d --- /dev/null +++ b/pydis_site/apps/api/migrations/0075_infraction_dm_sent.py @@ -0,0 +1,18 @@ +# Generated by Django 3.0.14 on 2021-11-10 22:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0074_reminder_failures'), + ] + + operations = [ + migrations.AddField( + model_name='infraction', + name='dm_sent', + field=models.BooleanField(help_text='Whether a DM was sent to the user when infraction was applied.', null=True), + ), + ] diff --git a/pydis_site/apps/api/models/bot/infraction.py b/pydis_site/apps/api/models/bot/infraction.py index 60c1e8dd..913631d4 100644 --- a/pydis_site/apps/api/models/bot/infraction.py +++ b/pydis_site/apps/api/models/bot/infraction.py @@ -57,6 +57,10 @@ class Infraction(ModelReprMixin, models.Model): default=False, help_text="Whether the infraction is a shadow infraction." ) + dm_sent = models.BooleanField( + null=True, + help_text="Whether a DM was sent to the user when infraction was applied." + ) def __str__(self): """Returns some info on the current infraction, for display purposes.""" diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index 3e213d43..f6801597 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -145,7 +145,7 @@ class InfractionSerializer(ModelSerializer): model = Infraction fields = ( - 'id', 'inserted_at', 'expires_at', 'active', 'user', 'actor', 'type', 'reason', 'hidden' + 'id', 'inserted_at', 'expires_at', 'active', 'user', 'actor', 'type', 'reason', 'hidden', 'dm_sent' ) validators = [ UniqueTogetherValidator( -- cgit v1.2.3 From 1e3725d8f6ef1a601c12054db3d913e447b51866 Mon Sep 17 00:00:00 2001 From: Izan Date: Fri, 12 Nov 2021 14:31:52 +0000 Subject: Update documentation to include `dm_sent` field --- pydis_site/apps/api/viewsets/bot/infraction.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/viewsets/bot/infraction.py b/pydis_site/apps/api/viewsets/bot/infraction.py index f8b0cb9d..8a48ed1f 100644 --- a/pydis_site/apps/api/viewsets/bot/infraction.py +++ b/pydis_site/apps/api/viewsets/bot/infraction.py @@ -70,7 +70,8 @@ class InfractionViewSet( ... 'actor': 125435062127820800, ... 'type': 'ban', ... 'reason': 'He terk my jerb!', - ... 'hidden': True + ... 'hidden': True, + ... 'dm_sent': True ... } ... ] @@ -100,7 +101,8 @@ class InfractionViewSet( ... 'hidden': True, ... 'type': 'ban', ... 'reason': 'He terk my jerb!', - ... 'user': 172395097705414656 + ... 'user': 172395097705414656, + ... 'dm_sent': False ... } #### Response format @@ -118,7 +120,8 @@ class InfractionViewSet( >>> { ... 'active': True, ... 'expires_at': '4143-02-15T21:04:31+00:00', - ... 'reason': 'durka derr' + ... 'reason': 'durka derr', + ... 'dm_sent': True ... } #### Response format -- cgit v1.2.3 From 546a2d18bb52a0b4f1fc31de765119623a97f7fa Mon Sep 17 00:00:00 2001 From: Izan Date: Thu, 25 Nov 2021 10:44:06 +0000 Subject: Fix linting --- pydis_site/apps/api/serializers.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/serializers.py b/pydis_site/apps/api/serializers.py index f6801597..de2fccff 100644 --- a/pydis_site/apps/api/serializers.py +++ b/pydis_site/apps/api/serializers.py @@ -145,7 +145,16 @@ class InfractionSerializer(ModelSerializer): model = Infraction fields = ( - 'id', 'inserted_at', 'expires_at', 'active', 'user', 'actor', 'type', 'reason', 'hidden', 'dm_sent' + 'id', + 'inserted_at', + 'expires_at', + 'active', + 'user', + 'actor', + 'type', + 'reason', + 'hidden', + 'dm_sent' ) validators = [ UniqueTogetherValidator( -- cgit v1.2.3 From 454ad492229253ae675f4ba956c74edf32f41c2a Mon Sep 17 00:00:00 2001 From: Johannes Christ Date: Thu, 25 Nov 2021 20:41:16 +0100 Subject: Merge migrations with upstream --- pydis_site/apps/api/migrations/0076_merge_20211125_1941.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 pydis_site/apps/api/migrations/0076_merge_20211125_1941.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0076_merge_20211125_1941.py b/pydis_site/apps/api/migrations/0076_merge_20211125_1941.py new file mode 100644 index 00000000..097d0a0c --- /dev/null +++ b/pydis_site/apps/api/migrations/0076_merge_20211125_1941.py @@ -0,0 +1,14 @@ +# Generated by Django 3.0.14 on 2021-11-25 19:41 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0075_infraction_dm_sent'), + ('api', '0075_add_redirects_filter'), + ] + + operations = [ + ] -- cgit v1.2.3 From f093907393b4f479f62409286831b938ba65c558 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Tue, 31 Aug 2021 16:27:18 +0200 Subject: Create a signal to unassign roles from user when deleted Add a signal to the api app that automatically unassigns deleted roles from users that have them --- pydis_site/apps/api/__init__.py | 1 + pydis_site/apps/api/apps.py | 10 +++++++++- pydis_site/apps/api/signals.py | 12 ++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 pydis_site/apps/api/signals.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/__init__.py b/pydis_site/apps/api/__init__.py index e69de29b..afa5b4d5 100644 --- a/pydis_site/apps/api/__init__.py +++ b/pydis_site/apps/api/__init__.py @@ -0,0 +1 @@ +default_app_config = 'pydis_site.apps.api.apps.ApiConfig' diff --git a/pydis_site/apps/api/apps.py b/pydis_site/apps/api/apps.py index 76810b2e..18eda9e3 100644 --- a/pydis_site/apps/api/apps.py +++ b/pydis_site/apps/api/apps.py @@ -4,4 +4,12 @@ from django.apps import AppConfig class ApiConfig(AppConfig): """Django AppConfig for the API app.""" - name = 'api' + name = 'pydis_site.apps.api' + + def ready(self) -> None: + """ + Gets called as soon as the registry is fully populated. + + https://docs.djangoproject.com/en/3.2/ref/applications/#django.apps.AppConfig.ready + """ + import pydis_site.apps.api.signals # noqa: F401 diff --git a/pydis_site/apps/api/signals.py b/pydis_site/apps/api/signals.py new file mode 100644 index 00000000..c69704b1 --- /dev/null +++ b/pydis_site/apps/api/signals.py @@ -0,0 +1,12 @@ +from django.db.models.signals import pre_delete +from django.dispatch import receiver + +from pydis_site.apps.api.models.bot import Role, User + + +@receiver(signal=pre_delete, sender=Role) +def delete_role_from_user(sender: Role, instance: Role, **kwargs) -> None: + """Unassigns the Role (instance) that is being deleted from every user that has it.""" + for user in User.objects.filter(roles__contains=[instance.id]): + del user.roles[user.roles.index(instance.id)] + user.save() -- cgit v1.2.3 From 0f24bdcd0ba261da045ac73e8567239eb63c6fc6 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Tue, 31 Aug 2021 17:54:39 +0200 Subject: Add test to check role unassignment Create a test that checks if a role gets deleted it will also get unassigned from the user --- pydis_site/apps/api/tests/test_roles.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_roles.py b/pydis_site/apps/api/tests/test_roles.py index d39cea4d..7c968852 100644 --- a/pydis_site/apps/api/tests/test_roles.py +++ b/pydis_site/apps/api/tests/test_roles.py @@ -1,7 +1,8 @@ from django.urls import reverse from .base import AuthenticatedAPITestCase -from ..models import Role +from ..models import Role, User + class CreationTests(AuthenticatedAPITestCase): @@ -35,6 +36,20 @@ class CreationTests(AuthenticatedAPITestCase): permissions=6, position=0, ) + cls.role_to_delete = Role.objects.create( + id=7, + name="role to delete", + colour=7, + permissions=7, + position=0, + ) + cls.role_unassigned_test_user = User.objects.create( + id=8, + name="role_unassigned_test_user", + discriminator="0000", + roles=[cls.role_to_delete.id], + in_guild=True + ) def _validate_roledict(self, role_dict: dict) -> None: """Helper method to validate a dict representing a role.""" @@ -181,6 +196,11 @@ class CreationTests(AuthenticatedAPITestCase): response = self.client.delete(url) self.assertEqual(response.status_code, 204) + def test_role_delete_unassigned(self): + """Tests if the deleted Role gets unassigned from the user.""" + self.role_to_delete.delete() + self.assertEqual(self.role_unassigned_test_user.roles, []) + def test_role_detail_404_all_methods(self): """Tests detail view with non-existing ID.""" url = reverse('api:bot:role-detail', args=(20190815,)) -- cgit v1.2.3 From 9d255dcf3daafde71071ad75b000077a861da659 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Tue, 31 Aug 2021 18:49:21 +0200 Subject: Patch roles test to use fresh instance from the DB --- pydis_site/apps/api/tests/test_roles.py | 1 + 1 file changed, 1 insertion(+) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_roles.py b/pydis_site/apps/api/tests/test_roles.py index 7c968852..88c0256b 100644 --- a/pydis_site/apps/api/tests/test_roles.py +++ b/pydis_site/apps/api/tests/test_roles.py @@ -199,6 +199,7 @@ class CreationTests(AuthenticatedAPITestCase): def test_role_delete_unassigned(self): """Tests if the deleted Role gets unassigned from the user.""" self.role_to_delete.delete() + self.role_unassigned_test_user.refresh_from_db() self.assertEqual(self.role_unassigned_test_user.roles, []) def test_role_detail_404_all_methods(self): -- cgit v1.2.3 From f34a52016bd5a7d50c1146d6fbd213ce889f58c7 Mon Sep 17 00:00:00 2001 From: D0rs4n <41237606+D0rs4n@users.noreply.github.com> Date: Tue, 31 Aug 2021 19:21:36 +0200 Subject: Patch signals to use post_delete, instead of pre_delete From now on the signal will only get executed after the Role has been deleted The commit also introduces minor changes in the tests of roles --- pydis_site/apps/api/signals.py | 4 ++-- pydis_site/apps/api/tests/test_roles.py | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/signals.py b/pydis_site/apps/api/signals.py index c69704b1..5c26bfb6 100644 --- a/pydis_site/apps/api/signals.py +++ b/pydis_site/apps/api/signals.py @@ -1,10 +1,10 @@ -from django.db.models.signals import pre_delete +from django.db.models.signals import post_delete from django.dispatch import receiver from pydis_site.apps.api.models.bot import Role, User -@receiver(signal=pre_delete, sender=Role) +@receiver(signal=post_delete, sender=Role) def delete_role_from_user(sender: Role, instance: Role, **kwargs) -> None: """Unassigns the Role (instance) that is being deleted from every user that has it.""" for user in User.objects.filter(roles__contains=[instance.id]): diff --git a/pydis_site/apps/api/tests/test_roles.py b/pydis_site/apps/api/tests/test_roles.py index 88c0256b..73c80c77 100644 --- a/pydis_site/apps/api/tests/test_roles.py +++ b/pydis_site/apps/api/tests/test_roles.py @@ -4,7 +4,6 @@ from .base import AuthenticatedAPITestCase from ..models import Role, User - class CreationTests(AuthenticatedAPITestCase): @classmethod def setUpTestData(cls): @@ -96,11 +95,11 @@ class CreationTests(AuthenticatedAPITestCase): url = reverse('api:bot:role-list') response = self.client.get(url) - self.assertContains(response, text="id", count=4, status_code=200) + self.assertContains(response, text="id", count=5, status_code=200) roles = response.json() self.assertIsInstance(roles, list) - self.assertEqual(len(roles), 4) + self.assertEqual(len(roles), 5) for role in roles: self._validate_roledict(role) -- cgit v1.2.3 From 3f4adf3768123c870f9da38a23b189862a7b9502 Mon Sep 17 00:00:00 2001 From: Johannes Christ Date: Sat, 27 Nov 2021 13:28:23 +0100 Subject: Migrate to generic `JSONField` --- .../api/migrations/0077_use_generic_jsonfield.py | 25 ++++++++++++++++++++++ pydis_site/apps/api/models/bot/bot_setting.py | 3 +-- pydis_site/apps/api/models/bot/message.py | 2 +- pydis_site/apps/api/models/utils.py | 3 +-- 4 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 pydis_site/apps/api/migrations/0077_use_generic_jsonfield.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0077_use_generic_jsonfield.py b/pydis_site/apps/api/migrations/0077_use_generic_jsonfield.py new file mode 100644 index 00000000..9e8f2fb9 --- /dev/null +++ b/pydis_site/apps/api/migrations/0077_use_generic_jsonfield.py @@ -0,0 +1,25 @@ +# Generated by Django 3.1.13 on 2021-11-27 12:27 + +import django.contrib.postgres.fields +from django.db import migrations, models +import pydis_site.apps.api.models.utils + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0076_merge_20211125_1941'), + ] + + operations = [ + migrations.AlterField( + model_name='botsetting', + name='data', + field=models.JSONField(help_text='The actual settings of this setting.'), + ), + migrations.AlterField( + model_name='deletedmessage', + name='embeds', + field=django.contrib.postgres.fields.ArrayField(base_field=models.JSONField(validators=[pydis_site.apps.api.models.utils.validate_embed]), blank=True, help_text='Embeds attached to this message.', size=None), + ), + ] diff --git a/pydis_site/apps/api/models/bot/bot_setting.py b/pydis_site/apps/api/models/bot/bot_setting.py index 2a3944f8..1bcb1ae6 100644 --- a/pydis_site/apps/api/models/bot/bot_setting.py +++ b/pydis_site/apps/api/models/bot/bot_setting.py @@ -1,4 +1,3 @@ -from django.contrib.postgres import fields as pgfields from django.core.exceptions import ValidationError from django.db import models @@ -24,6 +23,6 @@ class BotSetting(ModelReprMixin, models.Model): max_length=50, validators=(validate_bot_setting_name,) ) - data = pgfields.JSONField( + data = models.JSONField( help_text="The actual settings of this setting." ) diff --git a/pydis_site/apps/api/models/bot/message.py b/pydis_site/apps/api/models/bot/message.py index 60e2a553..bab3368d 100644 --- a/pydis_site/apps/api/models/bot/message.py +++ b/pydis_site/apps/api/models/bot/message.py @@ -48,7 +48,7 @@ class Message(ModelReprMixin, models.Model): blank=True ) embeds = pgfields.ArrayField( - pgfields.JSONField( + models.JSONField( validators=(validate_embed,) ), blank=True, diff --git a/pydis_site/apps/api/models/utils.py b/pydis_site/apps/api/models/utils.py index 0e220a1d..859394d2 100644 --- a/pydis_site/apps/api/models/utils.py +++ b/pydis_site/apps/api/models/utils.py @@ -103,11 +103,10 @@ def validate_embed(embed: Any) -> None: Example: - >>> from django.contrib.postgres import fields as pgfields >>> from django.db import models >>> from pydis_site.apps.api.models.utils import validate_embed >>> class MyMessage(models.Model): - ... embed = pgfields.JSONField( + ... embed = models.JSONField( ... validators=( ... validate_embed, ... ) -- cgit v1.2.3 From 953f232d47ff4e07baeaffa8add7912ff05d6457 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Sat, 11 Dec 2021 13:59:40 +0000 Subject: Use new approx message count view We have added a new view to metricity that will keep track of an approximate message count, updating every 10 seconds. By doing this, we avoid running a query against the whole message table every time we want to get a user's messages. --- pydis_site/apps/api/models/bot/metricity.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/models/bot/metricity.py b/pydis_site/apps/api/models/bot/metricity.py index 901f191a..52e946ac 100644 --- a/pydis_site/apps/api/models/bot/metricity.py +++ b/pydis_site/apps/api/models/bot/metricity.py @@ -46,14 +46,12 @@ class Metricity: self.cursor.execute( """ SELECT - COUNT(*) - FROM messages + message_count + FROM user_has_approx_message_count WHERE author_id = '%s' - AND NOT is_deleted - AND channel_id NOT IN %s """, - [user_id, EXCLUDE_CHANNELS] + [user_id] ) values = self.cursor.fetchone() -- cgit v1.2.3 From 1261efd75c10bf2031a2019475d4b32c5859d807 Mon Sep 17 00:00:00 2001 From: RohanJnr Date: Mon, 13 Dec 2021 11:25:27 +0530 Subject: Merge migrations to avoid conflicts. --- pydis_site/apps/api/migrations/0078_merge_20211213_0552.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 pydis_site/apps/api/migrations/0078_merge_20211213_0552.py (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0078_merge_20211213_0552.py b/pydis_site/apps/api/migrations/0078_merge_20211213_0552.py new file mode 100644 index 00000000..5ce0e871 --- /dev/null +++ b/pydis_site/apps/api/migrations/0078_merge_20211213_0552.py @@ -0,0 +1,14 @@ +# Generated by Django 3.1.14 on 2021-12-13 05:52 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0077_use_generic_jsonfield'), + ('api', '0074_merge_20211105_0518'), + ] + + operations = [ + ] -- cgit v1.2.3 From f65184b5e454437c3c524d1236041f170fff3ea4 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Tue, 14 Dec 2021 18:59:49 +0000 Subject: Query message count directly from messages This was changed due to performance reasons, but after some tweaking in the database, such as increasing work memory and adding an index, this query runs much faster now. To test this, I want to revert this change, so that we can stop the materialised view from refreshing, to see if the act of refreshing is what's causing this query to seem faster when runing against the database. --- pydis_site/apps/api/models/bot/metricity.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/models/bot/metricity.py b/pydis_site/apps/api/models/bot/metricity.py index 52e946ac..901f191a 100644 --- a/pydis_site/apps/api/models/bot/metricity.py +++ b/pydis_site/apps/api/models/bot/metricity.py @@ -46,12 +46,14 @@ class Metricity: self.cursor.execute( """ SELECT - message_count - FROM user_has_approx_message_count + COUNT(*) + FROM messages WHERE author_id = '%s' + AND NOT is_deleted + AND channel_id NOT IN %s """, - [user_id] + [user_id, EXCLUDE_CHANNELS] ) values = self.cursor.fetchone() -- cgit v1.2.3 From 59e4a5c8316464e116630a329064decac4c2a075 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Thu, 16 Dec 2021 22:29:11 +0000 Subject: Always include metricity message blocks Thanks to a recent database maintenance (https://pythondiscord.freshstatus.io/incident/139811) querying out metricity message data is far cheaper. So there is no longer a reason to only fetch blocks if the member has a low message count. --- pydis_site/apps/api/tests/test_users.py | 21 +-------------------- pydis_site/apps/api/viewsets/bot/user.py | 6 +----- 2 files changed, 2 insertions(+), 25 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/tests/test_users.py b/pydis_site/apps/api/tests/test_users.py index 81bfd43b..9b91380b 100644 --- a/pydis_site/apps/api/tests/test_users.py +++ b/pydis_site/apps/api/tests/test_users.py @@ -408,7 +408,7 @@ class UserMetricityTests(AuthenticatedAPITestCase): in_guild=True, ) - def test_get_metricity_data_under_1k(self): + def test_get_metricity_data(self): # Given joined_at = "foo" total_messages = 1 @@ -428,25 +428,6 @@ class UserMetricityTests(AuthenticatedAPITestCase): "activity_blocks": total_blocks }) - def test_get_metricity_data_over_1k(self): - # Given - joined_at = "foo" - total_messages = 1001 - total_blocks = 1001 - self.mock_metricity_user(joined_at, total_messages, total_blocks, []) - - # When - url = reverse('api:bot:user-metricity-data', args=[0]) - response = self.client.get(url) - - # Then - self.assertEqual(response.status_code, 200) - self.assertCountEqual(response.json(), { - "joined_at": joined_at, - "total_messages": total_messages, - "voice_banned": False, - }) - def test_no_metricity_user(self): # Given self.mock_no_metricity_user() diff --git a/pydis_site/apps/api/viewsets/bot/user.py b/pydis_site/apps/api/viewsets/bot/user.py index ed661323..1a5e79f8 100644 --- a/pydis_site/apps/api/viewsets/bot/user.py +++ b/pydis_site/apps/api/viewsets/bot/user.py @@ -273,11 +273,7 @@ class UserViewSet(ModelViewSet): data = metricity.user(user.id) data["total_messages"] = metricity.total_messages(user.id) - if data["total_messages"] < 1000: - # Only calculate and return activity_blocks if the user has a small amount - # of messages, as calculating activity_blocks is expensive. - # 1000 message chosen as an arbitrarily large number. - data["activity_blocks"] = metricity.total_message_blocks(user.id) + data["activity_blocks"] = metricity.total_message_blocks(user.id) data["voice_banned"] = voice_banned return Response(data, status=status.HTTP_200_OK) -- cgit v1.2.3 From 6b0741c560ebe74e1003c5d19e2889d2d8fa8847 Mon Sep 17 00:00:00 2001 From: Boris Muratov <8bee278@gmail.com> Date: Fri, 31 Dec 2021 00:16:42 +0200 Subject: Fix faulty regex filters in migration 59 Migration 59 populated the filters table with regex filters, some of which were faulty because the `\b` character wasn't escaped. This is fixed in this PR by making all patterns raw strings. --- .../api/migrations/0059_populate_filterlists.py | 58 +++++++++++----------- 1 file changed, 29 insertions(+), 29 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/api/migrations/0059_populate_filterlists.py b/pydis_site/apps/api/migrations/0059_populate_filterlists.py index 8c550191..273db3d1 100644 --- a/pydis_site/apps/api/migrations/0059_populate_filterlists.py +++ b/pydis_site/apps/api/migrations/0059_populate_filterlists.py @@ -60,35 +60,35 @@ domain_name_blacklist = [ ] filter_token_blacklist = [ - ("\bgoo+ks*\b", None, False), - ("\bky+s+\b", None, False), - ("\bki+ke+s*\b", None, False), - ("\bbeaner+s?\b", None, False), - ("\bcoo+ns*\b", None, False), - ("\bnig+lets*\b", None, False), - ("\bslant-eyes*\b", None, False), - ("\btowe?l-?head+s*\b", None, False), - ("\bchi*n+k+s*\b", None, False), - ("\bspick*s*\b", None, False), - ("\bkill* +(?:yo)?urself+\b", None, False), - ("\bjew+s*\b", None, False), - ("\bsuicide\b", None, False), - ("\brape\b", None, False), - ("\b(re+)tar+(d+|t+)(ed)?\b", None, False), - ("\bta+r+d+\b", None, False), - ("\bcunts*\b", None, False), - ("\btrann*y\b", None, False), - ("\bshemale\b", None, False), - ("fa+g+s*", None, False), - ("卐", None, False), - ("卍", None, False), - ("࿖", None, False), - ("࿕", None, False), - ("࿘", None, False), - ("࿗", None, False), - ("cuck(?!oo+)", None, False), - ("nigg+(?:e*r+|a+h*?|u+h+)s?", None, False), - ("fag+o+t+s*", None, False), + (r"\bgoo+ks*\b", None, False), + (r"\bky+s+\b", None, False), + (r"\bki+ke+s*\b", None, False), + (r"\bbeaner+s?\b", None, False), + (r"\bcoo+ns*\b", None, False), + (r"\bnig+lets*\b", None, False), + (r"\bslant-eyes*\b", None, False), + (r"\btowe?l-?head+s*\b", None, False), + (r"\bchi*n+k+s*\b", None, False), + (r"\bspick*s*\b", None, False), + (r"\bkill* +(?:yo)?urself+\b", None, False), + (r"\bjew+s*\b", None, False), + (r"\bsuicide\b", None, False), + (r"\brape\b", None, False), + (r"\b(re+)tar+(d+|t+)(ed)?\b", None, False), + (r"\bta+r+d+\b", None, False), + (r"\bcunts*\b", None, False), + (r"\btrann*y\b", None, False), + (r"\bshemale\b", None, False), + (r"fa+g+s*", None, False), + (r"卐", None, False), + (r"卍", None, False), + (r"࿖", None, False), + (r"࿕", None, False), + (r"࿘", None, False), + (r"࿗", None, False), + (r"cuck(?!oo+)", None, False), + (r"nigg+(?:e*r+|a+h*?|u+h+)s?", None, False), + (r"fag+o+t+s*", None, False), ] file_format_whitelist = [ -- cgit v1.2.3 From 5c63524c8871144736147e3b136d633901d0ef9d Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Wed, 5 Jan 2022 15:13:52 +0000 Subject: Add netcup logo to page footer --- pydis_site/static/css/base/base.css | 8 ++++++++ pydis_site/templates/base/footer.html | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/static/css/base/base.css b/pydis_site/static/css/base/base.css index f3fe1e44..340ff341 100644 --- a/pydis_site/static/css/base/base.css +++ b/pydis_site/static/css/base/base.css @@ -78,6 +78,14 @@ main.site-content { color: #00000000; } +#netcup-logo { + padding-left: 15px; + background: url(https://www.netcup-wiki.de/static/assets/images/netcup_logo_white.svg) no-repeat center; + background-size: 60px; + background-position: 0px 3px; + color: #00000000; +} + #django-logo { padding-bottom: 2px; background: url(https://static.djangoproject.com/img/logos/django-logo-negative.png) no-repeat center; diff --git a/pydis_site/templates/base/footer.html b/pydis_site/templates/base/footer.html index bca43b5d..0bc93578 100644 --- a/pydis_site/templates/base/footer.html +++ b/pydis_site/templates/base/footer.html @@ -1,7 +1,7 @@ -- cgit v1.2.3 From d5026f3f1ccbc8dd913d9aa58f9e6f41e5bc83e2 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Wed, 5 Jan 2022 15:15:29 +0000 Subject: Use an svg for django footer logo --- pydis_site/static/css/base/base.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/static/css/base/base.css b/pydis_site/static/css/base/base.css index 340ff341..deac15d2 100644 --- a/pydis_site/static/css/base/base.css +++ b/pydis_site/static/css/base/base.css @@ -88,8 +88,8 @@ main.site-content { #django-logo { padding-bottom: 2px; - background: url(https://static.djangoproject.com/img/logos/django-logo-negative.png) no-repeat center; - filter: grayscale(1) invert(0.02); + background: url(https://static.djangoproject.com/img/logos/django-logo-negative.svg) no-repeat center; + filter: grayscale(1) invert(0.09); background-size: 52px 25.5px; background-position: -1px -2px; color: #00000000; -- cgit v1.2.3 From 2384d6c4a739f5ee29bfd60c1608a67959169ba2 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Wed, 5 Jan 2022 15:15:48 +0000 Subject: Shift footer images slightly to be better in line --- pydis_site/static/css/base/base.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'pydis_site') diff --git a/pydis_site/static/css/base/base.css b/pydis_site/static/css/base/base.css index deac15d2..4b36b7ce 100644 --- a/pydis_site/static/css/base/base.css +++ b/pydis_site/static/css/base/base.css @@ -91,7 +91,7 @@ main.site-content { background: url(https://static.djangoproject.com/img/logos/django-logo-negative.svg) no-repeat center; filter: grayscale(1) invert(0.09); background-size: 52px 25.5px; - background-position: -1px -2px; + background-position: -2px -1px; color: #00000000; } @@ -100,6 +100,7 @@ main.site-content { height: 20px; background: url(https://bulma.io/images/bulma-logo-white.png) no-repeat center; background-size: 60px; + background-position: 0px 3px; color: #00000000; } -- cgit v1.2.3 From 512b1659f5bb5d2dfb8029f42d7b8c7e3436ede1 Mon Sep 17 00:00:00 2001 From: Krish Date: Fri, 7 Jan 2022 12:19:29 +0530 Subject: Resource Suggestion: #639 solved --- .../pydis-guides/contributing/setting-test-server-and-bot-account.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/setting-test-server-and-bot-account.md b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/setting-test-server-and-bot-account.md index c14fe50d..43d1c8f5 100644 --- a/pydis_site/apps/content/resources/guides/pydis-guides/contributing/setting-test-server-and-bot-account.md +++ b/pydis_site/apps/content/resources/guides/pydis-guides/contributing/setting-test-server-and-bot-account.md @@ -18,13 +18,11 @@ icon: fab fa-discord 4. Change your bot's `Public Bot` setting off so only you can invite it, save, and then get your **Bot Token** with the `Copy` button. > **Note:** **DO NOT** post your bot token anywhere public, or it can and will be compromised. 5. Save your **Bot Token** somewhere safe to use in the project settings later. -6. In the `General Information` tab, grab the **Client ID**. +6. In the `OAuth2` tab, grab the **Client ID**. 7. Replace `` in the following URL and visit it in the browser to invite your bot to your new test server. ```plaintext https://discordapp.com/api/oauth2/authorize?client_id=&permissions=8&scope=bot ``` -Optionally, you can generate your own invite url in the `OAuth` tab, after selecting `bot` as the scope. - --- ## Obtain the IDs -- cgit v1.2.3 From 0bca620f5f540744d29df42c6cb68ed387815139 Mon Sep 17 00:00:00 2001 From: Chris Lovering Date: Wed, 5 Jan 2022 15:16:08 +0000 Subject: Add netcup logo to sponsor block on homeapge --- pydis_site/static/images/sponsors/netcup.png | Bin 0 -> 9492 bytes pydis_site/templates/home/index.html | 3 +++ 2 files changed, 3 insertions(+) create mode 100644 pydis_site/static/images/sponsors/netcup.png (limited to 'pydis_site') diff --git a/pydis_site/static/images/sponsors/netcup.png b/pydis_site/static/images/sponsors/netcup.png new file mode 100644 index 00000000..e5dff196 Binary files /dev/null and b/pydis_site/static/images/sponsors/netcup.png differ diff --git a/pydis_site/templates/home/index.html b/pydis_site/templates/home/index.html index 985ccae1..c7350cac 100644 --- a/pydis_site/templates/home/index.html +++ b/pydis_site/templates/home/index.html @@ -173,6 +173,9 @@ Sponsors
+ + netcup + Linode -- cgit v1.2.3 From da2c211fd7024edf3a27d7fafe9b110afbe705fc Mon Sep 17 00:00:00 2001 From: Joe Banks Date: Fri, 14 Jan 2022 12:59:31 +0000 Subject: Add Django Discord community --- pydis_site/apps/resources/resources/communities/django.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 pydis_site/apps/resources/resources/communities/django.yaml (limited to 'pydis_site') diff --git a/pydis_site/apps/resources/resources/communities/django.yaml b/pydis_site/apps/resources/resources/communities/django.yaml new file mode 100644 index 00000000..0ef729ba --- /dev/null +++ b/pydis_site/apps/resources/resources/communities/django.yaml @@ -0,0 +1,13 @@ +description: Django is a high-level Python web framework that encourages rapid development and clean, + pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, + so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. +title_image: https://static.djangoproject.com/img/logos/django-logo-positive.png +title_url: https://discord.gg/M9Mx3RvKM5 +position: 5 +urls: + - icon: branding/discord + url: https://discord.gg/M9Mx3RvKM5 + color: blurple + - icon: regular/link + url: https://www.djangoproject.com/ + color: teal -- cgit v1.2.3 From 71a4214f53db5fc4c09fba9715f8f87cfa487123 Mon Sep 17 00:00:00 2001 From: Joe Banks Date: Fri, 14 Jan 2022 12:59:46 +0000 Subject: Renumber communities after Django --- pydis_site/apps/resources/resources/communities/kivy.yaml | 2 +- pydis_site/apps/resources/resources/communities/pallets.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'pydis_site') diff --git a/pydis_site/apps/resources/resources/communities/kivy.yaml b/pydis_site/apps/resources/resources/communities/kivy.yaml index 601d7dba..69f117c7 100644 --- a/pydis_site/apps/resources/resources/communities/kivy.yaml +++ b/pydis_site/apps/resources/resources/communities/kivy.yaml @@ -5,7 +5,7 @@ icon_image: https://raw.githubusercontent.com/kivy/kivy-website/master/logos/kiv icon_size: 50 title_image: https://i.imgur.com/EVP3jZR.png title_url: https://discord.gg/djPtTRJ -position: 5 +position: 6 urls: - icon: branding/discord url: https://discord.gg/djPtTRJ diff --git a/pydis_site/apps/resources/resources/communities/pallets.yaml b/pydis_site/apps/resources/resources/communities/pallets.yaml index 239b1491..64c97dab 100644 --- a/pydis_site/apps/resources/resources/communities/pallets.yaml +++ b/pydis_site/apps/resources/resources/communities/pallets.yaml @@ -3,7 +3,7 @@ description: The Pallets Projects develop Python libraries such as the Flask web and get help from the Pallets community. title_image: https://i.imgur.com/sV9Ypdf.png title_url: https://discord.gg/t6rrQZH -position: 6 +position: 7 urls: - icon: branding/discord url: https://discord.gg/t6rrQZH -- cgit v1.2.3