async def allow_service(self, user: Union[discord.User, int]): if user is int: user = self.bot.get_user(user) if not user: # User not found raise discord.NotFound("User cannot be found.") stopped = await self.config.user(user).stop() return not stopped
async def deny(self, ctx, party_id: convert_invite, invite_id: convert_invite): party = await Party.from_id(self.bot, party_id) if not party: raise discord.NotFound("No party found") await party.deny_invite(ctx.author, invite_id) await ctx.send("Party Denied!")
async def from_user(cls, bot, member): doc = await bot.db["links"].find_one({ "user": member.id }) try: return cls(bot, member, doc["uuid"]) except: raise discord.NotFound()
def get_channel(channel_id): if channel_id == TEST_CHANNEL.id: TEST_CHANNEL._state = discard.client._connection return TEST_CHANNEL elif channel_id == TEST_CHANNEL2.id: TEST_CHANNEL2._state = discard.client._connection return TEST_CHANNEL2 else: raise discord.NotFound()
async def kick(self, ctx, member: discord.Member): party = await Party.from_channel(self.bot, ctx.channel) if not party: raise discord.NotFound("No party found") if ctx.author.id == party.leader.id or ctx.author.guild_permissions.administrator: await party.leave(member) else: await ctx.send("**Only the party leader (or admins) can do this!**" )
async def test_add_emoji_role_pair_emoji_not_found(mocker): """Adds a emoji/role pair to the role message creation, but the emoji is NotFound.""" cog, mock_bot, _ = init_mocks() mock_message = tosurnament_mock.DEFAULT_MESSAGE_MOCK mock_not_found_response = mocker.Mock() mock_not_found_response.status = 0 mock_message.add_reaction = mocker.AsyncMock(side_effect=discord.NotFound(mock_not_found_response, "")) await cog.add_emoji_role_pair(cog, tosurnament_mock.CtxMock(mock_bot, message=mock_message), "🛎️", None) cog.send_reply.assert_called_once_with(mocker.ANY, "emoji_not_found", "🛎️")
async def guild(self, ctx, guild): try: for x in ctx.bot.guilds: if x.name == guild or str(x.id) == guild or x.owner == guild: return x.convert(ctx, guild) else: raise discord.NotFound( 'No guild with the name/id/owner {} found'.format(guild)) except Exception as E: raise E
async def alert_new_letter(self, user_id: int, letter: Letter, letter_id: int): user = self.bot.get_user(user_id) if user is None: # User not found raise discord.NotFound("User cannot be contacted.") if not await self.allow_service(user): raise StopService("User stopped using the service.") message = str() prefix = await self.bot._config.prefix() first_time = await self.config.user(user).first_usage() if first_time: message += ( ( f"Hello {user.name}, this is the first time you're receiving a letter in your " "letterbox, so let me introduce you to the service.\n\nLetters is a service that " "allows you to send and receive letters from members of Discord, as long as I " "share a server with you and I can contact you. When you receive a letter, the " "letter gets into your letterbox where all your letters are stocked, so you can " "open a letter whenever you want. When you have read a letter, it is marked as " "read.\n\nYou can disable this service. **However, this system is meant for " "receiving letters over Discord from others, from your friends, from the past or " "of today, every letters deserve to be delivered.** It would be hurtful " "for you to disable it.\n\n Now that you are familiar with the concept, here are " "2 commands you should know:\n- `[p]letterbox` to check your letterbox;\n- " "`[p]letterset` to set your settings for the letter service;\n\n You will not " "receive this message again. From now on, you will only receive regular alerts " "about new letters.\n\n📩 You have received a new letter from {authors}! Check " "it out in your letterbox!" ) .format(authors=humanize_list(list(letter.authors.values()))) .replace("[p]", prefix[0]) ) else: message += ( f"📩 You have received a new letter from {letter.author}! Check it out in your " "letterbox! (`[p]letterbox`)" ).replace("[p]", prefix[0]) if [ i for i in list(letter.authors.values()) if i in await self.config.user(user).blocklist() ]: message += ( "\n⚠The author of this letter as been marked as blocked, you still " "receiving this letter in your letterbox, open it if you want or delete " "it. Letter ID: " + str(letter_id) ) try: await user.send(message) if first_time: await self.config.user(user).first_usage.set(False) return True except discord.HTTPException: return False return False
async def delete_letter_in_letterbox(self, receiver_id: int, id: int): """ Remove a new letter to a letterbox. """ user = await self.bot.get_or_fetch_user(receiver_id) if user is None: # User not found raise discord.NotFound("User cannot be found.") async with self.config.user(user).letterbox() as letterbox: try: del letterbox[str(id)] except KeyError: raise LetterNotExist("Cannot find the letter ID.")
async def convert(self, ctx, arg: int): """Converter function for the lookup command""" async with ctx.bot.http._session.get(f'https://discordapp.com/api/v6/guilds/{arg}/widget.json') as get: assert isinstance(get, aiohttp.ClientResponse) if get.status == 200: json = await get.json(encoding='utf-8') json['data_type'] = 'guild' return json elif get.status == 403: return {'data_type': 'guild_partial', 'id': arg} else: raise discord.NotFound(get, 'guild not found')
async def add_new_letter_in_letterbox(self, receiver_id: int, letter: Letter) -> int: """ Append a new letter to a letterbox. """ user = self.bot.get_user(receiver_id) if user is None: # User not found raise discord.NotFound("User cannot be found.") if not await self.allow_service(user): raise StopService("User stopped using the service.") letter_id = await self.config.custom("LetterBox", user.id).next_id() await self.config.custom("LetterBox", user.id).letterbox.set_raw( str(letter_id), value=letter.to_json() ) await self.config.custom("LetterBox", user.id).next_id.set(letter_id + 1) return letter_id
async def get_message(self, id_, *args, **kwargs): """Find a message by id :param id_: Id of message to find :type id_: int :raises discord.NotFound: This exception is raised when a message is not found (or not accessible by bot) :rtype: discord.Message :return: discord.Message instance if message is found. """ msg = None for channel in self.client.get_all_channels(): try: return await channel.get_message(id_, *args, **kwargs) except discord.NotFound: continue if msg is None: raise discord.NotFound(None, "Message not found")
async def send(bot: utils.SeraphimBase, mes: discord.Message): # sends message to starboard channel send_embed = await star_generate(bot, mes) star_entry = await bot.starboard.get(mes.id) starboard_chan = mes.guild.get_channel( bot.config.getattr(mes.guild.id, "starboard_id")) if starboard_chan: content = star_utils.generate_content_str(star_entry) starred = await starboard_chan.send(content=content, embed=send_embed) await starred.add_reaction("тнР") star_entry.star_var_id = starred.id star_entry.starboard_id = starred.channel.id bot.starboard.upsert(star_entry) return starred raise discord.NotFound(21234, "Unable to find starboard channel.")
async def get_from_cdn(url) -> bytes: """ A method that downloads an image from a url. Parameters: url (str): The url of the image. Returns: (bytes): A bytes object of the downloaded image. """ async with ClientSession() as session: async with session.get(url) as resp: if resp.status == 200: return await resp.read() elif resp.status == 404: raise discord.NotFound(resp, 'Not Found') elif resp.status == 403: raise discord.Forbidden(resp, 'Forbidden') else: raise discord.HTTPException(resp, 'Failed')
async def leave(self, member): if member.id not in [p.id for p in self.players]: raise discord.NotFound(self.players, "Not found!") x = 0 for i, p in enumerate(self.players): x = i if p.id == member.id: break else: self.players.pop(x) if member.id in [p.id for p in self.players]: self.players.remove(member) await self.channel.set_permissions(member, read_messages=False, send_messages=False) if self.has_vc: await self.vc.set_permissions(member, view_channel=False, connect=False, speak=False) await self.update() await self.channel.send(f"{member.mention} just left the party!")
async def fetch_message(self, id): modlog = self.__get_modlog_channel() if modlog is not None: return await modlog.fetch_message(id) else: raise discord.NotFound()
def test_not_found(self): message = AsyncMock() message.delete.side_effect = discord.NotFound(Mock(), "") self.assertFalse(self._await(delete_message(message))) message.delete.assert_awaited_once()
async def fetch_message(id): m = next((m for m in channel.history_for_mock if m.id == id), None) if not m: raise discord.NotFound(None, f'message {id} not found') return m
async def invite(self, ctx, member: discord.Member): party = await Party.from_channel(self.bot, ctx.channel) if not party: raise discord.NotFound("No party found") await party.invite(member) await ctx.send("**Invited!**")
by raising a `StopIteration`. The `async for` construct does not expect it, and we therefore need to substitute it for the appropriate exception type. """ try: return next(self.iter_messages) except StopIteration: raise StopAsyncIteration class MockSignal(enum.Enum): A = "A" B = "B" mock_404 = discord.NotFound( response=MagicMock(aiohttp.ClientResponse), # Mock the erroneous response message="Not found", ) class TestDownloadFile(unittest.IsolatedAsyncioTestCase): """Collection of tests for the `download_file` helper function.""" async def test_download_file_success(self): """If `to_file` succeeds, function returns the acquired `discord.File`.""" file = MagicMock(discord.File, filename="bigbadlemon.jpg") attachment = MockAttachment(to_file=AsyncMock(return_value=file)) acquired_file = await incidents.download_file(attachment) self.assertIs(file, acquired_file) async def test_download_file_404(self): """If `to_file` encounters a 404, function handles the exception & returns None."""
async def leave(self, ctx): party = await Party.from_channel(self.bot, ctx.channel) if not party: raise discord.NotFound("No party found") await party.leave(ctx.author)