我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.NotFound()。
def clean(ctx, message): """ Cleans the previous messages :param ctx: :param message: :return: """ try: message_bucket = [] async for entry in ctx.logs_from(message.channel): if entry.author == ctx.user: message_bucket.append(entry) await ctx.delete_messages(message_bucket) await ctx.send_message(message.channel, ':sweat_drops: `Cleaned.`') except discord.Forbidden: await ctx.send_message(message.channel, '**Error**: `I do not have permissions to get channel logs`') return except discord.NotFound: await ctx.send_message(message.channel, '**Error**: `The channel you are requesting for doesnt exist.`') return except discord.HTTPException: return
def ok(self, emoji: str = '\N{OK HAND SIGN}'): """ Adds a reaction to the command message, or sends it to the channel if we can't add reactions. This should be used as feedback to commands, just like how most bots send out `:ok_hand:` when a command completes successfully. """ try: await self.message.add_reaction(emoji) except Forbidden: # can't add reactions await self.send(emoji) except NotFound: # the command message got deleted somehow pass
def multiban(self, ctx, reason, delete_days: DeleteDays=2, *members: converters.RawMember): """ Bans multiple users. Functions similarly to d?ban. """ progress = await ctx.send(f'Banning {len(members)} member(s)...') reason = reason or 'No reason provided.' paginator = commands.Paginator(prefix='', suffix='') for member in members: try: await ctx.guild.ban(member, delete_message_days=delete_days, reason=f'(Multi-banned by {ctx.author}) {reason}') paginator.add_line(f'{ctx.green_tick} Banned {describe(member)}.') except discord.NotFound: # XXX: This code path might be unreachable, research further paginator.add_line(f"{ctx.red_tick} {describe(member)} wasn't found.") except discord.HTTPException: paginator.add_line(f'{ctx.red_tick} Failed to ban {describe(member)}. No permissions?') await progress.delete() for page in paginator.pages: await ctx.send(page)
def ban(self, ctx, member: converters.RawMember, delete_days: DeleteDays=2, *, reason=None): """ Bans someone. This command is special in that you may specify an ID to ban, instead of regularly specifying a member to ban. Banning users outside of the server is called "hackbanning", and is handy for banning users who are not present in the server. If you don't want to delete any messages, specify 0 for delete_days. delete_days has a maximum of 7. By default, 2 days worth of messages are deleted. """ try: reason = reason or 'No reason provided.' await ctx.guild.ban(member, delete_message_days=delete_days, reason=f'(Banned by {ctx.author}) {reason}') ctx.bot.dispatch('member_dog_ban', member, ctx.author, reason) except discord.Forbidden: await ctx.send("I can't do that.") except discord.NotFound: await ctx.send("User not found.") else: banned = await ctx.bot.get_user_info(member.id) if isinstance(member, discord.Object) else member await ctx.send(f'\N{OK HAND SIGN} Banned {describe(banned)}.')
def adminlist(self, ctx): """List all bot admins defined. Usage: adminlist""" alist = '' for i in self.bot.store['bot_admins']: nid = '' try: _name = ctx.guild.get_member(i) except AttributeError: _name = None if not _name: try: _name = await self.bot.get_user_info(i) except discord.NotFound: _name = 'UNKNOWN' nid = i if not nid: nid = _name.id alist += '**' + str(_name) + f'** (ID `{nid}`)\n' await ctx.send('The following people are bot admins:\n' + alist)
def _loop(self): for name, value in self._member_fields(): self._track.add_field(name=name, value=value, inline=False) message = await self.ctx.send(embed=self._track) while not self.is_completed(): await asyncio.sleep(random.uniform(1, 3)) self.update_game() self.update_current_embed() try: await message.edit(embed=self._track) except discord.NotFound: message = await self.ctx.send(embed=self._track) await asyncio.sleep(random.uniform(1, 3))
def join(self, invite_url: discord.Invite=None): """Joins new server""" if hasattr(self.bot.user, 'bot') and self.bot.user.bot is True: # Check to ensure they're using updated discord.py msg = ("I have a **BOT** tag, so I must be invited with an OAuth2" " link:\nFor more information: " "https://twentysix26.github.io/" "Red-Docs/red_guide_bot_accounts/#bot-invites") await self.bot.say(msg) if hasattr(self.bot, 'oauth_url'): await self.bot.whisper("Here's my OAUTH2 link:\n{}".format( self.bot.oauth_url)) return if invite_url is None: await self.bot.say("I need a Discord Invite link for the " "server you want me to join.") return try: await self.bot.accept_invite(invite_url) await self.bot.say("Server joined.") log.debug("We just joined {}".format(invite_url)) except discord.NotFound: await self.bot.say("The invite was invalid or expired.") except discord.HTTPException: await self.bot.say("I wasn't able to accept the invite." " Try again.")
def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None, quiet=False): msg = None try: msg = await self.send_message(dest, content, tts=tts) if msg and expire_in: asyncio.ensure_future(self._wait_delete_msg(msg, expire_in)) if also_delete and isinstance(also_delete, discord.Message): asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in)) except discord.Forbidden: if not quiet: self.safe_print("Warning: Cannot send message to %s, no permission" % dest.name) except discord.NotFound: if not quiet: self.safe_print("Warning: Cannot send message to %s, invalid channel?" % dest.name) return msg
def whois(self, ctx, user_id: int): """ Searches for a user via ID """ try: with ctx.channel.typing(): user = await self.bot.get_user_info(user_id) embed = discord.Embed(colour=discord.Colour(0x30f9c7), description="ID: {}".format(user.id), timestamp=datetime.datetime.now()) embed.set_thumbnail( url=user.avatar_url) embed.set_author(name=user) embed.set_footer(text="Who Is: User") embed.add_field(name="Bot?", value=user.bot, inline=False) embed.add_field(name="Account Creation Date", value=user.created_at, inline=False) await ctx.send(embed=embed) except discord.NotFound: await ctx.send("`No user found under this ID`") except discord.HTTPException: await ctx.send("`Error collecting user information`") return
def edit_mod_entry(self, modcfg, data): """Edit a moderation entry.""" modlog = data['guild'].get_channel(modcfg['mod_log_id']) if modlog is None: raise self.SayException('Moderation channel not found') try: action_data = self.cache[data['action_id']] except KeyError: raise self.SayException("Can't find action ID in cache, sorry :c") old_data = action_data['data'] old_data['reason'] = data['reason'] try: message = await modlog.get_message(action_data['message_id']) except discord.NotFound: raise self.SayException('Message to edit not found') except discord.Forbidden: raise self.SayException("Can't read messages") except discord.HTTPException as err: raise self.SayException(f'fug `{err!r}`') await message.edit(content=self.modlog_fmt(old_data))
def star(self, ctx, message_id: int): """Star a message.""" try: message = await ctx.channel.get_message(message_id) except discord.NotFound: return await ctx.send('Message not found') except discord.Forbidden: return await ctx.send("Can't retrieve message") except discord.HTTPException as err: return await ctx.send(f'Failed to retrieve message: {err!r}') try: await self.add_star(message, ctx.author) await ctx.ok() except (StarAddError, StarError) as err: log.warning(f'[star_command] Errored: {err!r}') return await ctx.send(f'Failed to add star: {err!r}')
def unstar(self, ctx, message_id: int): """Unstar a message.""" try: message = await ctx.channel.get_message(message_id) except discord.NotFound: return await ctx.send('Message not found') except discord.Forbidden: return await ctx.send("Can't retrieve message") except discord.HTTPException as err: return await ctx.send(f'Failed to retrieve message: {err!r}') try: await self.remove_star(message, ctx.author) await ctx.ok() except (StarRemoveError, StarError) as err: log.warning(f'[unstar_cmd] Errored: {err!r}') return await ctx.send(f'Failed to remove star: {err!r}')
def starrers(self, ctx, message_id: int): """Get the list of starrers from a message in the current channel.""" try: message = await ctx.channel.get_message(message_id) except discord.NotFound: return await ctx.send('Message not found') except discord.Forbidden: return await ctx.send("Can't retrieve message") except discord.HTTPException as err: return await ctx.send(f'Failed to retrieve message: {err!r}') guild = ctx.guild await self._get_starconfig(guild.id) star = await self.get_star(guild.id, message.id) if star is None: return await ctx.send('Star object not found') _, em = make_star_embed(star, message) starrers = [guild.get_member(starrer_id) for starrer_id in star['starrers']] em.add_field(name='Starrers', value=', '.join([m.display_name for m in starrers])) await ctx.send(embed=em)
def streload(self, ctx, message_id: int): """Star reload. Reload a message, its starrers and update the star in the starboard. Useful if the starred message was edited. """ channel = ctx.channel cfg = await self._get_starconfig(channel.guild.id) try: message = await channel.get_message(message_id) except discord.NotFound: raise self.SayException('message not found') star = await self.get_star(ctx.guild.id, message_id) if star is None: raise self.SayException('star object not found') try: await self.update_star(cfg, star, msg=message) except StarError as err: log.error(f'force_reload: {err!r}') raise self.SayException(f'rip {err!r}') await ctx.ok()
def send_log(self, server: discord.Server, log: Log): """Sends a embed corresponding to the log in the log channel of the server""" if server.id in self.servers_config["servers"]: if "log channel" in self.servers_config["servers"][server.id]: embed = log.get_embed(self.bot) channel = self.servers_config["servers"][server.id]["log channel"] try: await self.bot.send_message(destination=channel, embed=embed) except discord.Forbidden: await self.bot.send_message(destination=server.owner, content=\ "I'm not allowed to send embeds in the log channel (#" + \ channel.name + "). Please change my permissions.") except discord.NotFound: await self.bot.send_message(destination=server.owner, content=\ "I'm not allowed to send embeds in the log channel because " + \ "it doesn't exists anymore. Please set another log channel " + \ "using the `[p]set_log_channel` command.") except discord.HTTPException: pass except discord.InvalidArgument: pass
def say_victory_message(self, msg_winner, msg_no_winner): serverlist = list(self.bot.servers) for s in serverlist: if self.get_victory_messages(s): try: msg = msg_winner if self.get_show_result(s) else msg_no_winner matches_channel = self.bot.get_channel(self.get_matches_channel(s)) if matches_channel: try: await self.bot.send_message(matches_channel, msg) except (discord.Forbidden, discord.NotFound, discord.InvalidArgument): pass except discord.HTTPException: pass #except Exception as e: # print("Unable to announce end of match: %s" % e)
def contact(self, ctx, *, message): """Sends a message to the bot owner (60s cooldown). Is not affected by Octarine Core, Refresher Orb, Rearm, or cooldown reduction talents.""" try: owner = await self.bot.get_owner() except discord.NotFound: await self.bot.say("Alas, I know not who my owner is.") return author = ctx.message.author emb = discord.Embed(description = message) emb.set_author(name = "Message from %s" % author) try: await self.bot.send_message(owner, embed = emb) except discord.InvalidArgument: await self.bot.say("Alas, I know not where my owner is.") except discord.HTTPException: await self.bot.say("Alas, I could not deliver your message. Perhaps it is too long?") except: await self.bot.say("Alas, for reasons yet unknown to me, I could not deliver your message.") else: await self.bot.say("I have delivered your message with utmost haste! I pray it should arrive safely.")
def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None): msg = None try: msg = await self.send_message(dest, content, tts=tts) if msg and expire_in: asyncio.ensure_future(self._wait_delete_msg(msg, expire_in)) if also_delete and isinstance(also_delete, discord.Message): asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in)) except discord.Forbidden: if self.config.debug: print('[PB][PERMISSIONS] Cannot send message to {0}, no permission'.format(dest.name)) except discord.NotFound: if self.config.debug: print('[PB][CHANNEL] Cannot send message to {0}, channel does not exist'.format(dest.name)) return msg
def item17(self, ctx, target: discord.Member): """Sabotage a weapon !shop 17 [target]""" message = ctx.message language = prefs.getPref(message.server, "language") if scores.getStat(message.channel, target, "sabotee", "-") == "-": scores.addToStat(message.channel, message.author, "exp", -14) scores.setStat(message.channel, target, "sabotee", message.author.name) await comm.message_user(message, _(":ok: {target}'s weapon is now sabotaged... but they don't know it (14 exp)!", language).format(**{ "target": target.name }), forcePv=True) else: await comm.message_user(message, _(":ok: {target}'s weapon is already sabotaged!", language).format(**{ "target": target.name }), forcePv=True) try: await self.bot.delete_message(ctx.message) except discord.Forbidden: await comm.logwithinfos_ctx(ctx, "Error deleting message: forbidden.") except discord.NotFound: pass
def on_command(command, ctx): bot.commands_used[command.name] += 1 await comm.logwithinfos_message(ctx.message, str(command) + " (" + ctx.message.clean_content + ") ") if prefs.getPref(ctx.message.server, "delete_commands") and checks.is_activated_check(ctx.message.channel): try: await bot.delete_message(ctx.message) except discord.Forbidden: await comm.logwithinfos_ctx(ctx, "Error deleting message: forbidden.") except discord.NotFound: await comm.logwithinfos_ctx(ctx, "Error deleting message: not found (normal if the purgemessages command was used).") # message = ctx.message # destination = None # if message.channel.is_private: # destination = 'Private Message' # else: # destination = '#{0.channel.name} ({0.server.name})'.format(message) # # log.info('{0.timestamp}: {0.author.name} in {1}: {0.content}'.format(message, destination))
def hackban(self, ctx, user_id: int): """Bans a user outside of the server.""" author = ctx.message.author guild = author.guild user = guild.get_member(user_id) if user is not None: return await ctx.invoke(self.ban, user=user) try: await self.bot.http.ban(user_id, guild.id, 0) await ctx.message.edit(content=self.bot.bot_prefix + 'Banned user: %s' % user_id) except discord.NotFound: await ctx.message.edit(content=self.bot.bot_prefix + 'Could not find user. ' 'Invalid user ID was provided.') except discord.errors.Forbidden: await ctx.message.edit(content=self.bot.bot_prefix + 'Could not ban user. Not enough permissions.')
def edit_message(self, message, content, *, delete=0): """ Overrides discord.py's function for editing a message """ msg = None try: msg = await super().edit_message(message, content) log.debug( 'Edited message ID {} in #{}'.format(msg.id, msg.channel)) if msg and delete and self.config.delete: asyncio.ensure_future(self._delete_after(msg, delete)) except discord.Forbidden: log.warning( "No permission to edit a message in #{}".format(message.channel)) except discord.NotFound: log.warning( "Could not find message ID {} to edit".format(message.id)) except discord.HTTPException as e: log.warning( "Problem editing a message in #{}: {}".format(message.channel, e)) return msg
def unban(self, ctx): """Unban a user by their ID. **Usage:** `g_unban <user>` **Permission:** BAN_MEMBERS""" if ctx.message.guild.me.guild_permissions.ban_members == True: if ctx.message.author.guild_permissions.ban_members == True: try: umsg = ctx.message.content args = umsg.split(' ') uid = int(args[1]) try: member = await self.bot.get_user_info(uid) except discord.NotFound: await ctx.send("I didn't find that user.") else: await self.bot.unban(ctx.message.guild, member) await ctx.send(":white_check_mark: unbanned "+str(member)) except ValueError: await ctx.send("That is not an ID.") except IndexError: await ctx.send("Usage: `{}unban <user id>`".format(self.bot.command_prefix)) else: await ctx.send("You can't manage bans.") else: await ctx.send("I can't manage bans.")
def quote(self, ctx): """Get a message from either the current channel or a specified channel. **Usage:** `g_quote [channel id] <message id>` **Permission:** User""" umsg = ctx.message.content args = umsg.split(' ') if '--s' in umsg: await ctx.message.delete() if len(args) > 1: try: if len(args) > 2: channel = self.bot.get_channel(int(args[1])) msg = await channel.get_message(int(args[2])) else: channel = ctx.message.channel msg = await channel.get_message(int(args[1])) em = discord.Embed(title="Found message!",description=msg.content,color=self.randomColour()) em.set_footer(text='Author: {}'.format(str(msg.author))) em.timestamp = msg.created_at await ctx.send(embed=em) except ValueError: await ctx.send(":x: Please enter an id (or multiple) to find a message.") except discord.NotFound: await ctx.send(":x: I'm sorry, but I couldn't find that message. :sob:") else: await ctx.send("Improper arguments.")
def edit_invite_blocker(ev, before, after): if after.guild: if isinstance(after.author, discord.Member): if not after.author.permissions_in(after.channel).manage_guild: active = await ev.db.get_guild_settings(after.guild.id, 'BlockInvites') if active is None: active = False if active: arguments = after.content.split(' ') invite_found = False for arg in arguments: triggers = ['.gg', '.com', 'http'] for trigger in triggers: if trigger in arg: try: invite_found = await ev.bot.get_invite(arg) break except discord.NotFound: pass if invite_found: title = '? Invite links are not allowed on this server.' response = discord.Embed(color=0xF9F9F9, title=title) await after.delete() try: await after.author.send(embed=response) except discord.Forbidden: pass log_embed = discord.Embed(color=0xF9F9F9) author = f'{after.author.name}#{after.author.discriminator}' log_embed.set_author(name=f'I removed {author}\'s invite link.', icon_url=user_avatar(after.author)) log_embed.set_footer( text=f'Posted In: #{after.channel.name} | Leads To: {invite_found.guild.name}') await log_event(ev.db, after.guild, log_embed)
def send_invite_blocker(ev, message): if message.guild: if isinstance(message.author, discord.Member): if not message.author.permissions_in(message.channel).manage_guild: active = await ev.db.get_guild_settings(message.guild.id, 'BlockInvites') if active is None: active = False if active: arguments = message.content.split(' ') invite_found = False for arg in arguments: triggers = ['.gg', '.com', 'http'] for trigger in triggers: if trigger in arg: try: invite_found = await ev.bot.get_invite(arg) break except discord.NotFound: pass if invite_found: title = '? Invite links are not allowed on this server.' response = discord.Embed(color=0xF9F9F9, title=title) await message.delete() try: await message.author.send(embed=response) except discord.Forbidden: pass log_embed = discord.Embed(color=0xF9F9F9) author = f'{message.author.name}#{message.author.discriminator}' log_embed.set_author(name=f'I removed {author}\'s invite link.', icon_url=user_avatar(message.author)) log_embed.set_footer( text=f'Posted In: #{message.channel.name} | Leads To: {invite_found.guild.name}') await log_event(ev.db, message.guild, log_embed)
def name_checker(ev): while True: guild_ids = [] guilds = [] actives = await ev.db[ev.db.db_cfg.database].ServerSettings.find({'ASCIIOnlyNames': True}).to_list(None) for doc in actives: gid = doc['ServerID'] guild_ids.append(gid) for guild_id in guild_ids: active_guild = discord.utils.find(lambda x: x.id == guild_id, ev.bot.guilds) if active_guild: guilds.append(active_guild) for guild in guilds: temp_name = await ev.db.get_guild_settings(guild.id, 'ASCIIOnlyTempName') if temp_name is None: temp_name = '<ChangeMyName>' members = guild.members for member in members: nam = member.display_name invalid = False for char in nam: if char not in string.printable: invalid = True break if invalid: try: new_name = clean_name(nam, temp_name) await member.edit(nick=new_name, reason='ASCII name enforcement.') except discord.NotFound: pass except discord.Forbidden: pass await asyncio.sleep(60)
def mute_checker(ev, message): if message.guild: if isinstance(message.author, discord.Member): if message.author.id not in ev.bot.cfg.dsc.owners: if not message.author.permissions_in(message.channel).administrator: mute_list = await ev.db.get_guild_settings(message.guild.id, 'MutedUsers') if mute_list is None: mute_list = [] if message.author.id in mute_list: try: await message.delete() except discord.Forbidden: pass except discord.NotFound: pass
def quote(cmd, message, args): if args: lookup = args[0] try: lookup = int(lookup) except ValueError: lookup = None if lookup: msg = None for channel in message.guild.channels: if isinstance(channel, discord.TextChannel): try: msg = await channel.get_message(lookup) break except discord.Forbidden: msg = None except discord.NotFound: msg = None if msg: if msg.content: location = f'{msg.guild.name} | #{msg.channel.name}' response = discord.Embed(color=msg.author.color, timestamp=msg.created_at) response.set_author(name=f'{msg.author.display_name}', icon_url=user_avatar(msg.author)) response.description = msg.content response.set_footer(text=location) else: response = discord.Embed(color=0xBE1931, title='? That message has no text content.') else: response = discord.Embed(color=0xBE1931, title='? Message not found.') else: response = discord.Embed(color=0xBE1931, title='? Invalid ID given.') else: response = discord.Embed(color=0xBE1931, title='? No ID given.') await message.channel.send(embed=response)
def _delete_msg(self, args): """ Deletes the given message. Syntax: delete_msg (id) """ try: chanstr = args[0] except IndexError: raise ConsoleCommandSyntaxError("No arguments provided.") try: id = int(args[1]) if id < 1: raise ValueError except ValueError: raise ConsoleCommandSyntaxError("Invalid amount.") except IndexError: raise ConsoleCommandSyntaxError("Missing amount argument.") try: guild, chan = re.match(r"(\d+).(\d+)", chanstr).group(1, 2) except AttributeError: raise ConsoleCommandSyntaxError("Invalid indices string.") try: guild = self.client.guilds[int(guild)] except IndexError: raise ConsoleCommandSyntaxError("Invalid guild index.") try: chan = guild.text_channels[int(chan)] except IndexError: raise ConsoleCommandSyntaxError("Invalid channel index.") try: msg = chan.get_message(id) except NotFound: raise ConsoleCommandSyntaxError(f"Message with ID {id} not found.") try: await msg.delete() except Forbidden: raise ConsoleCommandSyntaxError("Cannot delete message; no permissions.")
def command_note_delete(self, data, data_string, message): if not self.has_permission(message.author): return log.debug("Permission denied") # No perms if len(data) < 1: return await self.send_message( message.channel, "{} Usage: `note-delete \"<note number>\"`".format(message.author.mention) ) index = data[0] note = self.data_manager.get_note(message.server, index) if not note: return await self.send_message( message.channel, "{} Unknown note ID: {}".format(message.author.mention, index) ) self.data_manager.delete_note(message.server, index) self.data_manager.save_server(message.server) channel = self.data_manager.get_notes_channel(message.server) if channel: try: note_message = await self.get_message(self.get_channel(channel), note["message_id"]) except discord.NotFound: note_message = None if note_message: await self.delete_message(note_message) await self.send_message( message.channel, "{} Note deleted: `{}`".format( message.author.mention, index ) ) # Aliases
def base_purge(self, ctx: DogbotContext, limit: int, check=None, **kwargs): # check if it's too much if limit > 5000: await ctx.send('Too many messages to purge. 5,000 is the maximum.') return # purge the actual command message too limit += 1 try: msgs = await ctx.channel.purge(limit=limit, check=check, **kwargs) await ctx.send(f'Purge complete. Removed {len(msgs)} message(s).', delete_after=2.5) except discord.NotFound: pass # ignore not found errors
def clean(self, ctx: DogbotContext): """Removes recent messages posted by the bot.""" try: await ctx.channel.purge(limit=50, check=lambda m: m.author == ctx.bot.user) except discord.NotFound: pass
def rps_error(self, _ctx, error): if not isinstance(error, discord.NotFound): log.debug('RPS message deleted, ignoring!') error.should_suppress = True
def assign_roles(self, autorole_type: str, member: Member): async with self.bot.pgpool.acquire() as pg: # fetch autoroles for that user record = await pg.fetchrow('SELECT * FROM autoroles WHERE guild_id = $1 AND type = $2', member.guild.id, autorole_type) if not record: return [] # get the role ids we need role_ids = record['roles'] # collect roles to add roles_to_add = [discord.utils.get(member.guild.roles, id=role_id) for role_id in role_ids] # filter out dead roles roles_to_add = list(filter(lambda r: r is not None, roles_to_add)) if not roles_to_add: # no roles to add return log.debug('Adding {} roles to {}.'.format(len(roles_to_add), member)) try: # add roles await member.add_roles(*roles_to_add) except discord.Forbidden: log.warning('Failed to autorole %s. Forbidden!', member) except discord.NotFound: log.warning('Failed to autorole %s, not found?', member) else: return roles_to_add
def __auto_join_channels(self): for url in self.settings['auto join']['invite urls']: log('Auto-joining {}'.format(url)) try: await self.client.accept_invite(url) except discord.NotFound: log('Invite has expired') except discord.HTTPException as e: log('Got an HTTP exception: {}'.format(e)) except discord.Forbidden: log('Forbidden') return tuple()
def _loop(self): start = time.perf_counter() while True: colour = header = None try: message = await self.ctx.bot.wait_for('message', timeout=120, check=self.check_message) except asyncio.TimeoutError: await self.edit_board(0, header='Took too long...') raise parsed = self.parse_message(message.content) if parsed is None: # garbage input, ignore. continue x, y, thing = parsed with contextlib.suppress(discord.NotFound): await message.delete() try: if thing.value: getattr(self.board, thing.value)(x, y) else: self.board.show(x, y) except HitMine: self.board.explode(x, y) await self.edit_board(0xFFFF00, header='BOOM!') await asyncio.sleep(random.uniform(0.5, 1)) self.board.reveal_mines() colour, header = 0xFF0000, 'Game Over!' raise except Exception as e: await self.ctx.send(f'An error happened.\n```\y\n{type(e).__name__}: {e}```') raise else: if self.board.is_solved(): colour, header = 0x00FF00, "A winner is you!" self.board.reveal_mines(success=True) return time.perf_counter() - start finally: await self.edit_board(colour, header=header)
def _loop(self): self.edit_screen() self._message = await self.ctx.send(embed=self._screen) await self.add_buttons() while True: try: message = await self.ctx.bot.wait_for('message', timeout=120, check=self.check_message) except asyncio.TimeoutError: if self._state == State.default: raise continue try: x, y, number = self.parse_message(message.content) except ValueError: continue try: self.board[x, y] = number except (IndexError, ValueError): continue with suppress(discord.NotFound): await message.delete() self.edit_screen() await self._message.edit(embed=self._screen)
def reason(self, ctx, num: CaseNumber, *, reason): """Sets the reason for a particular case. You must own this case in order to edit the reason. Negative numbers are allowed. They count starting from the most recent case. e.g. -1 will show the newest case, and -10 will show the 10th newest case. """ case = await self._get_case(ctx.session, ctx.guild.id, num) if case is None: return await ctx.send(f"Case #{num} doesn't exist.") if case.mod_id != ctx.author.id: return await ctx.send("This case is not yours.") channel = ctx.guild.get_channel(case.channel_id) if not channel: return await ctx.send('This channel no longer exists... :frowning:') message = await _get_message(channel, case.message_id) if not message: return await ctx.send('Somehow this message was deleted...') embed = message.embeds[0] reason_field = embed.fields[-1] embed.set_field_at(-1, name=reason_field.name, value=reason, inline=False) try: await message.edit(embed=embed) except discord.NotFound: # In case the message was cached, and the message was deleted # While it was still in the cache. return await ctx.send('Somehow this message was deleted...') case.reason = reason await ctx.session.add(case) await ctx.send('\N{OK HAND SIGN}')
def safe_delete_message(self, message, *, quiet=False): try: return await self.delete_message(message) except discord.Forbidden: if not quiet: self.safe_print("Warning: Cannot delete message \"%s\", no permission" % message.clean_content) except discord.NotFound: if not quiet: self.safe_print("Warning: Cannot delete message \"%s\", message not found" % message.clean_content)
def safe_edit_message(self, message, new, *, send_if_fail=False, quiet=False): try: return await self.edit_message(message, new) except discord.NotFound: if not quiet: self.safe_print("Warning: Cannot edit message \"%s\", message not found" % message.clean_content) if send_if_fail: if not quiet: print("Sending instead") return await self.safe_send_message(message.channel, new)
def on_message(self, message): """Message listener""" if not message.channel.is_private: if message.server.id in self.settings and self.settings[message.server.id]: this_trigger = self.settings[message.server.id] if this_trigger in message.content and "pintrigger" not in message.content: try: await self.bot.pin_message(message) except discord.Forbidden: print("No permissions to do that!") except discord.NotFound: print("That channel or message doesn't exist!") except discord.HTTPException: print("Something went wrong. Maybe check the number of pinned messages?")
def show_page(self, page, *, first=False): self.current_page = page entries = self.get_page(page) p = [] for t in enumerate(entries, 1 + ((page - 1) * self.per_page)): p.append('%s. %s' % t) self.embed.set_footer(text='Page %s/%s (%s entries)' % (page, self.maximum_pages, len(self.entries))) if not self.paginating: self.embed.description = '\n'.join(p) return await self.bot.send_message(self.message.channel, embed=self.embed) if not first: self.embed.description = '\n'.join(p) await self.bot.edit_message(self.message, embed=self.embed) return # verify we can actually use the pagination session if not self.permissions.add_reactions: raise CannotPaginate('Bot does not have add reactions permission.') if not self.permissions.read_message_history: raise CannotPaginate('Bot does not have Read Message History permission.') p.append('') p.append('Confused? React with \N{INFORMATION SOURCE} for more info.') self.embed.description = '\n'.join(p) self.message = await self.bot.send_message(self.message.channel, embed=self.embed) for (reaction, _) in self.reaction_emojis: if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'): # no |<< or >>| buttons if we only have two pages # we can't forbid it if someone ends up using it but remove # it from the default set continue try: await self.bot.add_reaction(self.message, reaction) except discord.NotFound: # If the message isn't found, we don't care about clearing anything return
def xban(self, ctx, user_id: int): """ Allows the banning of a user not int he guild via ID """ try: await ctx.bot.http.ban(user_id, ctx.message.guild.id, 0) except discord.Forbidden: await ctx.channel.send(":x: 403 FORBIDDEN") except discord.NotFound: await ctx.channel.send(":x: User not found.") else: await ctx.channel.send(f":negative_squared_cross_mark: Banned user {user_id} - <@{user_id}>.")
def guild(self, ctx, guild_id: int): """ Searchs for a guild via ID """ try: with ctx.channel.typing(): guild = self.bot.get_guild(guild_id) if guild is None: raise discord.NotFound embed = discord.Embed(colour=discord.Colour(0x30f9c7), description=f"ID: {guild.id}", timestamp=datetime.datetime.now()) embed.set_thumbnail( url=guild.icon_url) embed.set_author(name=guild.name) embed.set_footer(text="Who Is: Guild") embed.add_field(name="Members", value=str(len(guild.members))) embed.add_field(name="Roles", value=str(len(guild.roles) - 1)) embed.add_field(name="Channels", value=str(len(guild.channels))) embed.add_field(name="AFK Channel", value=guild.afk_channel) embed.add_field(name="AFK Timeout", value=str(guild.afk_timeout / 60)) embed.add_field(name="Owner", value=guild.owner) embed.add_field(name="Creation Date", value=guild.created_at) embed.add_field(name="Region", value=guild.region) embed.add_field(name="Verification Level", value=guild.verification_level) await ctx.send(embed=embed) except discord.NotFound: await ctx.send("`No guild found under this ID`") except discord.HTTPException: await ctx.send("`Error collecting guild information`") return
def edit_invite_blocker(ev, before, after): if after.guild: if isinstance(after.author, discord.Member): if not after.author.permissions_in(after.channel).manage_guild: active = ev.db.get_guild_settings(after.guild.id, 'BlockInvites') if active is None: active = False if active: arguments = after.content.split(' ') invite_found = False for arg in arguments: triggers = ['.gg', '.com', 'http'] for trigger in triggers: if trigger in arg: try: invite_found = await ev.bot.get_invite(arg) break except discord.NotFound: pass if invite_found: title = '? Invite links are not allowed on this server.' response = discord.Embed(color=0xF9F9F9, title=title) await after.delete() try: await after.author.send(embed=response) except discord.Forbidden: pass log_embed = discord.Embed(color=0xF9F9F9) author = f'{after.author.name}#{after.author.discriminator}' log_embed.set_author(name=f'I removed {author}\'s invite link.', icon_url=user_avatar(after.author)) log_embed.set_footer( text=f'Posted In: #{after.channel.name} | Leads To: {invite_found.guild.name}') await log_event(ev.db, after.guild, log_embed)
def send_invite_blocker(ev, message): if message.guild: if isinstance(message.author, discord.Member): if not message.author.permissions_in(message.channel).manage_guild: active = ev.db.get_guild_settings(message.guild.id, 'BlockInvites') if active is None: active = False if active: arguments = message.content.split(' ') invite_found = False for arg in arguments: triggers = ['.gg', '.com', 'http'] for trigger in triggers: if trigger in arg: try: invite_found = await ev.bot.get_invite(arg) break except discord.NotFound: pass if invite_found: title = '? Invite links are not allowed on this server.' response = discord.Embed(color=0xF9F9F9, title=title) await message.delete() try: await message.author.send(embed=response) except discord.Forbidden: pass log_embed = discord.Embed(color=0xF9F9F9) author = f'{message.author.name}#{message.author.discriminator}' log_embed.set_author(name=f'I removed {author}\'s invite link.', icon_url=user_avatar(message.author)) log_embed.set_footer( text=f'Posted In: #{message.channel.name} | Leads To: {invite_found.guild.name}') await log_event(ev.db, message.guild, log_embed)
def mute_checker(ev, message): if message.guild: mute_list = ev.db.get_guild_settings(message.guild.id, 'MutedUsers') if mute_list is None: mute_list = [] if message.author.id in mute_list: try: await message.delete() except discord.Forbidden: pass except discord.NotFound: pass
def safe_send_file(self, dest, fp, *, filename=None, comment=None, tts=False, expire_in=0, also_delete=None, quiet=False): final_dest = None for servers in self.servers: this = discord.utils.get(servers.channels, id=str(dest.id)) if this: final_dest = this if not final_dest: return try: msg = None msg = await self.send_file(final_dest, fp, filename=filename, content=comment, tts=tts) self.action_dict['messages_sent'] += 1 if msg and expire_in: asyncio.ensure_future(self._wait_delete_msg(msg, expire_in)) if also_delete and isinstance(also_delete, discord.Message): asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in)) except discord.Forbidden: if not quiet: print( "Warning: Cannot send message to %s:%s, no permission" % ( final_dest.name, final_dest.server.name)) except discord.NotFound: if not quiet: print("Warning: Cannot send message to %s:%s, invalid channel?" % ( final_dest.name, final_dest.server.name)) except discord.HTTPException: if not quiet: print("Warning: I'm being rate limited") finally: if msg: return msg