-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
518 lines (428 loc) · 19.1 KB
/
main.py
File metadata and controls
518 lines (428 loc) · 19.1 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
import os
import sys
import json
import discord
from discord import app_commands
from dotenv import load_dotenv
load_dotenv()
# ── Konfiguracja ────────────────────────────────────────────────────────────
TOKEN = os.environ.get('DISCORD_TOKEN')
if not TOKEN:
print('Błąd: DISCORD_TOKEN nie jest ustawiony.')
sys.exit(1)
GUILD_ID = int(os.environ.get('GUILD_ID', '0'))
WELCOME_CHANNEL_ID = int(os.environ.get('WELCOME_CHANNEL_ID', '0'))
ROLE_CHANNEL_ID = int(os.environ.get('ROLE_CHANNEL_ID', '0'))
ROLE_MESSAGE_ID_TEAMS = int(os.environ.get('ROLE_MESSAGE_ID_TEAMS', '0'))
ROLE_MESSAGE_ID_FIELDS = int(os.environ.get('ROLE_MESSAGE_ID_FIELDS', '0'))
ADMIN_ROLE_ID = int(os.environ.get('ADMIN_ROLE_ID', '0'))
# Statyczne role w dziedzinie
EMOJI_TO_ROLE_FIELDS = {
'🧬': int(os.environ.get('ROLE_NEUROINFORMATIKA', '0')),
'🔬': int(os.environ.get('ROLE_RESEARCH', '0')),
'👨⚕️': int(os.environ.get('ROLE_LEKARZ', '0')),
'💡': int(os.environ.get('ROLE_INZYNIERIA', '0')),
'🎨': int(os.environ.get('ROLE_DESIGN', '0')),
}
KN_CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'kn_config.json')
# ────────────────────────────────────────────────────────────────────────────
# ── Konfiguracja KN ─────────────────────────────────────────────────────────
# Format kn_config:
# {
# "<emoji>": {
# "name": "Solvro",
# "role_id": 123456789,
# "channel_id": 987654321 # 0 jeśli brak kanału
# }
# }
def load_kn_config() -> dict:
if os.path.exists(KN_CONFIG_FILE):
try:
with open(KN_CONFIG_FILE, encoding='utf-8') as f:
data = json.load(f)
# Migracja starego formatu {emoji: role_id (int)}
migrated = False
for key, val in data.items():
if isinstance(val, (int, str)) and str(val).isdigit():
data[key] = {'name': key, 'role_id': int(val), 'channel_id': 0}
migrated = True
if migrated:
_write_json(data)
print('🔧 Migracja kn_config.json do nowego formatu zakończona')
return data
except Exception as e:
print(f'⚠️ Błąd wczytywania kn_config.json: {e}')
return {}
def _write_json(data: dict) -> None:
with open(KN_CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def save_kn_config(config: dict) -> None:
_write_json(config)
def get_role_id(entry) -> int:
"""Zwróć role_id niezależnie od formatu wpisu."""
if isinstance(entry, dict):
return int(entry.get('role_id', 0))
return int(entry)
def get_channel_id(entry) -> int:
if isinstance(entry, dict):
return int(entry.get('channel_id', 0))
return 0
# ────────────────────────────────────────────────────────────────────────────
# ── Bot ─────────────────────────────────────────────────────────────────────
intents = discord.Intents.default()
intents.members = True
intents.reactions = True
intents.message_content = True
class NeuroMeetBot(discord.Client):
def __init__(self):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
self.kn_config: dict = load_kn_config()
async def setup_hook(self):
if GUILD_ID:
guild_obj = discord.Object(id=GUILD_ID)
self.tree.copy_global_to(guild=guild_obj)
await self.tree.sync(guild=guild_obj)
print(f'🔧 Slash commands zsynchronizowane z serwerem {GUILD_ID}')
else:
await self.tree.sync()
print('🔧 Slash commands zsynchronizowane globalnie')
def _get_guild(self, guild_id: int = 0) -> discord.Guild | None:
gid = guild_id or GUILD_ID
return self.get_guild(gid) if gid else None
async def update_teams_message(self) -> bool:
if not ROLE_MESSAGE_ID_TEAMS or not ROLE_CHANNEL_ID:
print('⚠️ ROLE_MESSAGE_ID_TEAMS lub ROLE_CHANNEL_ID nie ustawione w .env')
return False
channel = self.get_channel(ROLE_CHANNEL_ID)
if not channel:
return False
try:
msg = await channel.fetch_message(ROLE_MESSAGE_ID_TEAMS)
except discord.NotFound:
print(f'⚠️ Wiadomość {ROLE_MESSAGE_ID_TEAMS} nie istnieje')
return False
guild = channel.guild
lines = [
'🧠 **WYBIERZ SWOJE KOŁO NAUKOWE** 🧠',
'',
'Reaguj emoji poniżej, aby dołączyć do swojego KN.',
'Usunięcie reakcji = opuszczenie koła.',
'',
]
if self.kn_config:
for emoji, entry in self.kn_config.items():
if isinstance(entry, dict):
name = entry.get('name', emoji)
role_id = entry.get('role_id', 0)
else:
name = emoji
role_id = int(entry)
role = guild.get_role(role_id) if role_id else None
display = role.mention if role else name
lines.append(f'{emoji} — {display}')
else:
lines.append('*(brak kół naukowych — admin może je dodać przez /kn_create)*')
await msg.edit(content='\n'.join(lines))
# Synchronizuj reakcje
current = {str(r.emoji) for r in msg.reactions}
wanted = set(self.kn_config.keys())
for emoji in current - wanted:
try:
await msg.clear_reaction(emoji)
except Exception:
pass
for emoji in wanted - current:
try:
await msg.add_reaction(emoji)
except discord.HTTPException as e:
print(f'⚠️ Nie można dodać reakcji {emoji}: {e}')
print(f'🔄 Wiadomość KN zaktualizowana ({len(self.kn_config)} kół)')
return True
client = NeuroMeetBot()
# ── Sprawdzenie uprawnień ────────────────────────────────────────────────────
def admin_check():
async def predicate(interaction: discord.Interaction) -> bool:
if ADMIN_ROLE_ID:
return any(r.id == ADMIN_ROLE_ID for r in interaction.user.roles)
return interaction.user.guild_permissions.administrator
return app_commands.check(predicate)
# ── Slash commands ────────────────────────────────────────────────────────────
@client.tree.command(
name='kn_create',
description='[Admin] Utwórz nowe KN: rolę + prywatny kanał + wpis w liście ról'
)
@admin_check()
@app_commands.describe(
name='Nazwa koła naukowego (np. Solvro)',
emoji='Emoji lub custom emoji dla reakcji (np. 🔷 lub <:solvro:123456789>)',
reference_role='Rola, od której zostaną skopiowane uprawnienia i poziom',
category='Kategoria Discord, w której zostanie utworzony kanał (opcjonalne)',
role_color='Kolor roli w formacie hex (np. #3498db) — opcjonalne',
)
async def kn_create(
interaction: discord.Interaction,
name: str,
emoji: str,
reference_role: discord.Role,
category: discord.CategoryChannel = None,
role_color: str = '',
):
await interaction.response.defer(ephemeral=True)
guild = interaction.guild
emoji = emoji.strip()
name = name.strip()
if not emoji or not name:
await interaction.followup.send('❌ Podaj nazwę i emoji.', ephemeral=True)
return
if emoji in client.kn_config:
await interaction.followup.send(
f'❌ Emoji {emoji} jest już używane. Użyj /kn_remove najpierw lub wybierz inne emoji.',
ephemeral=True,
)
return
steps = []
# 1. Kolor roli
color = reference_role.color
if role_color:
try:
color = discord.Color(int(role_color.lstrip('#'), 16))
except ValueError:
steps.append(f'⚠️ Nieprawidłowy kolor "{role_color}", użyto koloru reference_role')
# 2. Utwórz rolę
try:
new_role = await guild.create_role(
name=name,
permissions=reference_role.permissions,
color=color,
mentionable=True,
reason=f'/kn_create przez {interaction.user}',
)
steps.append(f'✅ Rola {new_role.mention} utworzona')
except discord.Forbidden:
await interaction.followup.send('❌ Bot nie ma uprawnień do tworzenia ról.', ephemeral=True)
return
except Exception as e:
await interaction.followup.send(f'❌ Błąd tworzenia roli: {e}', ephemeral=True)
return
# 3. Ustaw poziom roli (zaraz pod reference_role)
try:
positions = {new_role: max(1, reference_role.position)}
await guild.edit_role_positions(positions=positions)
steps.append(f'✅ Poziom roli ustawiony na {max(1, reference_role.position)}')
except Exception as e:
steps.append(f'⚠️ Nie udało się ustawić poziomu roli: {e}')
# 4. Utwórz kanał tekstowy
channel_name = name.lower().replace(' ', '-').replace('_', '-')
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
new_role: discord.PermissionOverwrite(
view_channel=True,
send_messages=True,
read_message_history=True,
attach_files=True,
embed_links=True,
),
guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True),
}
try:
new_channel = await guild.create_text_channel(
name=channel_name,
category=category,
overwrites=overwrites,
topic=f'Kanał koła naukowego {name}',
reason=f'/kn_create przez {interaction.user}',
)
steps.append(f'✅ Kanał {new_channel.mention} utworzony')
except discord.Forbidden:
await interaction.followup.send(
f'❌ Bot nie ma uprawnień do tworzenia kanałów.\n' + '\n'.join(steps),
ephemeral=True,
)
return
except Exception as e:
new_channel = None
steps.append(f'⚠️ Błąd tworzenia kanału: {e}')
# 5. Powiadomienie powitalne na kanale KN
if new_channel:
try:
await new_channel.send(
f'🎉 Witajcie w kanale **{name}**!\n'
f'Ten kanał jest widoczny tylko dla członków {new_role.mention}.\n'
f'Aby dołączyć, wybierz emoji {emoji} w kanale z rolami.'
)
except Exception:
pass
# 6. Zapisz do konfiguracji
client.kn_config[emoji] = {
'name': name,
'role_id': new_role.id,
'channel_id': new_channel.id if new_channel else 0,
}
save_kn_config(client.kn_config)
# 7. Zaktualizuj wiadomość z rolami
ok = await client.update_teams_message()
steps.append('✅ Wiadomość z rolami zaktualizowana' if ok else '⚠️ Nie udało się zaktualizować wiadomości')
summary = (
f'**KN {name}** zostało utworzone:\n\n'
+ '\n'.join(steps)
+ f'\n\n**Emoji reakcji:** {emoji}'
)
await interaction.followup.send(summary, ephemeral=True)
@client.tree.command(
name='kn_add',
description='[Admin] Podepnij istniejącą rolę i kanał jako KN (bez tworzenia nowych)'
)
@admin_check()
@app_commands.describe(
emoji='Emoji dla reakcji',
name='Wyświetlana nazwa KN',
role='Istniejąca rola Discord',
channel='Istniejący kanał Discord (opcjonalne)',
)
async def kn_add(
interaction: discord.Interaction,
emoji: str,
name: str,
role: discord.Role,
channel: discord.TextChannel = None,
):
await interaction.response.defer(ephemeral=True)
emoji = emoji.strip()
is_update = emoji in client.kn_config
client.kn_config[emoji] = {
'name': name.strip(),
'role_id': role.id,
'channel_id': channel.id if channel else 0,
}
save_kn_config(client.kn_config)
ok = await client.update_teams_message()
verb = 'Zaktualizowano' if is_update else 'Dodano'
status = '✅' if ok else '⚠️ (wiadomość nie zaktualizowana — sprawdź logi)'
ch_info = f' | Kanał: {channel.mention}' if channel else ''
await interaction.followup.send(
f'{status} {verb}: {emoji} → {role.mention}{ch_info}', ephemeral=True
)
@client.tree.command(name='kn_remove', description='[Admin] Usuń KN z listy ról (rola i kanał na serwerze pozostają)')
@admin_check()
@app_commands.describe(emoji='Emoji KN do usunięcia')
async def kn_remove(interaction: discord.Interaction, emoji: str):
await interaction.response.defer(ephemeral=True)
emoji = emoji.strip()
if emoji not in client.kn_config:
await interaction.followup.send(
f'❌ Nie znaleziono KN z emoji {emoji}. Sprawdź /kn_list.', ephemeral=True
)
return
entry = client.kn_config.pop(emoji)
save_kn_config(client.kn_config)
ok = await client.update_teams_message()
name = entry.get('name', emoji) if isinstance(entry, dict) else emoji
status = '✅' if ok else '⚠️ (wiadomość nie zaktualizowana)'
await interaction.followup.send(
f'{status} Usunięto **{name}** ({emoji}) z listy.\n'
f'Rola i kanał na serwerze **nie zostały usunięte** — zrób to ręcznie jeśli potrzebujesz.',
ephemeral=True,
)
@client.tree.command(name='kn_list', description='Pokaż listę wszystkich kół naukowych')
async def kn_list(interaction: discord.Interaction):
if not client.kn_config:
await interaction.response.send_message(
'📋 Brak kół naukowych. Admin może dodać przez `/kn_create`.', ephemeral=True
)
return
guild = interaction.guild
lines = ['📋 **Aktualne koła naukowe:**', '']
for emoji, entry in client.kn_config.items():
if isinstance(entry, dict):
name = entry.get('name', '?')
role_id = entry.get('role_id', 0)
channel_id = entry.get('channel_id', 0)
else:
name, role_id, channel_id = str(entry), int(entry), 0
role = guild.get_role(role_id) if role_id else None
channel = guild.get_channel(channel_id) if channel_id else None
role_str = role.mention if role else f'Rola {role_id}'
ch_str = f' → {channel.mention}' if channel else ''
lines.append(f'{emoji} **{name}** — {role_str}{ch_str}')
await interaction.response.send_message('\n'.join(lines), ephemeral=True)
@client.tree.command(name='kn_refresh', description='[Admin] Odśwież wiadomość i reakcje KN')
@admin_check()
async def kn_refresh(interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
ok = await client.update_teams_message()
msg = '✅ Wiadomość i reakcje odświeżone.' if ok else '❌ Nie udało się — sprawdź ROLE_MESSAGE_ID_TEAMS i ROLE_CHANNEL_ID w .env.'
await interaction.followup.send(msg, ephemeral=True)
# ── Eventy ────────────────────────────────────────────────────────────────────
@client.event
async def on_ready():
print(f'✅ Zalogowano jako {client.user} — NeuroMeet bot gotowy')
print(f'📋 Wczytano {len(client.kn_config)} kół naukowych')
@client.event
async def on_member_join(member: discord.Member):
channel = client.get_channel(WELCOME_CHANNEL_ID)
if channel:
await channel.send(
f'Witamy na serwerze NeuroMeet, {member.mention}! 🥳🧠🦾\n'
f'Wybierz role i zespół w kanale #🎭-wybierz-role'
)
@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
if payload.member and payload.member.bot:
return
is_teams = payload.message_id == ROLE_MESSAGE_ID_TEAMS
is_fields = payload.message_id == ROLE_MESSAGE_ID_FIELDS
if not is_teams and not is_fields:
return
guild = client.get_guild(payload.guild_id)
member = payload.member or (guild.get_member(payload.user_id) if guild else None)
if not guild or not member:
return
emoji_str = str(payload.emoji)
if is_teams:
entry = client.kn_config.get(emoji_str)
if not entry:
return
role_id = get_role_id(entry)
role = guild.get_role(role_id)
if role and member:
await member.add_roles(role)
kn_name = entry.get('name', emoji_str) if isinstance(entry, dict) else emoji_str
print(f'✅ [KN] Przydzielono "{kn_name}" → {member.name}')
elif is_fields:
role_id = EMOJI_TO_ROLE_FIELDS.get(emoji_str)
if role_id:
role = guild.get_role(role_id)
if role and member:
await member.add_roles(role)
print(f'✅ [Dziedzina] Przydzielono "{role.name}" → {member.name}')
@client.event
async def on_raw_reaction_remove(payload: discord.RawReactionActionEvent):
is_teams = payload.message_id == ROLE_MESSAGE_ID_TEAMS
is_fields = payload.message_id == ROLE_MESSAGE_ID_FIELDS
if not is_teams and not is_fields:
return
guild = client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id) if guild else None
if not guild or not member:
return
emoji_str = str(payload.emoji)
if is_teams:
entry = client.kn_config.get(emoji_str)
if not entry:
return
role_id = get_role_id(entry)
role = guild.get_role(role_id)
if role and member:
await member.remove_roles(role)
kn_name = entry.get('name', emoji_str) if isinstance(entry, dict) else emoji_str
print(f'❌ [KN] Usunięto "{kn_name}" od {member.name}')
elif is_fields:
role_id = EMOJI_TO_ROLE_FIELDS.get(emoji_str)
if role_id:
role = guild.get_role(role_id)
if role and member:
await member.remove_roles(role)
print(f'❌ [Dziedzina] Usunięto "{role.name}" od {member.name}')
# ── Start ─────────────────────────────────────────────────────────────────────
client.run(TOKEN)