discord-havoc/util/discord_helpers.py

59 lines
1.8 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
"""
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
"""
Get Channel by Name
2025-02-16 20:07:02 -05:00
2025-02-13 14:51:35 -05:00
Args:
bot (discord.Bot)
channel (str)
guild (int|None)
Returns:
Optional[Any]
"""
2025-02-15 08:36:45 -05:00
channel = re.sub(r'^#', '', channel.strip())
2025-02-13 14:51:35 -05:00
if not guild:
return discord.utils.get(bot.get_all_channels(),
name=channel)
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
async def send_message(bot: discord.Bot, channel: str,
message: str, guild: int | None = None) -> None:
"""
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-02-16 20:07:02 -05: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-02-15 08:36:45 -05:00
channel = re.sub(r'^#', '', channel.strip())
2025-02-13 14:51:35 -05:00
_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)