-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathconfigure-guild.py
More file actions
1305 lines (1177 loc) · 55.3 KB
/
configure-guild.py
File metadata and controls
1305 lines (1177 loc) · 55.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "discord-py>=2.3.1",
# "pydantic>=2.8.2",
# ]
# ///
from __future__ import annotations
import argparse
import asyncio
import logging
import os
import re
import sys
import textwrap
from collections import defaultdict
from typing import Annotated, Any, Literal, Self, assert_never
import discord
from discord import VerificationLevel
from discord.ext.commands import Bot
from discord.utils import get as discord_get
from pydantic import AfterValidator, BaseModel, Field, model_validator
logger = logging.getLogger(__name__)
DESCRIPTION = """\
Configure the EuroPython Discord guild.
Requires the environment variable 'BOT_TOKEN' to be set.
Requires bot privileges for receiving 'GUILD_MEMBER' events.
It will:
- Enable 'Community Server' features
- Configure system channels
- Update roles
- Add missing roles
- Update colors
- Update 'hoist' flag
- Update 'mentionable' flag
- Update role permissions
- Update categories, text channels, and forums
- Add missing categories, text channels, and forums
- Update positions
- Add missing forum tags
- Update 'mandatory/optional' state of forum tags
- Update category, text channel, and forum permission overwrites
- Update category and channel permission overwrites
- Update channel's default messages
To do manually:
- Configure role order
It will not:
- Delete roles
- Delete categories
- Delete channels
- Delete forum tags
- Delete human-authored messages
All operations are idempotent. Applying the same configuration twice will perform no changes.
"""
MultilineString = Annotated[
str,
AfterValidator(lambda text: textwrap.dedent(text.strip("\r\n").rstrip())),
]
Permission = Literal[
"add_reactions",
"administrator",
"attach_files",
"ban_members",
"change_nickname",
"connect",
"create_events",
"create_expressions",
"create_instant_invite",
"create_polls",
"create_private_threads",
"create_public_threads",
"deafen_members",
"embed_links",
"external_emojis",
"external_stickers",
"kick_members",
"manage_channels",
"manage_emojis",
"manage_emojis_and_stickers",
"manage_events",
"manage_expressions",
"manage_guild",
"manage_messages",
"manage_nicknames",
"manage_permissions",
"manage_roles",
"manage_threads",
"manage_webhooks",
"mention_everyone",
"moderate_members",
"move_members",
"mute_members",
"priority_speaker",
"read_message_history",
"read_messages",
"request_to_speak",
"send_messages",
"send_messages_in_threads",
"send_polls",
"send_tts_messages",
"send_voice_messages",
"speak",
"stream",
"use_application_commands",
"use_embedded_activities",
"use_external_apps",
"use_external_emojis",
"use_external_sounds",
"use_external_stickers",
"use_soundboard",
"use_voice_activation",
"view_audit_log",
"view_channel",
"view_creator_monetization_analytics",
"view_guild_insights",
]
class PermissionOverwrite(BaseModel):
roles: list[str]
allow: list[Permission] = Field(default_factory=list)
deny: list[Permission] = Field(default_factory=list)
class Role(BaseModel):
name: str
color: str = Field(pattern="#[0-9A-F]{6}")
hoist: bool = False
mentionable: bool = False
permissions: list[Permission] = Field(default_factory=list)
class ForumChannel(BaseModel):
type: Literal["forum"] = "forum"
name: str
topic: MultilineString
permission_overwrites: list[PermissionOverwrite] = Field(default_factory=list)
tags: list[str] = Field(default_factory=list)
require_tag: bool = False
class TextChannel(BaseModel):
type: Literal["text"] = "text"
name: str
topic: MultilineString
permission_overwrites: list[PermissionOverwrite] = Field(default_factory=list)
channel_messages: list[MultilineString] = Field(default_factory=list)
class VoiceChannel(BaseModel):
type: Literal["voice"] = "voice"
name: str
permission_overwrites: list[PermissionOverwrite] = Field(default_factory=list)
class Category(BaseModel):
name: str
channels: list[
Annotated[TextChannel | ForumChannel | VoiceChannel, Field(discriminator="type")]
]
permission_overwrites: list[PermissionOverwrite] = Field(default_factory=list)
class GuildConfig(BaseModel):
roles: list[Role]
rules_channel_name: str
system_channel_name: str
updates_channel_name: str
categories: list[Category]
@model_validator(mode="after")
def verify_system_channel_names(self) -> Self:
channel_names: list[str] = []
for category in self.categories:
channel_names.extend(channel.name for channel in category.channels)
required_channels = [
self.rules_channel_name,
self.system_channel_name,
self.updates_channel_name,
]
missing_channels = [
channel for channel in required_channels if channel not in channel_names
]
if missing_channels:
raise ValueError(f"Missing system channels: {missing_channels}")
return self
@model_validator(mode="after")
def verify_permission_roles(self) -> Self:
roles = [role.name for role in self.roles]
missing_roles = set()
for category in self.categories:
for overwrite in category.permission_overwrites:
for role in overwrite.roles:
if role not in roles:
missing_roles.add(role)
for channel in category.channels:
for overwrite in channel.permission_overwrites:
for role in overwrite.roles:
if role not in roles:
missing_roles.add(role)
if missing_roles:
raise ValueError(f"Missing roles: {missing_roles}")
return self
COLOR_BLUE = "#0096C7"
COLOR_LIGHT_BLUE = "#8FD3E0"
COLOR_DARK_ORANGE = "#E6412C"
COLOR_ORANGE = "#E85D04"
COLOR_DARK_YELLOW = "#BC8C15"
COLOR_YELLOW = "#FFD700"
COLOR_PURPLE = "#D34EA5"
COLOR_GREY = "#99AAB5"
COLOR_DARK_PURPLE = "#658B34"
ROLE_COC = "Code of Conduct Committee"
ROLE_MODERATORS = "Moderators"
ROLE_ORGANIZERS = "Organizers"
ROLE_VOLUNTEERS = "Volunteers"
ROLE_SPEAKERS = "Speakers"
ROLE_SPONSORS = "Sponsors"
ROLE_PARTICIPANTS = "Participants"
ROLE_EVERYONE = "@everyone"
ROLE_BEGINNERS_DAY = "Beginners Day"
ROLES_COC = [ROLE_COC]
ROLES_MODERATORS = [ROLE_MODERATORS, *ROLES_COC]
ROLES_ORGANIZERS = [ROLE_ORGANIZERS, *ROLES_MODERATORS]
ROLES_VOLUNTEERS = [ROLE_VOLUNTEERS, *ROLES_ORGANIZERS]
ROLES_SPEAKERS = [ROLE_SPEAKERS, *ROLES_ORGANIZERS]
ROLES_SPONSORS = [ROLE_SPONSORS, *ROLES_ORGANIZERS]
ROLES_REGISTERED = [
ROLE_PARTICIPANTS,
ROLE_SPONSORS,
ROLE_SPEAKERS,
*ROLES_VOLUNTEERS,
ROLE_BEGINNERS_DAY,
]
SERVER_CONFIG = GuildConfig(
roles=[
Role(
name=ROLE_COC,
color=COLOR_DARK_ORANGE,
hoist=True,
mentionable=True,
permissions=[
"kick_members",
"ban_members",
"priority_speaker",
"deafen_members",
"mute_members",
],
),
Role(
name=ROLE_MODERATORS,
color=COLOR_ORANGE,
hoist=True,
mentionable=True,
permissions=[
"manage_nicknames",
"moderate_members",
"manage_messages",
"manage_threads",
"priority_speaker",
"deafen_members",
"mute_members",
],
),
Role(
name=ROLE_ORGANIZERS,
color=COLOR_DARK_YELLOW,
permissions=["mention_everyone", "use_external_apps", "manage_roles"],
),
Role(
name=ROLE_VOLUNTEERS,
color=COLOR_YELLOW,
hoist=True,
mentionable=True,
),
Role(name="Onsite Volunteers", color=COLOR_GREY),
Role(name="Remote Volunteers", color=COLOR_GREY),
Role(
name=ROLE_SPEAKERS,
color=COLOR_BLUE,
hoist=True,
mentionable=True,
),
Role(
name=ROLE_SPONSORS,
color=COLOR_LIGHT_BLUE,
hoist=True,
mentionable=True,
),
Role(
name=ROLE_PARTICIPANTS,
color=COLOR_PURPLE,
hoist=True,
mentionable=True,
permissions=["use_external_emojis", "use_external_stickers", "create_polls"],
),
Role(name="Onsite Participants", color=COLOR_GREY),
Role(name="Remote Participants", color=COLOR_GREY),
Role(
name=ROLE_BEGINNERS_DAY,
color=COLOR_DARK_PURPLE,
mentionable=True,
permissions=["use_external_emojis", "use_external_stickers", "create_polls"],
),
Role(name="Programme Team", color=COLOR_GREY, mentionable=True),
Role(
name="@everyone",
color=COLOR_GREY,
permissions=[
"view_channel",
"change_nickname",
"send_messages",
"send_messages_in_threads",
"create_public_threads",
"embed_links",
"attach_files",
"add_reactions",
"read_message_history",
"use_application_commands",
"connect",
"speak",
"use_voice_activation",
],
),
],
rules_channel_name="rules",
system_channel_name="system-events",
updates_channel_name="discord-updates",
categories=[
Category(
name="Information",
channels=[
TextChannel(
name="rules",
topic="Please read the rules carefully!",
channel_messages=[
"""
## Community Rules
**Rule 1**
Follow the [EuroPython Society Code of Conduct](https://www.europython-society.org/coc/).
**Rule 2**
Use English to the best of your ability. Be polite if someone speaks English imperfectly.
**Rule 3**
Use the name on your ticket as your display name. This will be done automatically during the #registration-form process.
**Rule 4**
When posting pictures, please keep visually impaired attendees in mind. A short description can make a big difference.
See also: [Discord - Add Alt Text To Your Image Upload](https://support.discord.com/hc/en-us/articles/211866427-How-do-I-upload-images-and-GIFs#h_01GWWTHYJEV2S1WCDGFEMY21AQ)
**Reporting Incidents**
If you notice something that needs the attention of a moderator of the community, please ping the <<@&Moderators>> role.
Note that not all moderators are a member of the EuroPython Code of Conduct team. See the <<#code-of-conduct>> channel to read how you can report Code of Conduct incidents.
""" # noqa: E501 (line too long)
],
),
TextChannel(
name="code-of-conduct",
topic="https://www.europython-society.org/coc/",
channel_messages=[
"""
## EuroPython Society Code of Conduct
EuroPython is a community conference intended for networking and collaboration in the developer community.
We value the participation of each member of the Python community and want all participants to have an enjoyable and fulfilling experience. Accordingly, all attendees are expected to show respect and courtesy to other attendees throughout the conference and at all conference events.
To make clear what is expected, all staff, attendees, speakers, exhibitors, organisers, and volunteers at any EuroPython event are required to conform to the [Code of Conduct](https://www.europython-society.org/coc/), as set forth by the [EuroPython Society](https://www.europython-society.org/about/). Organisers will enforce this code throughout the event.
**Please read the Code of Conduct:** https://www.europython-society.org/coc/
""", # noqa: E501 (line too long)
"""
## Reporting Incidents
**If you believe someone is in physical danger, including from themselves**, the most important thing is to get that person help. Please contact the appropriate crisis number, non-emergency number, or police number. If you are a EuroPython attendee, you can consult with a volunteer or organiser to help find an appropriate number.
If you believe a [Code of Conduct](https://www.europython-society.org/coc/) incident has occurred, we encourage you to report it. If you are unsure whether the incident is a violation, or whether the space where it happened is covered by the Code of Conduct, we encourage you to still report it. We are fine with receiving reports where we decide to take no action for the sake of creating a safer space.
""", # noqa: E501 (line too long)
"""
## General Reporting Procedure
If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of the Code of Conduct committee immediately:
- Email: [coc@europython.eu](mailto:coc@europython.eu)
- Discord role: <<@&Code of Conduct Committee>>
- Individual contact information: [EPS Website](https://www.europython-society.org/coc/#contact-information)
""", # noqa: E501 (line too long)
"""
## Links
- [EuroPython Society Code of Conduct](https://www.europython-society.org/coc/)
- [Incident Reporting Procedure](https://www.europython-society.org/coc-incident-reporting/)
- [Procedure for Incident Response](https://www.europython-society.org/coc-enforcement-procedure/)
""",
],
),
ForumChannel(
name="job-board",
topic="""
Make sure your job openings follows the following rules:
1. Title: A clear and concise title including the role and the Company/Organization
2. Job Type: Indicate whether the job is full-time, part-time, contract-based, freelance, or an internship.
3. Job Description: Provide a URL or text explaining the job.
4. Application Deadline: If there is a specific deadline for applications, mention it in the post.
5. Salary/Compensation: If possible and appropriate, include salary or compensation details.
6. Additional Information: stuff like: perks, or notable company culture, include them in the post.
7. Relevant Tags: Use relevant tags or keywords to categorize the job post. Please let us know if important tags are missing.
8. No Discrimination: Ensure that the job post does not include any discriminatory language or requirements.
9. Updates and Removal: If the job position is filled or no longer available, update or remove the post to avoid confusion for job seekers.
""", # noqa: E501 (line too long)
tags=[
"Remote",
"Hybrid",
"On-site",
"AI",
"Data Science",
"Data Engineering",
"Backend",
"Frontend",
"Full Stack",
"Cloud",
"Web",
"DevOps",
"Junior",
"Professional",
"Senior",
],
require_tag=True,
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_SPONSORS, allow=["send_messages", "create_public_threads"]
),
],
),
],
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE],
deny=["send_messages", "create_public_threads", "add_reactions"],
)
],
),
Category(
name="EuroPython 2025",
channels=[
TextChannel(
name="announcements",
topic="Organisers will make EuroPython announcements in this channel",
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE], deny=["send_messages", "create_public_threads"]
),
PermissionOverwrite(roles=[ROLE_ORGANIZERS], allow=["send_messages"]),
],
),
TextChannel(
name="general-chat",
topic=(
"Social chat for conference participants. "
"Please follow the Rules and Code of Conduct."
),
),
ForumChannel(
name="support",
topic="""
Use this forum channel to create support tickets if you **need support from the conference organization**. Please don't open forum threads related to other topics, as that makes it difficult for the organizers to keep track of support tickets that need their attention.
If you to make a report to the Code of Conduct Committee, please use coc@europython.eu or contact an organizer at the conference.
""", # noqa: E501 (line too long)
tags=["Remote Support", "On-Site Support"],
require_tag=True,
),
ForumChannel(
name="feedback",
topic="""
Please share your thoughts and ideas. What works well? What doesn't? How can we make EuroPython even better?
""", # noqa: E501 (line too long)
),
TextChannel(
name="introduction",
topic="Feel free to introduce yourself here :)",
),
TextChannel(
name="ask-the-locals",
topic="""
The right place to ask locals for help and experience.
Many people recommended the YouTube channel 'HONEST GUIDE', maybe you find it helpful as well: https://www.youtube.com/@HONESTGUIDE
""", # noqa: E501 (line too long)
),
ForumChannel(
name="topics-and-interests",
topic="""
You can use this forum channel to start conversations focused around specific topics and interests, including topics unrelated to EuroPython or Python. Think of it like a virtual hallway track where you can discuss topics with the people you meet while participating in a conference.
**Use a descriptive title** that clearly highlights the topic you intend to discuss within this channel. However, do **keep in mind that conversations tend to meander away from their initial topic over time**. While it's okay to nudge the conversation back onto its original topic, do **be patient and civil** with each other, even if you perceive someone as going "off-topic".
Thank you for your cooperation in maintaining an open and welcoming environment for everyone!
""", # noqa: E501 (line too long)
),
ForumChannel(
name="social-activities",
topic="""
# Social Activities organized by and for attendees
You can use this channel to organize a social activity with other attendees of the conference. Do note that EuroPython only provides a space for attendees to coordinate social activities, it does not officially endorse activities posted here.
## topic for a good post
- Use a **descriptive title** that captures the core of your activity
- If relevant, **include the date and time in your title**
- Indicate if your activity is **in-person** or **remote** by selecting the appropriate tag
""", # noqa: E501 (line too long)
tags=["In Person", "Remote"],
require_tag=True,
),
TextChannel(
name="lost-and-found",
topic=(
"Channel for the coordination of lost and found items. "
"Please bring found items to the registration desk."
),
),
],
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_REGISTERED, allow=["view_channel"]),
],
),
Category(
name="Remote Attendees",
channels=[
TextChannel(name="remote-text", topic="Text chat for remote attendees"),
VoiceChannel(name="remote-voice"),
],
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_REGISTERED, allow=["view_channel"]),
],
),
Category(
name="Sponsors",
channels=[],
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_REGISTERED, allow=["view_channel"]),
],
),
Category(
name="Rooms",
channels=[
TextChannel(
name="programme-notifications",
topic="Find the latest information about starting sessions here!",
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["send_messages"])
],
),
TextChannel(name="forum-hall", topic="Livestream: [TBA]"),
TextChannel(name="south-hall-2a", topic="Livestream: [TBA]"),
TextChannel(name="south-hall-2b", topic="Livestream: [TBA]"),
TextChannel(name="north-hall", topic="Livestream: [TBA]"),
TextChannel(name="terrace-2a", topic="Livestream: [TBA]"),
TextChannel(name="terrace-2b", topic="Livestream: [TBA]"),
TextChannel(
name="exhibit-hall", topic="For conversations related to the exhibit hall."
),
TextChannel(
name="open-spaces",
topic=(
"For conversations related to the open spaces. Schedule and booking: [TBA]"
),
),
ForumChannel(
name="tutorials",
topic="""
We kindly ask you to **only create one thread per tutorial**. Having too many threads makes it more difficult for participants to find the thread of the tutorial they're participating in.
**Tips:**
- On desktop, you can open a forum thread in "full window mode" using the `...` option menu in the top bar.
- If you select to "follow" a thread, it will appear directly in your channel list.
""", # noqa: E501 (line too long)
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_REGISTERED,
deny=["create_public_threads"],
),
PermissionOverwrite(
roles=ROLES_SPEAKERS,
allow=["create_public_threads"],
),
],
),
ForumChannel(
name="sprints",
topic=(
"To keep things manageable, one post/thread per sprint would be the best."
"If there are reasons to create multiple threads/posts "
"(e.g., for groups working on a sub-project), that should be fine, too."
),
),
ForumChannel(
name="beginners-day",
topic=(
"Channel for the Beginners' Day: "
"https://ep2025.europython.eu/beginners-day/"
),
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_BEGINNERS_DAY],
allow=["view_channel"],
),
],
),
ForumChannel(
name="slides-and-artefacts",
topic="""
You can create a thread for your talk where you can add slides and other artefacts.
- Please add the **title of your talk **and the **names of the speakers** in the title. This makes it easy for participants to find your talk.
- Only create a single post per talk!
- Participants can't send messages in the thread.
""", # noqa: E501 (line too long)
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_REGISTERED,
deny=["create_public_threads"],
),
PermissionOverwrite(
roles=ROLES_SPEAKERS,
allow=["create_public_threads"],
),
],
),
],
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_REGISTERED, allow=["view_channel"]),
],
),
Category(
name="Conference Organization",
channels=[
TextChannel(
name="announcements-volunteers",
topic=(
"Announcements and requests for conference volunteers. "
"Please use <<#volunteers-lounge>> for all other "
"volunteer-related conversations."
),
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_VOLUNTEERS,
allow=["view_channel"],
),
],
),
TextChannel(
name="volunteers-lounge",
topic=(
"Social chat for volunteers. Please follow the #rules and #code-of-conduct!"
),
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_VOLUNTEERS,
allow=["view_channel"],
),
],
),
TextChannel(
name="sponsors-lounge",
topic=(
"Social chat for sponsors. Please follow the #rules and #code-of-conduct!"
),
permission_overwrites=[
PermissionOverwrite(
roles=[*ROLES_SPONSORS, *ROLES_VOLUNTEERS],
allow=["view_channel"],
),
],
),
TextChannel(
name="speakers-lounge",
topic=(
"Channel open to all speakers & conference volunteers. "
"Please follow the #rules and #code-of-conduct!"
),
permission_overwrites=[
PermissionOverwrite(
roles=[*ROLES_SPEAKERS, *ROLES_VOLUNTEERS],
allow=["view_channel"],
),
],
),
TextChannel(
name="moderators",
topic=(
"For discussions related to ongoing moderation activities, "
"moderation policy, and other moderation-related topic."
),
permission_overwrites=[
PermissionOverwrite(
roles=ROLES_MODERATORS,
allow=["view_channel"],
),
],
),
TextChannel(
name="discord-updates",
topic="Discord will send community server notifications here.",
),
],
permission_overwrites=[
PermissionOverwrite(roles=[ROLE_EVERYONE], deny=["view_channel"]),
],
),
Category(
name="Registration",
channels=[
TextChannel(
name="welcome",
topic="Welcome to our server, please register.",
channel_messages=[
"""
**Welcome to our Discord server! Please register using the <<#registration-form>>**
If you encounter any problems with registration, please ask in <<#registration-help>>.
""", # noqa: E501 (line too long)
],
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE], deny=["send_messages", "create_public_threads"]
),
PermissionOverwrite(roles=ROLES_REGISTERED, deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_ORGANIZERS, allow=["view_channel"]),
],
),
TextChannel(
name="registration-form",
topic="Please follow the registration instructions.",
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE], deny=["send_messages", "create_public_threads"]
),
PermissionOverwrite(roles=ROLES_REGISTERED, deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_ORGANIZERS, allow=["view_channel"]),
],
),
ForumChannel(
name="registration-help",
topic="""
# This channel is only for asking for help with registration, not for general discussion.
As this community is only intended for EuroPython participants, there are no public discussion channels.
""", # noqa: E501 (line too long)
permission_overwrites=[
PermissionOverwrite(roles=ROLES_REGISTERED, deny=["view_channel"]),
PermissionOverwrite(roles=ROLES_ORGANIZERS, allow=["view_channel"]),
],
),
TextChannel(
name="registration-log",
topic=(
"The EuroPython bot will log registration actions here "
"to help us with debugging."
),
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE],
deny=["view_channel"],
)
],
),
TextChannel(
name="system-events",
topic=(
'This channel will show "raw" joins to keep track of who joins '
"and who registered without diving into the audit log."
),
permission_overwrites=[
PermissionOverwrite(
roles=[ROLE_EVERYONE],
deny=["view_channel"],
)
],
),
],
),
],
)
class GuildConfigurator:
def __init__(self, guild: discord.Guild) -> None:
self.guild = guild
async def apply_configuration(self, template: GuildConfig) -> None:
logger.info("Configuring roles")
for role_template in template.roles:
await self.ensure_role(role_template)
logger.info("Configuring 'COMMUNITY' features")
await self.ensure_community_feature(
rules_channel_name=template.rules_channel_name,
updates_channel_name=template.updates_channel_name,
)
logger.info("Configuring categories and channels")
await self.ensure_categories_and_channels(template.categories)
logger.info("Configuring system channels and events")
await self.ensure_system_channel_configuration(
system_channel_name=template.system_channel_name,
updates_channel_name=template.updates_channel_name,
rules_channel_name=template.rules_channel_name,
)
logger.info("Configuring permissions")
await self.ensure_category_and_channel_permissions(template.categories)
logger.info("Configure channel topics")
await self.ensure_channel_topics(template.categories)
logger.info("Configure channel default messages")
await self.ensure_default_messages(template.categories)
def get_text_channel(self, name: str) -> discord.TextChannel:
channel = discord_get(self.guild.text_channels, name=name)
if channel is None:
raise RuntimeError(f"Could not find text channel with name '{name}'")
return channel
def get_forum(self, name: str) -> discord.ForumChannel:
channel = discord_get(self.guild.forums, name=name)
if channel is None:
raise RuntimeError(f"Could not find forum with name '{name}'")
return channel
def get_channel(
self, name: str
) -> discord.TextChannel | discord.ForumChannel | discord.VoiceChannel:
channel = discord_get(self.guild.channels, name=name)
if channel is None or not isinstance(
channel, (discord.TextChannel, discord.ForumChannel, discord.VoiceChannel)
):
raise RuntimeError(f"Could not find text, forum, or voice channel with name '{name}'")
return channel
def get_role(self, name: str) -> discord.Role:
role = discord_get(self.guild.roles, name=name)
if role is None:
raise RuntimeError(f"Could not find role with name '{name}'")
return role
def get_category(self, name: str) -> discord.CategoryChannel:
category = discord_get(self.guild.categories, name=name)
if category is None:
raise RuntimeError(f"Could not find category with name '{name}'")
return category
async def ensure_channel_permissions(
self,
channel: discord.TextChannel | discord.ForumChannel | discord.VoiceChannel,
permission_overwrite_templates: list[PermissionOverwrite],
) -> None:
logger.info("Ensure permissions for channel %s", channel.name)
logger.debug("Accumulating expected permission overwrites")
expected_overwrites_by_role: dict[str, dict[str, bool]] = defaultdict(dict)
for overwrite_template in permission_overwrite_templates:
for role_name in overwrite_template.roles:
for permission in overwrite_template.allow:
expected_overwrites_by_role[role_name][permission] = True
for permission in overwrite_template.deny:
expected_overwrites_by_role[role_name][permission] = False
logger.debug("Determine if update is required")
# Enabling some settings for some roles sometimes enables it also for @everyone.
# Workaround: If any update is required, do a full update
update_required = False
updates_by_role: dict[discord.Role, discord.PermissionOverwrite] = {}
for role_name, expected_overwrites in expected_overwrites_by_role.items():
role = self.get_role(role_name)
current_permissions = channel.permissions_for(role)
for permission, expected in expected_overwrites.items(): # type: ignore[assignment]
current_value = getattr(current_permissions, permission)
if current_value != expected:
update_required = True
updates_by_role[role] = discord.PermissionOverwrite(**expected_overwrites)
if update_required:
logger.debug("Update permissions")
await channel.edit(overwrites=updates_by_role)
async def ensure_category_and_channel_permissions(
self, category_templates: list[Category]
) -> None:
for category_template in category_templates:
for channel_template in category_template.channels:
channel = self.get_channel(channel_template.name)
await self.ensure_channel_permissions(
channel,
category_template.permission_overwrites
+ channel_template.permission_overwrites,
)
async def ensure_categories_and_channels(self, category_templates: list[Category]) -> None:
# channel positions are global, not per-category
channel_position = 0
for category_position, category_template in enumerate(category_templates):
await self.ensure_category(name=category_template.name, position=category_position)
category = self.get_category(category_template.name)
for channel_template in category_template.channels:
if isinstance(channel_template, TextChannel):
await self.ensure_text_channel(
channel_template.name, category=category, position=channel_position
)
elif isinstance(channel_template, VoiceChannel):
await self.ensure_voice_channel(
channel_template.name, category=category, position=channel_position
)
elif isinstance(channel_template, ForumChannel):
await self.ensure_forum_channel(
channel_template.name,
category=category,
position=channel_position,
expected_tags=channel_template.tags,
require_tag=channel_template.require_tag,
)
else:
# hint for the type checker: report error if there can be more channel types
assert_never(channel_template)
channel_position += 1
async def ensure_category(self, *, name: str, position: int) -> None:
logger.info("Ensure category %s at position %d", name, position)
category = discord_get(self.guild.categories, name=name)
if category is None:
logger.debug("Create category")
await self.guild.create_category(name, position=position)
else:
logger.debug("Found category")
if category.position != position:
logger.debug("Update position")
await category.edit(position=position)
async def ensure_text_channel(
self, name: str, *, category: discord.CategoryChannel | None, position: int
) -> None:
logger.info("Ensure text channel %s at position %d", name, position)
channel = discord_get(self.guild.text_channels, name=name)
if channel is None:
logger.debug("Create text channel %s", name)
await self.guild.create_text_channel(name=name, category=category, position=position)
else:
logger.debug("Found text channel")
if channel.category != category:
logger.debug("Update category")
await channel.edit(category=category)
if channel.position != position:
logger.debug("Update position")
await channel.edit(position=position)
async def ensure_voice_channel(
self, name: str, *, category: discord.CategoryChannel | None, position: int
) -> None:
logger.info("Ensure voice channel %s at position %d", name, position)
channel = discord_get(self.guild.voice_channels, name=name)
if channel is None:
logger.debug("Create voice channel %s", name)
await self.guild.create_voice_channel(name=name, category=category, position=position)
else:
logger.debug("Found voice channel")
if channel.category != category:
logger.debug("Update category")
await channel.edit(category=category)
if channel.position != position: