from typing import Tuple import discord from payphone.db import models async def get_channel(channel: discord.TextChannel) -> models.Channel: """Returns a channel from the database, creating or updating it if it already exists. Args: channel (discord.TextChannel): The channel to fetch. Returns: models.Channel: The channel row. """ row, _ = await models.Channel.update_or_create( id=channel.id, server=channel.guild.id ) channel_name = channel.name.replace("discord", "d").replace("wumpus", "w") webhook_name = f"Payphone #{channel_name}" if row.webhook_id is None: webhook = await channel.create_webhook( name=webhook_name, reason="First call started in channel." ) row.webhook_id = webhook.id row.webhook_url = webhook.url await row.save(update_fields=["webhook_id", "webhook_url"]) else: found = False for webhook in await channel.webhooks(): if webhook.id != row.webhook_id: if webhook.token is None: await webhook.delete(reason="Webhook is unaccessible by Payphone.") break else: found = True if not found: webhook = await channel.create_webhook( name=webhook_name, reason="Previous webhook was deleted." ) row.webhook_id = webhook.id row.webhook_url = webhook.url await row.save(update_fields=["webhook_id", "webhook_url"]) return row async def get_user( user: discord.User | discord.Member, ) -> Tuple[models.User, models.Profile]: """Returns a user from the database, creating or updating it if it already exists. Args: user (discord.User | discord.Member): The user or member to fetch. Returns: Tuple[models.User, models.Profile]: The user and profile. """ user_row, _ = await models.User.update_or_create( {"username": user.name}, id=user.id ) # TODO: Make per-server profiles a premium feature. profile_row, _ = await models.Profile.update_or_create( { "avatar_url": user.display_avatar.url, "name": user.global_name or user.name, }, user=user_row, server_id=None, # user.guild.id if isinstance(user, discord.Member) else None, ) return (user_row, profile_row)