bot.py (view raw)
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 |
import discord
import discord.ext.commands
import asyncio
from utils import nameof
import emoji
import sys
import bot_token
import db as database
# ======================== STARTUP =========================== #
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
role_converter = discord.ext.commands.RoleConverter()
member_converter = discord.ext.commands.MemberConverter()
# ======================= INITIALIZATION ========================== #
@bot.event
async def on_ready():
print(f'LOG: bot has logged in as {bot.user}')
@bot.listen()
async def on_guild_join(guild):
db = await init_db(guild, guild=guild)
print(f"LOG: guild {guild} joined")
# ====================== DB INIT ========================= #
async def init_db(ctx, guild=None) -> database.Database:
if guild:
db = database.Database(f"{guild.id}.db")
else:
db = database.Database(f"{ctx.guild.id}.db")
await db.initial_setup()
return db
# ======================== ERROR HANDLING ============================= #
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
async def dm(ctx, message: str, err):
user = await bot.fetch_user(621759962280099840)
if user:
messageDraft = message
if err is not None:
messageDraft += "\n```{err}```"
try:
await user.send(messageDraft)
await ctx.send("Der Entwickler wurde kontaktiert und wird sich sobald wie möglich darum kümmern")
except discord.Forbidden:
eprint(f"{ctx.guild.id} | ERROR: Can't DM user")
await ctx.send("Bitte kontaktiere die Serverleitung")
else:
eprint(f"{ctx.guild.id} | ERROR: Can't find user to DM")
await ctx.send("Bitte kontaktiere die Serverleitung")
async def error(ctx, message: str, err=None):
decoratedMessage = f"{ctx.guild.id} | ERROR: {message}\n{err}"
eprint(decoratedMessage)
await dm(ctx, decoratedMessage, err=err)
await ctx.send(":x: Interner Fehler")
async def log(ctx, message: str):
decoratedMessage = f"{ctx.guild.id} | LOG: {message}"
print(decoratedMessage)
async def is_admin(ctx):
if not ctx.author.guild_permissions.administrator:
ctx.respond(
":x: Du musst Administrator sein, um diesen Command auszuführen")
return False
else:
return True
# ======================= SETUP ========================= #
@bot.slash_command(description="Gibt alle Commands zurück, die für die Initialisation des Bots nötig sind")
async def setup(ctx):
if await is_admin(ctx) is False:
return
db = await init_db(ctx)
await db.initial_setup()
ids = await db.get_discord_ids()
#print(ids)
checks = []
for id in ids:
if id[2] is None:
checks.append("❌")
else:
checks.append("✅")
await ctx.respond(
f"{checks[0]
} Setze die Booster Rolle mit `/{nameof(setze_booster_rolle)[0]}`\n"
f"{checks[1]} Setze den Verteiler Channel mit `/{
nameof(setze_verteiler_channel)[0]}`\n"
f"{checks[2]} Setze die Kategorie, in der die Clubs erstellt werden sollen mit `/{
nameof(setze_club_kategorie)[0]}`\n"
f"{checks[3]} Setze die Rolle, welche als Clubrollenheader dient mit `/{
nameof(setze_clubrollenheader_rolle)[0]}`"
)
return
@bot.slash_command(description="Setzt die Booster Rolle intern im Bot")
async def setze_booster_rolle(ctx, booster_rolle):
if await is_admin(ctx) is False:
return
db = await init_db(ctx)
# [3:-1] to remove @<> around role ping
err = await db.add_id("booster_role_id", booster_rolle[3:-1])
if err:
await error(ctx, "Set-Booster-Role: DB error", err)
return
await ctx.respond("✅ Booster Rolle registriert")
await log(ctx, f"{ctx.author} added {booster_rolle} as booster role")
return
@bot.slash_command(description="Setzt den Verteiler Channel intern im Bot")
async def setze_verteiler_channel(ctx, verteiler_channel_id):
if await is_admin(ctx) is False:
return
db = await init_db(ctx)
err = await db.add_id("distributor_channel_id", verteiler_channel_id)
if err:
await error(ctx, "Set-Distributor-Channel: DB error", err)
return
await ctx.respond("✅ Verteiler Channel registriert")
await log(ctx, f"{ctx.author} added {verteiler_channel_id} as distributor channel id")
return
@bot.slash_command(description="Setzt die Kategorie, in der die Clubs erstellt werden sollen")
async def setze_club_kategorie(ctx, kategorie_id):
if await is_admin(ctx) is False:
return
db = await init_db(ctx)
err = await db.add_id("new_channel_category_id", kategorie_id)
if err:
await error(ctx, "Set-New-Channel-Category: DB error", err)
return
await ctx.respond("✅ Club Kategorie regisitriert")
await log(ctx, f"{ctx.author} added {kategorie_id} as booster role")
@bot.slash_command(description="Setzt die Rolle für den Clubrollen-Header")
async def setze_clubrollenheader_rolle(ctx, clubrollenheader_rolle: str):
if await is_admin(ctx) is False:
return
clubrollenheader_rolle = clubrollenheader_rolle.strip()
db = await init_db(ctx)
err = await db.add_id("club_role_header_role_id", int(clubrollenheader_rolle[3:-1]))
if err is not None:
await error(ctx, "Database error when adding club role header role id", err)
return
await ctx.respond(f"✅ Clubrollenheader {clubrollenheader_rolle} registriert")
"""
@bot.slash_command()
async def get_existing_roles(ctx):
results = ctx.guild.roles
print(results)
"""
@bot.slash_command()
async def test(ctx):
await ctx.guild.create_role(name="hi", color=int("0x"+("#5460D9"[1:]), 16)+0x200, mentionable=False)
await ctx.respond("hi")
# ======================== ADD CLUB ================================ #
async def check_club_parameters(ctx, db: database.Database, channelName="", channelEmoji="", roleName="", roleColor=""):
if channelEmoji != "":
if len(channelEmoji) != 1:
await ctx.respond(
"❌ Error! Das Emoji-Feld darf nicht länger oder kürzer als 1 sein")
return
if emoji.is_emoji(channelEmoji) is not True:
await ctx.respond(
"❌ Error! Das Emoji-Feld muss mit einem Emoji gefüllt werden")
return
if channelName != "":
if emoji.emoji_count(channelName) > 0:
await ctx.respond("❌ Error! Der Kanalname darf keine Emojis enthalten")
return
combined_channel_name = f"「{channelEmoji}」{channelName}"
existing_club = await db.select_club_by_channel_name(combined_channel_name)
if existing_club is not None:
await ctx.respond(
"❌ Error! Es gibt bereits einen Club mit diesem Kanalnamen")
return
if roleName != "":
existing_club_role = await db.select_club_by_role_name(roleName)
if existing_club_role is not None:
ctx.respond(
"❌ Error! Es existiert bereits ein Club mit diesem Rollennamen")
return
if roleColor != "":
if roleColor[0] == '#':
roleColor = roleColor[1:]
try:
roleColor = int("0x"+roleColor, 16)
except:
return ("❌ Error! Farbformat falsch angegeben")
return (roleName, roleColor)
@bot.slash_command(description="Erstellt einen Booster Club")
async def club_erstellen(ctx, kanalname, kanalemoji, rollenname, rollenfarbe):
db = await init_db(ctx)
kanalemoji = kanalemoji.strip()
boosterRoleId = await db.get_booster_role_id()
if boosterRoleId is None:
await error(ctx, "Role-Creation: No booster role id foundin DB")
return
if ctx.author.get_role(boosterRoleId) is None:
await ctx.respond(":x: Du bist kein Booster")
return
if await db.select_role_id_by_owner(ctx.author.id) is not None:
await ctx.respond("❌ Error! Du hast bereits einen Club")
return
check_return = await check_club_parameters(ctx, db, kanalname, kanalemoji, rollenname, rollenfarbe)
if check_return is not None:
roleName, roleColor = check_return
createdRole = await ctx.guild.create_role(name=roleName, color=roleColor, mentionable=False)
if createdRole is None:
await error(ctx, "Role-Creation: Couldn't create role on discord")
return
err = await db.create_club(f"「{kanalemoji}」{kanalname}", ctx.author.id, createdRole.id, roleName)
if err:
await error(ctx, "Role-Creation: Couldn't create new role in DB", err)
return
await log(ctx, f"club {kanalname} created by {ctx.author}")
await ctx.author.add_roles(createdRole)
await db.add_member(ctx.author.id, ctx.author.id)
await log(ctx, f"Role {createdRole} added to {ctx.author}")
await ctx.respond(f"✅ Club `「{kanalemoji}」{kanalname}` erstellt!")
# ==================== EDIT CLUBS ====================== #
@bot.slash_command(description="Ändern eines Paramaters seines Clubs")
async def club_editieren(ctx, kanalname="", kanalemoji="", rollenname="", rollenfarbe=""):
db = await init_db(ctx)
owner_id = ctx.author.id
if type(await db.select_role_id_by_owner(owner_id)) != int:
ctx.respond(f":x: Du besitzt keinen Club")
if kanalname != "":
channel_name = await db.get_channel_name_by_owner(ctx.author.id)
check_return = await check_club_parameters(ctx, db, channelName=kanalname, channelEmoji=channel_name[:3])
if check_return == None:
return
response = await db.club_edit(owner_id, "channel_name", channel_name[:3]+kanalname)
if kanalemoji != "":
channel_name = await db.get_channel_name_by_owner(ctx.author.id)
check_return = await check_club_parameters(ctx, db, channelName=channel_name[3:], channelEmoji=kanalemoji)
if check_return == None:
return
response = await db.club_edit(owner_id, "channel_name", f"「{kanalemoji}」{channel_name[3:]}")
if rollenname != "" or rollenfarbe != "":
check_return = await check_club_parameters(ctx, db, roleName=rollenname, roleColor=rollenfarbe)
if check_return == None:
return
club_role_id = await db.select_role_id_by_owner(owner_id)
role = discord.utils.get(ctx.guild.roles, id=club_role_id)
# Check if the role exists
if role is None:
await error(ctx, f"Club-Edit: Role {club_role_id} could not be found")
return
# Attempt to edit the role
try:
if rollenname != "":
if rollenfarbe != "":
await role.edit(name=check_return[0], colour=check_return[1])
else:
await role.edit(name=check_return[0])
else:
await role.edit(colour=check_return[1])
await ctx.respond(f":white_check_mark: Rolle {role.name} geupdated")
await log(ctx, f"role '{role.name}' has been edited by {ctx.author}")
except discord.Forbidden:
await error(ctx, f"Club-Edit: No permission to edit role ({club_role_id})")
return
except discord.HTTPException as e:
await error(ctx, "Club-Edit: Error when editing role", e)
return
if check_return[0] != "":
response = await db.club_edit(owner_id, "role_name", check_return[0])
if response != None:
await error(ctx, "Error, editing club", response)
else:
await ctx.respond(f"✅ Club editiert!")
# ========================= dsfsf ======================= #
async def add_header_role(ctx):
pass
@bot.slash_command(description="Fügt Member zu eigenem Club hinzu")
async def mitglied_hinzufuegen(ctx, member):
db = await init_db(ctx)
response = await db.add_member(member[2:-1], ctx.author.id)
if response is not None:
await ctx.respond(response)
return
member = await member_converter.convert(ctx, member)
response = await db.select_role_id_by_owner(ctx.author.id)
if response is None:
await ctx.respond(":x: Du hast keinen Club")
return
role = discord.utils.get(ctx.guild.roles, id=response)
await member.add_roles(role)
await ctx.respond(":white_check_mark:")
await log(ctx, f"Added {member} to {role}")
# this decorator makes a slash command
@bot.command(description="Sends the bot's latency.")
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")
# ==================== distributor vc ======================= #
async def send_club_list(ctx, user, db_response):
clubs = ""
for i in range(len(db_response)):
# create a new numbered line for every club
clubs += f"\n**{i+1}.** {db_response[i][0]}"
if clubs.strip() == "":
# if no clubs
await ctx.send(f":x: {user.name}, du bist in keinen Clubs")
return
else:
await ctx.send(f" {user.name}, welchen Club-Kanal willst du öffnen?" + clubs)
async def get_and_check_user_response(ctx, user, db_response):
def check(m):
return m.author == user and m.channel == ctx
cycle = 1
while cycle <= 3:
try:
response = await bot.wait_for('message', check=check, timeout=30.0)
except asyncio.TimeoutError:
await ctx.send(":x: Zu spät (joine dem Kanal noch einmal, um die Dialogauswahl wieder zu erhalten)")
return
else:
try:
int(response.content)
except ValueError:
await ctx.send(":x: Konnte nicht in ganze Zahl umwandeln")
continue
if int(response.content) > len(db_response) or int(response.content) <= 0:
await ctx.send(":x: Nicht zulässige Zahl")
else:
return response
cycle += 1
await ctx.send(
":x: Zu viele Versuche, trete dem Channel erneut bei, um noch einmal auszuwählen")
return None
async def gather_arguments_for_channel_creation(ctx, db, db_response, userResponse):
channel_name = db_response[int(userResponse.content)-1][0]
new_channel_category_id = await db.get_discord_id("new_channel_category_id")
category = discord.utils.get(
ctx.guild.categories, id=new_channel_category_id)
if category is None:
await error(ctx, f"Distributor-Channel: Can't find new channel category ({new_channel_category_id}) on Discord")
roleId = db_response[int(userResponse.content)-1][1]
role = discord.utils.get(ctx.guild.roles, id=roleId)
if role is None:
await error(ctx, f"Distributor-Channel: Can't find club role ({roleId}) on Discord")
bot_member = ctx.guild.me
clubOwnerId = await db.get_owner_by_club_id(db_response[int(userResponse.content)-1][2])
club_owner = discord.utils.get(ctx.guild.members, id=clubOwnerId)
if club_owner is None:
await error(ctx, f"Distributor-Channel: Can't find club owner ({clubOwnerId}) on Discord")
return (channel_name, category, role, bot_member, club_owner)
async def create_permission_overwrites(ctx, role, bot_member, club_owner):
bot_overwrites = discord.PermissionOverwrite(
move_members=True,
view_channel=True,
manage_channels=True
)
club_member_overwrites = discord.PermissionOverwrite(
view_channel=True
)
club_owner_overwrites = discord.PermissionOverwrite(
manage_channels=True,
mute_members=True,
deafen_members=True,
move_members=True
)
default_overwrites = discord.PermissionOverwrite(
view_channel=False
)
overwrites = {
ctx.guild.default_role: default_overwrites,
bot_member: bot_overwrites,
club_owner: club_owner_overwrites,
role: club_member_overwrites
}
return overwrites
async def distributor_channel(user, after, db):
ctx = after.channel # ctx is distributor channel
await log(ctx, f"{user.name} joined distributor channel {ctx.name}")
db_response = await db.get_channel_name_role_name_by_member(user.id)
await send_club_list(ctx, user, db_response)
userResponse = await get_and_check_user_response(ctx, user, db_response)
if userResponse is None:
return
channel_name, category, role, bot_member, club_owner = await gather_arguments_for_channel_creation(ctx, db, db_response, userResponse)
overwrites = await create_permission_overwrites(ctx, role, bot_member, club_owner)
voice_channel = await category.create_voice_channel(
name=channel_name,
overwrites=overwrites
)
await log(ctx, f"New channel {voice_channel} created")
distributor_vcs.append(voice_channel.id)
await log(ctx, f"The List of existing club channels is now: {distributor_vcs}")
if user.voice:
await user.move_to(voice_channel)
await log(ctx, f"Moved {user} into {voice_channel}")
distributor_vcs = []
@bot.event
async def on_voice_state_update(user, before, after):
if before.channel != after.channel: # actually moved channels in some way
if after.channel: # moved and didn't leave
db = await init_db(after.channel)
if after.channel.id == await db.get_discord_id("distributor_channel_id"):
await distributor_channel(user, after, db)
# if old channel exists and is a distributor vc
if before.channel and before.channel.id in distributor_vcs:
if len(before.channel.members) == 0:
await before.channel.delete(reason="Niemand ist mehr verbunden")
distributor_vcs.remove(before.channel.id)
await log(before.channel, f"Deleted {before.channel} because it was empty")
@bot.slash_command(description="Löscht eigenen Club")
async def club_löschen(ctx, owner=None):
db = database.Database(f"{ctx.guild.id}.db")
if owner is None:
owner = ctx.author.id
else:
owner = owner[2:-1]
club_role_id = await db.select_role_id_by_owner(owner)
if club_role_id is None:
await ctx.respond(":x: Der angegebene Benutzer besitzt keinen Club")
return
#TODO: db should only be updated once role deletion is successful
err = await db.delete_club(owner)
if err is not None:
await error(ctx, "Club-Deletion: Club from {owner} could not be deleted from the db", err)
return
else:
await log(ctx, f"club from {owner} has been deleted from the db")
role = discord.utils.get(ctx.guild.roles, id=club_role_id)
# Check if the role exists
if role is None:
await error(ctx, f"Club-Deletion: Role {club_role_id} could not be found")
return
# Attempt to delete the role
try:
await role.delete()
await ctx.respond(f":white_check_mark: Rolle {role.name} und Club von <@{owner}> wurden gelöscht")
await log(ctx, f"role '{role.name}' has been deleted by {ctx.author}")
except discord.Forbidden:
await error(ctx, f"Club-Deletion: No permission to delete role ({club_role_id})")
return
except discord.HTTPException as e:
await error(ctx, "Club-Deletion: Error when deleting role", e)
return
bot.run(bot_token.token)
|