0
# Guild and Server Management
1
2
This knowledge tile covers nextcord's comprehensive Guild and server management capabilities, providing detailed information about server administration, member management, channel organization, role management, moderation tools, and more.
3
4
## Guild Class - Main Server Representation
5
6
The `Guild` class is the primary representation of a Discord server in nextcord, containing all server-related functionality and properties.
7
8
### Basic Guild Properties { .api }
9
10
```python
11
from nextcord import Guild, Client
12
import nextcord
13
14
# Basic guild information
15
@client.event
16
async def on_guild_join(guild: Guild):
17
print(f"Joined guild: {guild.name}")
18
print(f"Guild ID: {guild.id}")
19
print(f"Member count: {guild.member_count}")
20
print(f"Owner: {guild.owner}")
21
print(f"Region: {guild.region}")
22
print(f"Premium tier: {guild.premium_tier}")
23
```
24
25
### Core Guild Attributes
26
27
- `id: int` - The guild's unique snowflake ID
28
- `name: str` - The guild name
29
- `description: Optional[str]` - Guild description (for Community guilds)
30
- `owner_id: int` - ID of the guild owner
31
- `owner: Optional[Member]` - The guild owner as a Member object
32
- `region: VoiceRegion` - Voice region for the guild
33
- `verification_level: VerificationLevel` - Server verification level
34
- `explicit_content_filter: ContentFilter` - Content filtering level
35
- `default_notifications: NotificationLevel` - Default notification settings
36
- `nsfw_level: NSFWLevel` - Guild NSFW classification level
37
- `mfa_level: int` - Two-factor authentication requirement (0 or 1)
38
- `premium_tier: int` - Server boost level (0-3)
39
- `premium_subscription_count: int` - Number of boosts
40
- `features: List[str]` - List of guild features (see feature list below)
41
- `unavailable: bool` - Whether the guild is temporarily unavailable
42
- `large: bool` - Whether the guild has 250+ members
43
- `member_count: Optional[int]` - Total member count
44
- `max_members: Optional[int]` - Maximum member limit
45
- `max_presences: Optional[int]` - Maximum presence limit
46
- `preferred_locale: Optional[str]` - Preferred language for the guild
47
48
### Guild Features
49
50
Guild features indicate special capabilities:
51
52
- `ANIMATED_BANNER` - Can upload animated banners
53
- `ANIMATED_ICON` - Can upload animated icons
54
- `AUTO_MODERATION` - Has auto moderation enabled
55
- `BANNER` - Can use banners
56
- `COMMUNITY` - Community server features
57
- `DISCOVERABLE` - Appears in Server Discovery
58
- `INVITE_SPLASH` - Custom invite splash screens
59
- `MEMBER_VERIFICATION_GATE_ENABLED` - Membership screening
60
- `MONETIZATION_ENABLED` - Server monetization
61
- `MORE_STICKERS` - Increased sticker slots
62
- `NEWS` - Can create news channels
63
- `PARTNERED` - Discord Partner server
64
- `ROLE_ICONS` - Can set custom role icons
65
- `VANITY_URL` - Custom vanity invite URL
66
- `VERIFIED` - Verified server
67
- `VIP_REGIONS` - Access to VIP voice regions
68
- `WELCOME_SCREEN_ENABLED` - Welcome screen features
69
70
## Server Configuration
71
72
### Guild Settings and Metadata { .api }
73
74
```python
75
# Edit guild settings
76
async def configure_guild(guild: Guild):
77
await guild.edit(
78
name="New Server Name",
79
description="Updated server description",
80
verification_level=nextcord.VerificationLevel.medium,
81
explicit_content_filter=nextcord.ContentFilter.members_without_roles,
82
default_notifications=nextcord.NotificationLevel.only_mentions,
83
afk_timeout=300, # 5 minutes
84
system_channel=guild.text_channels[0], # Set system channel
85
rules_channel=guild.get_channel(12345), # Community servers
86
public_updates_channel=guild.get_channel(67890),
87
preferred_locale="en-US"
88
)
89
90
# Upload guild assets
91
with open("icon.png", "rb") as f:
92
icon_data = f.read()
93
94
with open("banner.png", "rb") as f:
95
banner_data = f.read()
96
97
await guild.edit(
98
icon=icon_data,
99
banner=banner_data,
100
splash=None # Remove splash image
101
)
102
```
103
104
### System Channels { .api }
105
106
```python
107
# System channel management
108
guild.system_channel # Channel for system messages
109
guild.system_channel_flags # System channel settings
110
guild.rules_channel # Rules channel (Community guilds)
111
guild.public_updates_channel # Public updates channel
112
guild.safety_alerts_channel # Safety alerts channel
113
114
# AFK channel configuration
115
guild.afk_channel # AFK voice channel
116
guild.afk_timeout # AFK timeout in seconds
117
```
118
119
### Guild Limits and Features { .api }
120
121
```python
122
# Check guild limits
123
print(f"Emoji limit: {guild.emoji_limit}")
124
print(f"Sticker limit: {guild.sticker_limit}")
125
print(f"Bitrate limit: {guild.bitrate_limit}")
126
print(f"File upload limit: {guild.filesize_limit}")
127
128
# Premium features
129
print(f"Premium tier: {guild.premium_tier}")
130
print(f"Boost count: {guild.premium_subscription_count}")
131
print(f"Premium subscribers: {len(guild.premium_subscribers)}")
132
```
133
134
## Member Management
135
136
### Member Access and Querying { .api }
137
138
```python
139
# Access members
140
all_members = guild.members # List of cached members
141
member = guild.get_member(user_id) # Get by ID
142
member = guild.get_member_named("username#1234") # Get by name
143
144
# Fetch members from API
145
member = await guild.fetch_member(user_id)
146
147
# Bulk member operations
148
async for member in guild.fetch_members(limit=1000):
149
print(f"Member: {member.name}")
150
151
# Query members by username
152
members = await guild.query_members(
153
query="user", # Username prefix
154
limit=50,
155
presences=True # Include presence info
156
)
157
158
# Chunk all members (requires members intent)
159
members = await guild.chunk(cache=True)
160
```
161
162
### Member Properties and Filtering { .api }
163
164
```python
165
# Member collections
166
guild.members # All cached members
167
guild.bots # Bot members only
168
guild.humans # Human members only
169
guild.premium_subscribers # Members who boosted the server
170
171
# Member counts and status
172
guild.member_count # Total member count
173
guild.approximate_member_count # Approximate count
174
guild.approximate_presence_count # Active members
175
guild.chunked # Whether all members are cached
176
```
177
178
### Member Moderation Actions { .api }
179
180
```python
181
# Kick member
182
await guild.kick(member, reason="Violation of rules")
183
184
# Ban member
185
await guild.ban(
186
member,
187
reason="Serious rule violation",
188
delete_message_seconds=86400 # Delete 1 day of messages
189
)
190
191
# Unban member
192
user = await client.fetch_user(user_id)
193
await guild.unban(user, reason="Appeal accepted")
194
195
# Timeout member (done via Member object)
196
import datetime
197
await member.timeout_for(
198
datetime.timedelta(minutes=10),
199
reason="Temporary timeout"
200
)
201
202
# Remove timeout
203
await member.remove_timeout(reason="Timeout lifted")
204
```
205
206
### Member Pruning { .api }
207
208
```python
209
# Estimate prunable members
210
count = await guild.estimate_pruned_members(
211
days=30, # Inactive for 30 days
212
roles=[guild.get_role(role_id)] # Only members with specific roles
213
)
214
215
# Prune inactive members
216
pruned = await guild.prune_members(
217
days=30,
218
compute_prune_count=True,
219
roles=[guild.get_role(role_id)],
220
reason="Cleaning inactive members"
221
)
222
```
223
224
## Channel Management
225
226
### Channel Types and Access { .api }
227
228
```python
229
# Channel collections by type
230
guild.channels # All channels
231
guild.text_channels # Text channels only
232
guild.voice_channels # Voice channels only
233
guild.stage_channels # Stage channels only
234
guild.categories # Category channels only
235
guild.forum_channels # Forum channels only
236
guild.threads # Threads you can view
237
238
# Get channels
239
channel = guild.get_channel(channel_id)
240
thread = guild.get_thread(thread_id)
241
channel_or_thread = guild.get_channel_or_thread(id)
242
243
# Fetch from API
244
channel = await guild.fetch_channel(channel_id)
245
channels = await guild.fetch_channels()
246
threads = await guild.active_threads()
247
```
248
249
### Channel Organization { .api }
250
251
```python
252
# Channels organized by category
253
categorized = guild.by_category()
254
for category, channels in categorized:
255
if category:
256
print(f"Category: {category.name}")
257
else:
258
print("Uncategorized channels:")
259
260
for channel in channels:
261
print(f" - {channel.name}")
262
```
263
264
### Creating Channels { .api }
265
266
```python
267
from nextcord import PermissionOverwrite
268
269
# Create text channel
270
overwrites = {
271
guild.default_role: PermissionOverwrite(read_messages=False),
272
guild.me: PermissionOverwrite(read_messages=True)
273
}
274
275
text_channel = await guild.create_text_channel(
276
"general-chat",
277
category=guild.categories[0], # Place in category
278
topic="General discussion",
279
slowmode_delay=5, # 5 second slowmode
280
nsfw=False,
281
overwrites=overwrites,
282
position=0,
283
default_thread_slowmode_delay=60,
284
reason="Creating new text channel"
285
)
286
287
# Create voice channel
288
voice_channel = await guild.create_voice_channel(
289
"General Voice",
290
category=guild.categories[0],
291
bitrate=96000, # 96kbps
292
user_limit=10, # Max 10 users
293
rtc_region=nextcord.VoiceRegion.us_east,
294
video_quality_mode=nextcord.VideoQualityMode.auto,
295
overwrites=overwrites,
296
reason="Creating voice channel"
297
)
298
299
# Create stage channel
300
stage_channel = await guild.create_stage_channel(
301
"Weekly Events",
302
topic="Weekly community events",
303
category=guild.categories[0],
304
bitrate=128000,
305
user_limit=50,
306
overwrites=overwrites,
307
reason="Creating stage channel"
308
)
309
310
# Create category
311
category = await guild.create_category(
312
"Community Channels",
313
overwrites=overwrites,
314
position=0,
315
reason="Organizing channels"
316
)
317
318
# Create forum channel
319
from nextcord.channel import ForumTag
320
321
forum_tags = [
322
ForumTag(name="Question", emoji="β", moderated=False),
323
ForumTag(name="Solved", emoji="β ", moderated=True)
324
]
325
326
forum_channel = await guild.create_forum_channel(
327
"Help Forum",
328
topic="Community help and support",
329
category=guild.categories[0],
330
available_tags=forum_tags,
331
default_thread_slowmode_delay=0,
332
default_sort_order=nextcord.SortOrderType.creation_date,
333
overwrites=overwrites,
334
reason="Creating help forum"
335
)
336
```
337
338
## Role Management
339
340
### Role Access and Properties { .api }
341
342
```python
343
# Access roles
344
guild.roles # All roles in hierarchy order
345
role = guild.get_role(role_id) # Get by ID
346
guild.default_role # @everyone role
347
guild.premium_subscriber_role # Boost role
348
guild.self_role # Bot's role
349
350
# Fetch from API
351
roles = await guild.fetch_roles(cache=True)
352
```
353
354
### Creating and Managing Roles { .api }
355
356
```python
357
from nextcord import Permissions, Colour
358
359
# Create role
360
permissions = Permissions(
361
send_messages=True,
362
read_messages=True,
363
manage_messages=True,
364
kick_members=True
365
)
366
367
role = await guild.create_role(
368
name="Moderator",
369
permissions=permissions,
370
colour=Colour.blue(),
371
hoist=True, # Display separately
372
mentionable=True,
373
icon="π‘οΈ", # Unicode emoji or image bytes
374
reason="Creating moderator role"
375
)
376
377
# Edit role positions
378
positions = {
379
role1: 1,
380
role2: 2,
381
admin_role: 10
382
}
383
await guild.edit_role_positions(positions, reason="Reorganizing roles")
384
```
385
386
### Role Assignment and Management { .api }
387
388
```python
389
# Add/remove roles from members
390
await member.add_roles(role1, role2, reason="Promoting member")
391
await member.remove_roles(role1, reason="Role cleanup")
392
393
# Bulk role operations
394
moderator_role = guild.get_role(moderator_role_id)
395
for member in guild.members:
396
if member.premium_since: # If they boost the server
397
await member.add_roles(moderator_role)
398
```
399
400
## Moderation Tools
401
402
### Banning and Unbanning { .api }
403
404
```python
405
# Ban management
406
async def ban_user(guild: Guild, user_id: int, reason: str):
407
# Ban user
408
user = await client.fetch_user(user_id)
409
await guild.ban(
410
user,
411
reason=reason,
412
delete_message_seconds=604800 # Delete 7 days of messages
413
)
414
415
# Check bans
416
ban_entry = await guild.fetch_ban(user)
417
print(f"Ban reason: {ban_entry.reason}")
418
419
# Iterate through all bans
420
async for ban in guild.bans(limit=100):
421
print(f"{ban.user.name} - {ban.reason}")
422
423
# Unban
424
await guild.unban(user, reason="Appeal approved")
425
```
426
427
### Auto Moderation { .api }
428
429
```python
430
from nextcord.auto_moderation import (
431
AutoModerationTriggerMetadata,
432
AutoModerationAction,
433
AutoModerationActionType,
434
AutoModerationEventType,
435
AutoModerationTriggerType
436
)
437
438
# Create auto moderation rule
439
trigger_metadata = AutoModerationTriggerMetadata(
440
keyword_filter=["badword1", "badword2"],
441
regex_patterns=[r"\b\d{16,18}\b"], # Credit card numbers
442
mention_total_limit=5
443
)
444
445
actions = [
446
AutoModerationAction(
447
type=AutoModerationActionType.block_message
448
),
449
AutoModerationAction(
450
type=AutoModerationActionType.send_alert_message,
451
metadata={"channel_id": alert_channel.id}
452
),
453
AutoModerationAction(
454
type=AutoModerationActionType.timeout,
455
metadata={"duration_seconds": 300}
456
)
457
]
458
459
rule = await guild.create_auto_moderation_rule(
460
name="Content Filter",
461
event_type=AutoModerationEventType.message_send,
462
trigger_type=AutoModerationTriggerType.keyword,
463
actions=actions,
464
trigger_metadata=trigger_metadata,
465
enabled=True,
466
exempt_roles=[moderator_role],
467
exempt_channels=[staff_channel],
468
reason="Setting up content filtering"
469
)
470
471
# Get existing rules
472
rules = await guild.auto_moderation_rules()
473
rule = await guild.fetch_auto_moderation_rule(rule_id)
474
```
475
476
### Audit Log Tracking { .api }
477
478
```python
479
# Access audit logs
480
async for entry in guild.audit_logs(
481
limit=100,
482
action=nextcord.AuditLogAction.ban,
483
user=moderator_user, # Filter by moderator
484
after=datetime.datetime.now() - datetime.timedelta(days=7)
485
):
486
print(f"{entry.user} {entry.action} {entry.target}")
487
print(f"Reason: {entry.reason}")
488
```
489
490
## Guild Events
491
492
### Scheduled Events { .api }
493
494
```python
495
from nextcord.scheduled_events import EntityMetadata
496
import datetime
497
498
# Create scheduled event
499
start_time = datetime.datetime.now() + datetime.timedelta(hours=24)
500
end_time = start_time + datetime.timedelta(hours=2)
501
502
# Stage channel event
503
event = await guild.create_scheduled_event(
504
name="Weekly Community Meeting",
505
entity_type=nextcord.ScheduledEventEntityType.stage_instance,
506
start_time=start_time,
507
end_time=end_time,
508
channel=guild.stage_channels[0],
509
description="Weekly community discussion and updates",
510
privacy_level=nextcord.ScheduledEventPrivacyLevel.guild_only,
511
reason="Creating weekly meeting"
512
)
513
514
# External event
515
external_event = await guild.create_scheduled_event(
516
name="Game Tournament",
517
entity_type=nextcord.ScheduledEventEntityType.external,
518
start_time=start_time,
519
end_time=end_time,
520
metadata=EntityMetadata(location="Community Center, Main St"),
521
description="Monthly gaming tournament",
522
reason="Creating tournament event"
523
)
524
525
# Get events
526
guild.scheduled_events # Cached events
527
event = guild.get_scheduled_event(event_id)
528
event = await guild.fetch_scheduled_event(event_id, with_users=True)
529
530
# Iterate events
531
async for event in guild.fetch_scheduled_events(with_users=True):
532
print(f"Event: {event.name} - Users interested: {event.user_count}")
533
```
534
535
### Event Management { .api }
536
537
```python
538
# Event user management
539
async for user in event.fetch_users(limit=100, with_members=True):
540
print(f"Interested user: {user.user.name}")
541
if user.member:
542
print(f" Member since: {user.member.joined_at}")
543
```
544
545
## Integrations
546
547
### Bot and Application Management { .api }
548
549
```python
550
# Application commands (slash commands)
551
commands = guild.get_application_commands()
552
await guild.sync_application_commands(
553
associate_known=True,
554
delete_unknown=True,
555
update_known=True,
556
register_new=True
557
)
558
559
# Register specific commands
560
await guild.register_application_commands(*command_objects)
561
562
# Delete commands
563
await guild.delete_application_commands(*command_objects)
564
```
565
566
### Webhooks { .api }
567
568
```python
569
# Get guild webhooks
570
webhooks = await guild.webhooks()
571
for webhook in webhooks:
572
print(f"Webhook: {webhook.name} in {webhook.channel}")
573
574
# Webhook management is typically done per-channel
575
channel_webhooks = await text_channel.webhooks()
576
```
577
578
### Third-party Integrations { .api }
579
580
```python
581
# Get integrations (YouTube, Twitch, etc.)
582
integrations = await guild.integrations()
583
for integration in integrations:
584
print(f"Integration: {integration.name} ({integration.type})")
585
586
# Create integration
587
await guild.create_integration(
588
type="twitch", # Integration type
589
id=integration_id
590
)
591
```
592
593
### Templates { .api }
594
595
```python
596
# Guild templates
597
templates = await guild.templates()
598
for template in templates:
599
print(f"Template: {template.name} - {template.code}")
600
601
# Create template
602
template = await guild.create_template(
603
name="Community Server Template",
604
description="Basic community server setup"
605
)
606
```
607
608
## Voice and Stage Channels
609
610
### Voice State Management { .api }
611
612
```python
613
# Change bot's voice state
614
await guild.change_voice_state(
615
channel=voice_channel, # None to disconnect
616
self_mute=False,
617
self_deaf=False
618
)
619
620
# Access voice states
621
voice_client = guild.voice_client # Bot's voice connection
622
for member in voice_channel.members:
623
voice_state = member.voice
624
if voice_state:
625
print(f"{member.name} - Muted: {voice_state.mute}")
626
```
627
628
### Stage Instance Management { .api }
629
630
```python
631
# Stage instances
632
guild.stage_instances # Active stage instances
633
stage_instance = guild.get_stage_instance(instance_id)
634
635
# Create stage instance (done via StageChannel)
636
stage_instance = await stage_channel.create_instance(
637
topic="Community Discussion",
638
privacy_level=nextcord.StagePrivacyLevel.guild_only,
639
reason="Starting community discussion"
640
)
641
```
642
643
## Advanced Guild Operations
644
645
### Guild Widget and Discovery { .api }
646
647
```python
648
# Guild widget
649
widget = await guild.widget()
650
print(f"Widget enabled: {widget.enabled}")
651
print(f"Instant invite: {widget.invite_url}")
652
653
# Edit widget
654
await guild.edit_widget(
655
enabled=True,
656
channel=guild.text_channels[0]
657
)
658
659
# Vanity invite
660
vanity_invite = await guild.vanity_invite()
661
if vanity_invite:
662
print(f"Vanity URL: {vanity_invite.url}")
663
```
664
665
### Guild Assets and Branding { .api }
666
667
```python
668
# Guild assets
669
if guild.icon:
670
print(f"Icon URL: {guild.icon.url}")
671
672
if guild.banner:
673
print(f"Banner URL: {guild.banner.url}")
674
675
if guild.splash:
676
print(f"Splash URL: {guild.splash.url}")
677
678
if guild.discovery_splash:
679
print(f"Discovery splash URL: {guild.discovery_splash.url}")
680
```
681
682
### Emoji and Sticker Management { .api }
683
684
```python
685
# Emoji management
686
guild.emojis # All guild emojis
687
emoji = await guild.fetch_emoji(emoji_id)
688
emojis = await guild.fetch_emojis()
689
690
# Create custom emoji
691
with open("emoji.png", "rb") as f:
692
emoji_data = f.read()
693
694
emoji = await guild.create_custom_emoji(
695
name="custom_emoji",
696
image=emoji_data,
697
roles=[moderator_role], # Restrict to specific roles
698
reason="Adding custom emoji"
699
)
700
701
# Delete emoji
702
await guild.delete_emoji(emoji, reason="Cleaning up emojis")
703
704
# Sticker management
705
guild.stickers # All guild stickers
706
sticker = await guild.fetch_sticker(sticker_id)
707
stickers = await guild.fetch_stickers()
708
709
# Create sticker
710
from nextcord import File
711
712
sticker_file = File("sticker.png", filename="sticker.png")
713
sticker = await guild.create_sticker(
714
name="custom_sticker",
715
description="Custom guild sticker",
716
emoji="π", # Related emoji
717
file=sticker_file,
718
reason="Adding custom sticker"
719
)
720
721
# Delete sticker
722
await guild.delete_sticker(sticker, reason="Removing sticker")
723
```
724
725
### Mention Parsing { .api }
726
727
```python
728
# Parse mentions in text
729
text = "Hello <@123456789> and <@&987654321> in <#555666777>!"
730
731
mentioned_users = guild.parse_mentions(text) # List of Member/User objects
732
mentioned_roles = guild.parse_role_mentions(text) # List of Role objects
733
mentioned_channels = guild.parse_channel_mentions(text) # List of Channel objects
734
735
# Get raw IDs
736
from nextcord import utils
737
user_ids = utils.parse_raw_mentions(text)
738
role_ids = utils.parse_raw_role_mentions(text)
739
channel_ids = utils.parse_raw_channel_mentions(text)
740
```
741
742
### Guild Lifecycle Management { .api }
743
744
```python
745
# Leave guild (cannot leave if owner)
746
await guild.leave()
747
748
# Delete guild (owner only)
749
await guild.delete()
750
751
# Guild information
752
print(f"Created at: {guild.created_at}")
753
print(f"Shard ID: {guild.shard_id}")
754
print(f"Is large: {guild.large}")
755
print(f"Invites disabled: {guild.invites_disabled}")
756
```
757
758
## Usage Examples
759
760
### Complete Server Setup { .api }
761
762
```python
763
async def setup_new_guild(guild: Guild):
764
"""Complete setup for a new guild"""
765
766
# 1. Configure basic settings
767
await guild.edit(
768
name="My Community Server",
769
description="A friendly community server",
770
verification_level=nextcord.VerificationLevel.medium,
771
explicit_content_filter=nextcord.ContentFilter.members_without_roles,
772
default_notifications=nextcord.NotificationLevel.only_mentions
773
)
774
775
# 2. Create role hierarchy
776
admin_role = await guild.create_role(
777
name="Admin",
778
permissions=nextcord.Permissions.all(),
779
colour=nextcord.Colour.red(),
780
hoist=True,
781
mentionable=True
782
)
783
784
mod_role = await guild.create_role(
785
name="Moderator",
786
permissions=nextcord.Permissions(
787
kick_members=True,
788
ban_members=True,
789
manage_messages=True
790
),
791
colour=nextcord.Colour.blue(),
792
hoist=True
793
)
794
795
# 3. Create channel structure
796
general_category = await guild.create_category("General")
797
798
await guild.create_text_channel(
799
"rules",
800
category=general_category,
801
topic="Server rules and guidelines",
802
position=0
803
)
804
805
await guild.create_text_channel(
806
"general",
807
category=general_category,
808
topic="General discussion"
809
)
810
811
voice_category = await guild.create_category("Voice")
812
await guild.create_voice_channel(
813
"General Voice",
814
category=voice_category
815
)
816
817
# 4. Set up auto moderation
818
await guild.create_auto_moderation_rule(
819
name="Spam Protection",
820
event_type=nextcord.AutoModerationEventType.message_send,
821
trigger_type=nextcord.AutoModerationTriggerType.mention_spam,
822
actions=[
823
nextcord.AutoModerationAction(
824
type=nextcord.AutoModerationActionType.block_message
825
)
826
],
827
trigger_metadata=nextcord.AutoModerationTriggerMetadata(
828
mention_total_limit=5
829
),
830
enabled=True,
831
exempt_roles=[admin_role, mod_role]
832
)
833
```
834
835
### Member Onboarding System { .api }
836
837
```python
838
@client.event
839
async def on_member_join(member: Member):
840
"""Handle new member joining"""
841
guild = member.guild
842
843
# Send welcome message
844
welcome_channel = guild.get_channel(WELCOME_CHANNEL_ID)
845
if welcome_channel:
846
embed = nextcord.Embed(
847
title=f"Welcome {member.display_name}!",
848
description=f"Welcome to {guild.name}! Please read the rules.",
849
colour=nextcord.Colour.green()
850
)
851
embed.set_thumbnail(url=member.avatar.url)
852
await welcome_channel.send(embed=embed)
853
854
# Assign default role
855
default_role = guild.get_role(DEFAULT_ROLE_ID)
856
if default_role:
857
await member.add_roles(default_role, reason="New member default role")
858
859
# Log join in audit channel
860
audit_channel = guild.get_channel(AUDIT_CHANNEL_ID)
861
if audit_channel:
862
await audit_channel.send(
863
f"π₯ {member.mention} joined the server. "
864
f"Account created: {member.created_at.strftime('%Y-%m-%d')}"
865
)
866
```
867
868
### Comprehensive Moderation System { .api }
869
870
```python
871
class ModerationSystem:
872
def __init__(self, guild: Guild):
873
self.guild = guild
874
875
async def warn_member(self, member: Member, reason: str, moderator: Member):
876
"""Warn a member with logging"""
877
# Log to database (implement your own storage)
878
await self.log_warning(member.id, reason, moderator.id)
879
880
# Notify member
881
try:
882
await member.send(f"You received a warning in {self.guild.name}: {reason}")
883
except:
884
pass # DMs disabled
885
886
# Log in moderation channel
887
mod_channel = self.guild.get_channel(MOD_LOG_CHANNEL)
888
if mod_channel:
889
embed = nextcord.Embed(
890
title="Member Warned",
891
colour=nextcord.Colour.yellow()
892
)
893
embed.add_field(name="Member", value=member.mention)
894
embed.add_field(name="Moderator", value=moderator.mention)
895
embed.add_field(name="Reason", value=reason, inline=False)
896
await mod_channel.send(embed=embed)
897
898
async def timeout_member(self, member: Member, duration: int, reason: str):
899
"""Timeout a member"""
900
import datetime
901
902
await member.timeout_for(
903
datetime.timedelta(seconds=duration),
904
reason=reason
905
)
906
907
# Log timeout
908
mod_channel = self.guild.get_channel(MOD_LOG_CHANNEL)
909
if mod_channel:
910
embed = nextcord.Embed(
911
title="Member Timed Out",
912
colour=nextcord.Colour.orange()
913
)
914
embed.add_field(name="Member", value=member.mention)
915
embed.add_field(name="Duration", value=f"{duration} seconds")
916
embed.add_field(name="Reason", value=reason, inline=False)
917
await mod_channel.send(embed=embed)
918
919
async def ban_member(self, member: Member, reason: str, delete_days: int = 1):
920
"""Ban a member with full logging"""
921
await self.guild.ban(
922
member,
923
reason=reason,
924
delete_message_seconds=delete_days * 24 * 60 * 60
925
)
926
927
# Log ban
928
mod_channel = self.guild.get_channel(MOD_LOG_CHANNEL)
929
if mod_channel:
930
embed = nextcord.Embed(
931
title="Member Banned",
932
colour=nextcord.Colour.red()
933
)
934
embed.add_field(name="Member", value=f"{member} ({member.id})")
935
embed.add_field(name="Reason", value=reason, inline=False)
936
embed.add_field(name="Messages Deleted", value=f"{delete_days} days")
937
await mod_channel.send(embed=embed)
938
```
939
940
This comprehensive documentation covers all major aspects of nextcord's Guild and server management capabilities, providing both API reference information and practical usage examples for building Discord bots with advanced server management features.