async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Discord from a config entry.""" nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() try: await discord_bot.login(entry.data[CONF_API_TOKEN]) except nextcord.LoginFailure as ex: raise ConfigEntryAuthFailed("Invalid token given") from ex except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound) as ex: raise ConfigEntryNotReady("Failed to connect") from ex finally: await discord_bot.close() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = entry.data hass.async_create_task( discovery.async_load_platform( hass, Platform.NOTIFY, DOMAIN, hass.data[DOMAIN][entry.entry_id], hass.data[DOMAIN], )) return True
async def _async_try_connect( token: str) -> tuple[str | None, nextcord.AppInfo | None]: """Try connecting to Discord.""" discord_bot = nextcord.Client() try: await discord_bot.login(token) info = await discord_bot.application_info() except nextcord.LoginFailure: return "invalid_auth", None except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound): return "cannot_connect", None except Exception as ex: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception: %s", ex) return "unknown", None await discord_bot.close() return None, info
#!/usr/bin/python3 import sys import os import nextcord import asyncio import random import logging import json logging.basicConfig(level=logging.INFO) client = nextcord.Client() #wb = gspread.authorize("token_google").open_by_key('1v-MzfsOmmCQNwWFHl86UVrf3lIm5QPitRiJeA4ISIPw') #wb = wb.get_worksheet(0) global word word = [] @client.event async def on_ready(): print("Connected") @client.event async def on_message(m): global word av = m.content.split(' ') if av[0] == "/add" : word.append(" ".join(av[1:])) if av[0] == "/pick" : mot = random.choice(word) word.remove(mot)
logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w") handler.setFormatter( logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s") ) logger.addHandler(handler) # Enable intents god damn it discord intents = nextcord.Intents.default() intents.members = True # Reduce noise intents.typing = False allowed_mentions = nextcord.AllowedMentions(everyone=False, users=True, roles=True) client = nextcord.Client(intents=intents, allowed_mentions=allowed_mentions) bot = None bot_replies = {} to_delete = {} with open("plugin_data/twemoji_800x800.json") as f: emojis = json.load(f) raw_msg_cache = {} # message cache that we use to map msg_id to msg # TODO plp # slash commands # 1. Move all print statements to a logger # 2. Handle slash message timeouts class Init:
async def async_send_message(self, message: str, **kwargs: Any) -> None: """Login to Discord, send message to channel(s) and log out.""" nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() images = None embedding = None if ATTR_TARGET not in kwargs: _LOGGER.error("No target specified") return None data = kwargs.get(ATTR_DATA) or {} embeds: list[nextcord.Embed] = [] if ATTR_EMBED in data: embedding = data[ATTR_EMBED] title = embedding.get(ATTR_EMBED_TITLE) or nextcord.Embed.Empty description = embedding.get( ATTR_EMBED_DESCRIPTION) or nextcord.Embed.Empty color = embedding.get(ATTR_EMBED_COLOR) or nextcord.Embed.Empty url = embedding.get(ATTR_EMBED_URL) or nextcord.Embed.Empty fields = embedding.get(ATTR_EMBED_FIELDS) or [] if embedding: embed = nextcord.Embed(title=title, description=description, color=color, url=url) for field in fields: embed.add_field(**field) if ATTR_EMBED_FOOTER in embedding: embed.set_footer(**embedding[ATTR_EMBED_FOOTER]) if ATTR_EMBED_AUTHOR in embedding: embed.set_author(**embedding[ATTR_EMBED_AUTHOR]) if ATTR_EMBED_THUMBNAIL in embedding: embed.set_thumbnail(**embedding[ATTR_EMBED_THUMBNAIL]) embeds.append(embed) if ATTR_IMAGES in data: images = [] for image in data.get(ATTR_IMAGES, []): image_exists = await self.hass.async_add_executor_job( self.file_exists, image) if image_exists: images.append(image) await discord_bot.login(self.token) try: for channelid in kwargs[ATTR_TARGET]: channelid = int(channelid) # Must create new instances of File for each channel. files = [nextcord.File(image) for image in images] if images else [] try: channel = cast(Messageable, await discord_bot.fetch_channel(channelid)) except nextcord.NotFound: try: channel = await discord_bot.fetch_user(channelid) except nextcord.NotFound: _LOGGER.warning("Channel not found for ID: %s", channelid) continue await channel.send(message, files=files, embeds=embeds) except (nextcord.HTTPException, nextcord.NotFound) as error: _LOGGER.warning("Communication error: %s", error) await discord_bot.close()