discord-havoc/util/discord_helpers.py

61 lines
1.7 KiB
Python
Raw Normal View History

2025-02-13 14:51:35 -05:00
import re
import discord
from typing import Optional, Any
"""
Discord Helper Methods
"""
2025-04-17 14:35:56 -04:00
async def get_channel_by_name(
bot: discord.Bot, channel: str, guild: int | None = None
) -> Optional[Any]: # Optional[Any] used as pycord channel types can be ambigious
2025-02-13 14:51:35 -05:00
"""
Get Channel by Name
2025-04-17 14:35:56 -04:00
2025-02-13 14:51:35 -05:00
Args:
bot (discord.Bot)
channel (str)
guild (int|None)
Returns:
Optional[Any]
"""
2025-04-17 14:35:56 -04:00
channel = re.sub(r"^#", "", channel.strip())
2025-02-13 14:51:35 -05:00
if not guild:
2025-04-17 14:35:56 -04:00
return discord.utils.get(bot.get_all_channels(), name=channel)
2025-02-13 14:51:35 -05:00
else:
2025-02-15 08:36:45 -05:00
_guild: Optional[discord.Guild] = bot.get_guild(guild)
if not _guild:
return None
channels: list = _guild.channels
2025-02-13 14:51:35 -05:00
for _channel in channels:
if _channel.name.lower() == channel.lower().strip():
return _channel
2025-02-15 08:36:45 -05:00
return None
2025-02-13 14:51:35 -05:00
2025-04-17 14:35:56 -04:00
async def send_message(
bot: discord.Bot, channel: str, message: str, guild: int | None = None
) -> None:
2025-02-13 14:51:35 -05:00
"""
Send Message to the provided channel. If guild is provided, will limit to channels within that guild to ensure the correct
channel is selected. Useful in the event a channel exists in more than one guild that the bot resides in.
2025-04-17 14:35:56 -04:00
2025-02-13 14:51:35 -05:00
Args:
bot (discord.Bot)
channel (str)
message (str)
guild (int|None)
Returns:
None
"""
if channel.isnumeric():
2025-02-15 08:36:45 -05:00
channel_int: int = int(channel)
_channel = bot.get_channel(channel_int)
2025-02-13 14:51:35 -05:00
else:
2025-04-17 14:35:56 -04:00
channel = re.sub(r"^#", "", channel.strip())
_channel = await get_channel_by_name(bot=bot, channel=channel, guild=guild)
2025-02-15 08:36:45 -05:00
if not isinstance(_channel, discord.TextChannel):
return None
2025-02-13 14:51:35 -05:00
await _channel.send(message)