我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.Object()。
def find_target(self, ctx, arg): """Returns the ID of the given target""" if arg.casefold() in ('everyone', 'all'): return discord.Object(id=0) try: return await MemberConverter().convert(ctx, arg) except BadArgument: pass try: return await RoleConverter().convert(ctx, arg) except BadArgument: pass return None
def __init__(self, prefix: str, start_time: int, colour: int, logger, session_manager: SessionManager, db: MongoClient, error_log: int, feedback_log: int): """ Init the instance of HahaNoUR. :param prefix: the bot prefix. :param start_time: the bot start time. :param colour: the colour used for embeds. :param logger: the logger. :param session_manager: the SessionManager instance. :param db: the MongoDB data controller. :param error_log: the channel id for error log. """ super().__init__(prefix) self.prefix = prefix self.colour = colour self.start_time = start_time self.logger = logger self.help_general = None self.all_help = None self.db = db self.session_manager = session_manager # FIXME remove type casting after library rewrite self.error_log = Object(str(error_log)) self.feedbag_log = Object(str(feedback_log))
def my_background_task(): client = discord.Client() await client.wait_until_ready() channel = discord.Object(id='189472786056478720') feed = youtube.start() while not client.is_closed: update = youtube.update(feed) if update != "304": entry = youtube.getLastEntry() YTEmbed = discord.Embed() YTEmbed.colour = 0x3498db YTEmbed.title = "Nouvelle vidéo sur la chaîne de Sakiut ! `" + entry['title'] + "`" YTEmbed.description = "Vidéo : " + entry['link'] + "\nChaîne : " + entry['channel'] + "\nPosté le : " + entry['published'] YTEmbed.set_thumbnail(url = entry['thumbnail']) YTEmbed.set_footer(text = "Posté par {0}".format(entry['author'])) await client.send_message(channel, "@everyone", embed = YTEmbed) feed = youtube.start() await asyncio.sleep(300)
def check_training(self): await self.bot.wait_until_ready() channel = discord.Object(id=overwatchChannelId) # SENDS TO CHANNEL OVERWATCH IN BANANA'S DISCORD while not self.bot.is_closed: now = datetime.datetime.now() if now.weekday() == 0 or now.weekday() == 3: if now.hour == 20: role = discord.utils.find(lambda r: r.name == 'overwatch_players', self.bot.get_server(bananasDiscordId).roles) message = role.mention + ' Yo mes ptits poulets, oubliez pas le training de ce soir de 21h a 23h, sinon Loulou il va raler !' await self.bot.send_message(channel, message) elif now.weekday() == 5: if now.hour == 15: role = discord.utils.find(lambda r: r.name == 'overwatch_players', self.bot.get_server(bananasDiscordId).roles) message = role.mention + ' Yo mes ptits poulets, oubliez pas le training de cette apres-midi de 16h a 18h, sinon Loulou il va raler !' await self.bot.send_message(channel, message) await asyncio.sleep(3600) # task runs every hour
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 _remove_time_entry(self, guild, member, session, *, event='mute_complete'): query = """SELECT * FROM schedule WHERE event = $3 AND args_kwargs #>> '{args,0}' = $1 AND args_kwargs #>> '{args,1}' = $2 ORDER BY expires LIMIT 1; """ # We have to go to the lowest level possible, because simply using # session.cursor WILL NOT work, as it uses str.format to format # the parameters, which will throw a KeyError due to the {} in the # JSON operators. session = session.transaction.acquired_connection entry = await session.fetchrow(query, str(guild.id), str(member.id), event) if entry is None: return None await self.bot.db_scheduler.remove(discord.Object(id=entry['id'])) return entry
def remove_old(self): for sid in self.aliases: to_delete = [] to_add = [] for aliasname, alias in self.aliases[sid].items(): lower = aliasname.lower() if aliasname != lower: to_delete.append(aliasname) to_add.append((lower, alias)) if aliasname != self.first_word(aliasname): to_delete.append(aliasname) continue server = discord.Object(id=sid) prefix = self.get_prefix(server, alias) if prefix is not None: self.aliases[sid][aliasname] = alias[len(prefix):] for alias in to_delete: # Fixes caps and bad prefixes del self.aliases[sid][alias] for alias, command in to_add: # For fixing caps self.aliases[sid][alias] = command dataIO.save_json(self.file_path, self.aliases)
def unban(self, ctx, member_id: int): """Used to unban a member from this server Due to the fact that I cannot find a user without being in a server with them only the ID should be provided EXAMPLE: !unban 353217589321750912 RESULT: That dude be unbanned""" # Lets only accept an int for this method, in order to ensure only an ID is provided # Due to that though, we need to ensure a string is passed as the member's ID member = discord.Object(id=str(member_id)) try: await self.bot.unban(ctx.message.server, member) await self.bot.say("\N{OK HAND SIGN}") except discord.Forbidden: await self.bot.say("But I can't, muh permissions >:c") except discord.HTTPException: await self.bot.say("Sorry, I failed to unban that user!")
def feeds_delete(self, ctx, *, feed : str): """Removes a feed from the channel. This will also delete the associated role so this action is irreversible. """ channel = ctx.message.channel server = channel.server feeds = self.feeds.get(channel.id, {}) feed = feed.lower() if feed not in feeds: await self.bot.say('This feed does not exist.') return role = feeds.pop(feed) try: await self.bot.delete_role(server, discord.Object(id=role)) except discord.HTTPException: await self.bot.say('\U0001F52B') else: await self.feeds.put(channel.id, feeds) await self.bot.say('\U0001F6AE')
def do_subscription(self, ctx, feed, action): channel = ctx.message.channel member = ctx.message.author feeds = self.feeds.get(channel.id, {}) feed = feed.lower() if feed not in feeds: await self.bot.say('This feed does not exist.') return role = feeds[feed] function = getattr(self.bot, action) try: await function(member, discord.Object(id=role)) except discord.HTTPException: # muh rate limit await asyncio.sleep(10) await function(member, discord.Object(id=role)) else: await self.bot.send_message(channel, '\u2705')
def write_to_modlog(self, message, author, server, reason): self.action_dict['actions_taken'] += 1 if server.id in self.server_index: config = self.server_index[server.id] else: return if not config[8] or not config[10][0]: return if not reason: reason = "***No Reason Specified***" content = message.clean_content else: content = message.clean_content.replace('\"{}\"'.format(reason), '') await self.safe_send_message(discord.Object(id=config[8]), 'At `{}` UTC in **<#{}>**, **{}** used the command ```{}```Reason: `{}`' ''.format(datetime.utcnow().strftime("%H:%M:%S on %a %b %d"), message.channel.id, clean_string(author.name), content, reason), server=server)
def _write_to_modlog(self, autoaction, offender, server, reason, channel=None): self.action_dict['actions_taken'] += 1 await self.user_index_check(offender) self.user_dict[offender.id]['actions_taken_against'] += 1 if server.id in self.server_index: config = self.server_index[server.id] else: return if not config[8] or not config[10][0]: return if not reason: reason = "*No reason was specified*" if not channel: await self.safe_send_message(discord.Object(id=config[8]), 'At `{}` UTC, I automatically took action against **{}** due to {}.\n**Action:** __{}__.' ''.format( datetime.utcnow().strftime("%H:%M:%S on %a %b %d"), clean_string(offender.name), autoaction, reason)) else: await self.safe_send_message(discord.Object(id=config[8]), 'At `{}` UTC, I automatically took action against **{}** in <#{}> due to {}. \n**Action:** __{}__' ''.format(datetime.utcnow().strftime("%H:%M:%S on %a %b %d"), clean_string(offender.name), channel.id, reason, autoaction), server=server) # TODO: Make this code that is mine, not stuff taken from code written by @Sharpwaves
def cmd_unban(self, message, author, server, leftover_args): """ Usage: {command_prefix}unban [id] ["reason"] Unbans the user(s) from the server, accepts a list of user ids with spaces between each """ if await self.has_roles(message.channel, author, server, command='unban'): reason = None if not leftover_args: raise CommandError('Usage: {command_prefix}unban [id] ["reason"]\nForces the ID to be banned from a server') try: int(leftover_args[-1]) except: try: reason = leftover_args[-1] del leftover_args[-1] except TypeError: raise CommandError('Please use a **USER ID** when using this command and not a name') for id in leftover_args: await self.unban(server, discord.Object(id=id)) await self.write_to_modlog(message, author, server, reason)
def cmd_shutdown(self, channel, author, server): """ Usage: {command_prefix}forcebackup Forces a back up of all server configs """ if author.id in [self.config.master_id]: await self.safe_send_message(discord.Object(id='155553608400764928'), '__**<@{}>**__ shutdown made in *{}* on `{}`'.format(author.id, channel.name, server.name ) ) await self.safe_send_message(channel, '**Powering off :see_no_evil:**') await self.backup_config(self.server_index) await self.logout() return
def ban(self, ctx, member: MemberID, *, reason: ActionReason = None): """Bans a member from the server. You can also ban from ID to ban regardless whether they're in the server or not. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Ban Members permission. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.ban(discord.Object(id=member), reason=reason) await ctx.send('\N{OK HAND SIGN}')
def massban(self, ctx, reason: ActionReason, *members: MemberID): """Mass bans multiple members from the server. You can also ban from ID to ban regardless whether they're in the server or not. Note that unlike the ban command, the reason comes first and is not optional. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Ban Members permission. """ for member_id in members: await ctx.guild.ban(discord.Object(id=member_id), reason=reason) await ctx.send('\N{OK HAND SIGN}')
def softban(self, ctx, member: MemberID, *, reason: ActionReason = None): """Soft bans a member from the server. A softban is basically banning the member from the server but then unbanning the member as well. This allows you to essentially kick the member while removing their messages. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Kick Members permissions. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' obj = discord.Object(id=member) await ctx.guild.ban(obj, reason=reason) await ctx.guild.unban(obj, reason=reason) await ctx.send('\N{OK HAND SIGN}')
def on_tempban_timer_complete(self, timer): guild_id, mod_id, member_id = timer.args guild = self.bot.get_guild(guild_id) if guild is None: # RIP return moderator = guild.get_member(mod_id) if moderator is None: try: moderator = await self.bot.get_user_info(mod_id) except: # request failed somehow moderator = f'Mod ID {mod_id}' else: moderator = f'{moderator} (ID: {mod_id})' else: moderator = f'{moderator} (ID: {mod_id})' reason = f'Automatic unban from timer made on {timer.created_at} by {moderator}.' await guild.unban(discord.Object(id=member_id), reason=reason)
def filter(self): await self.client.wait_until_ready() # get arrays channels id need to post discord_channels = [] for server in self.client.servers: for channel in server.channels: if channel.name in self.config.get('channels', []): discord_channels.append(discord.Object(channel.id)) while not self.client.is_closed: for channel in discord_channels: await self.client.send_message(channel, message) await asyncio.sleep(300)
def filter(self): await self.client.wait_until_ready() # get arrays channels id need to post discord_channels = [] for server in self.client.servers: for channel in server.channels: if channel.name in self.config.get('channels', []): discord_channels.append( discord.Object(channel.id)) while not self.client.is_closed: for channel in discord_channels: await self.client.send_message(channel, message) await asyncio.sleep(300)
def unfollow(ctx): f = open('%susers/allusers.txt' % path, 'r+') all = f.read().strip() if all: users = all.split(',') else: users = [] if ctx.message.author.id in users: users.remove(ctx.message.author.id) f.seek(0) f.truncate() if users != ['']: for i in users: if i: f.write(i + ',') else: pass os.remove('%susers/user%s.txt' % (path, ctx.message.author.id)) await bot.send_message(ctx.message.channel, 'You have unsubscribed from the reddit notifier feed. Use ``ap:follow`` to resubscribe if you\'d like. **Note: your list has been deleted** so if you subscribe again, you must remake your list.') await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content)) else: await bot.send_message(ctx.message.channel, 'You are already unsubscribed from the notifier.') f.close()
def off(ctx): if not isFollowing(ctx.message.author.id): await bot.send_message(ctx.message.channel, 'Use ``ap:follow`` first to subscribe to the bot. Do ``ap:commands`` for more help') else: f = open('%susers/user%s.txt' % (path, ctx.message.author.id), 'r+') content = f.read() f.seek(0) if content.startswith('--disable--off'): f.write(content) elif content.startswith('off'): f.write(content) elif content.startswith('--disable--'): f.write('--disable--off' + content[11:]) else: f.write('off' + content) f.close() await bot.send_message(ctx.message.channel, 'The bot will no longer ping you on every message. Do ``ap:ping on`` to reverse this.') await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content))
def remove(ctx): msg = '**Error** Something went wrong. Are you using the command right? Example use: ``ap:remove anime One Punch Man S2``' try: toUnfollow = ctx.message.content.split('ap:remove')[1].strip() status = removeKeyWords(toUnfollow, ctx.message.author.id) if status == True: await bot.send_message(ctx.message.channel, 'Successfully removed ``%s`` from ``%s``. View your list with ``ap:list``.' % (toUnfollow.split(' ', 1)[1].strip(), toUnfollow.split(' ', 1)[0].strip())) await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content)) elif status == 'blacklist': await bot.send_message(ctx.message.channel, 'Successfully removed all words from blacklist. View your list with ``ap:list``.') await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content)) else: await bot.send_message(ctx.message.channel, msg) except Exception as e: traceback.print_exc() await bot.send_message(ctx.message.channel, msg)
def edit(ctx): msg = '**Error** Something went wrong. Are you using the command right? Example use: ``ap:edit anime One Punch Man S2 = opm s2, one punch man s2`` to replace entire entry. Add a ``+`` or ``-`` after ``edit`` to just add or remove some keywords from entry.' sub = ctx.message.content.split('edit', 1)[1].strip() if sub: try: entry = editEntry(sub, ctx.message.author.id) if '=' in entry: await bot.send_message(ctx.message.channel, 'Successfully edited entry. Entry is now: %s. View your list with ``ap:list``.' % entry) await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content)) else: await bot.send_message(ctx.message.channel, '**Could not find the specified entry.**') await bot.send_message(discord.Object(id=config["log_location"]), 'User: ' + str(ctx.message.author) + '\nCmd: ' + str(ctx.message.content)) except: await bot.send_message(ctx.message.channel, '**Error** Something went wrong. Are you using the command right? Example uses: ``ap:edit + manga Boku no Hero`` For changing notifications to all threads (``-`` for episode/chapters only) or ``ap:edit manga Boku no Hero = my hero academia, boku no hero academia`` to change the entry values.') traceback.print_exc() else: await bot.send_message(ctx.message.channel, msg)
def _send_message(self, channel_id, message): await self.client.login(self.token) self.client.connect() c = discord.Object(id=channel_id) await self.client.send_message(c, message) await self.client.logout() await self.client.close()
def echoserver(self, ctx, serverName:str, channelName:str, *, content:str): ''' Echos some content back into another server ''' # It'll only be the owner sending this so there doesn't need to be any error handling. server = [i for i in self.sparcli.servers if i.name.lower() == serverName.lower()][0] if channelName.isdigit(): channel = Object(channelName) elif channelName.startswith('<#') and channelName.endswith('>'): channel = Object(channelName[2:-1]) else: channel = [i for i in server.channels if i.name.lower() == channelName.lower()][0] await self.sparcli.send_message(channel, content)
def as_object(obj_id: str) -> discord.Object: """ Creates a basic Discord Object given an ID. :param obj_id: The ID of the object being created :type obj_id: str :return: The new object with the specified ID. """ return discord.Object(obj_id)
def newstuff(self): """sends a message about a new feature in all servers""" await self.bot.say("\U0001f44d") await self.bot.send_message(discord.Object(id='248106639410855936'), "@here, A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>") await self.bot.send_message(discord.Object(id='227514633735372801'), "A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>") await self.bot.send_message(discord.Object(id='258350226279104512'), "A new WordPress post about my development has been made, check it out at <https://inkxbot.wordpress.com/>")
def __init__(self, bot): self.bot = bot self.channel = channel = discord.Object(id='189472786056478720') self.feed = youtube.start()
def setup(bot): n = Twitch(bot) bot.loop.create_task(n.check_streams(discord.Object(id=overwatchChannelId),'OverwatchCOI')) bot.loop.create_task(n.check_streams(discord.Object(id=sc2ChannelId),'StarcraftCOI')) bot.loop.create_task(n.check_streams(discord.Object(id=videogamesChannelId),'OtherCOI')) bot.add_cog(n)
def check_nextMatch(self): await self.bot.wait_until_ready() channel = discord.Object(id=overwatchChannelId) # SENDS TO CHANNEL OVERWATCH IN BANANA'S DISCORD matches = getMatches() current_datetime = datetime.now().astimezone(tz=None) for match in matches: delta = match.date - current_datetime if(match not in self.notified_matches and match.date - current_datetime > timedelta() and match.date - current_datetime < timedelta(minutes=30)): message = "Match incoming : \n" + str(match) await self.bot.send_message(channel, message) self.notified_matches += [match] await asyncio.sleep(60) # task runs every minute
def on_ready(): log('BOOTUP', 'Starting up Jinux system...') await dclient.change_presence(game=discord.Game(name=config.get('Jinux', 'Playing'))) global start_time start_time = datetime.now() # Notifies that Jinux has successfully connected to the Discord server if Channel_ID != 0: await dclient.send_message(discord.Object(id=Channel_ID), ":wave:") log('BOOTUP', 'Finished starting up Jinux system!') # Auto welcome new members
def convert(self, ctx, argument): try: return await MemberConverter().convert(ctx, argument) except commands.BadArgument: try: return discord.Object(id=int(argument)) except ValueError: raise commands.BadArgument('Invalid member ID. I also couldn\'t find the user by username.')
def on_discord_message(self, message, match): if isinstance(message.channel, discord.Object): return() if message.channel.is_private: return () if not self.bridge_enable: return () if message.content[0] == self.command_prefix: return () if not message.channel.id in self.irc_settings['discord channels']: return () author = message.author.name content = self.substitute_mentions(message) self.send_to_all_channels('<{}> {}'.format(author, content)) return ()
def nsfw(ctx): member = ctx.message.author role = discord.Object(id='199082489598181377') await bot.add_roles(member, role)
def on_member_join(member): if member.server.id=='154009582748827648': channel = discord.Object(id='160670845675634688') message = "{0.name} has joined the server~" await bot.send_message(channel, message.format(member)) user = discord.User() user.id = member.id await bot.send_message(user, Text("greeting.txt").format(member))
def on_member_join(member): if member.server.id=='154009582748827648': channel = discord.Object(id='155225555598442496') message = "{0.name} has joined the server~" await bot.send_message(channel, message.format(member)) user = discord.User() user.id = member.id await bot.send_message(user, Text("greeting.txt").format(member))
def _add_auto_role(self, member): server = member.guild async with self.bot.db.get_session() as session: query = session.select.from_(AutoRoles).where(AutoRoles.guild_id == server.id) role = await query.first() if role is None: return # TODO: respect the high verification level await member.add_roles(discord.Object(id=role.role_id))
def cancel_reminder(self, ctx, index: int=1): """Cancels a running reminder with a given index. Reminders start at 1. If an index is not given, it defaults to the one that will end first. You can't cancel reminders that you've set to go off in 30 seconds or less. """ query = """SELECT * FROM schedule WHERE event = 'reminder_complete' AND args_kwargs #>> '{args,0}' = $1 ORDER BY expires OFFSET $2 LIMIT 1; """ # We have to go to the lowest level possible, because simply using # ctx.session.cursor WILL NOT work, as it uses str.format to format # the parameters, which will throw a KeyError due to the {} in the # JSON operators. session = ctx.session.transaction.acquired_connection entry = await session.fetchrow(query, str(ctx.author.id), index - 1) if entry is None: return await ctx.send(f'Reminder #{index} does not exist... baka...') await ctx.bot.db_scheduler.remove(discord.Object(id=entry['id'])) _, channel_id, message = json.loads(entry['args_kwargs'])['args'] channel = self.bot.get_channel(channel_id) or 'deleted-channel' # In case the channel doesn't exist anymore server = getattr(channel, 'guild', None) embed = (discord.Embed(colour=0xFF0000, description=message, timestamp=entry['expires']) .set_author(name=f'Reminder #{index} cancelled!', icon_url=CANCELED_URL) .add_field(name='Was for', value=f'{channel} in {server}') .set_footer(text='Was set to go off at') ) await ctx.send(embed=embed)
def _get_message(channel, message_id): o = discord.Object(id=message_id + 1) # don't wanna use get_message due to poor rate limit (1/1s) vs (50/1s) msg = await channel.history(limit=1, before=o).next() if msg.id != message_id: return None return msg
def convert(self, ctx, arg): member = await super().convert(ctx, arg) if isinstance(member, int): obj = discord.Object(id=member) obj.__str__ = attrgetter('id') obj.guild = ctx.guild return obj return member
def get_guild_prefixes(self, guild): proxy_msg = discord.Object(id=None) proxy_msg.guild = guild return _callable_prefix(self, proxy_msg)
def on_ready(): while not client.is_closed: html = urllib.request.urlopen("https://insult.mattbas.org/api/insult.html").read() soup = BeautifulSoup(html,"html.parser") insult_text = soup.find('h1') print(insult_text.text) await client.send_message(discord.Object(id=DiscordChannel), insult_text.text) await asyncio.sleep(SpamSpeed) # Changes how fast the messages are posted. (Anything under 0.7 tends to break it
def on_ready(): print("Started Text Spam") while not client.is_closed: print(spam_text) await client.send_message(discord.Object(id=DiscordChannel), spam_text) await asyncio.sleep(SpamSpeed)
def on_ready(): print("Started Image Spam") while not client.is_closed: UpImage = random.choice(os.listdir(DirPictures)) print(UpImage) await client.send_file(discord.Object(id=DiscordChannel), DirPictures + UpImage) await asyncio.sleep(SpamSpeed) # Changes how fast the images are posted. (Anything under 0.7 tends to break it (????))????? )
def ban(self, ctx, *, member): """Used to ban a member This can be used to ban someone preemptively as well. Provide the ID of the user and this should ban them without them being in the server EXAMPLE: !ban 531251325312 RESULT: That dude be banned""" # Lets first check if a user ID was provided, as that will be the easiest case to ban if member.isdigit(): # First convert it to a discord object based on the ID that was given member = discord.Object(id=member) # Next, to ban from the server the API takes a server obejct and uses that ID # So set "this" server as the member's server. This creates the "fake" member we need member.server = ctx.message.server else: # If no ID was provided, lets try to convert what was given using the internal coverter converter = commands.converter.UserConverter(ctx, member) try: member = converter.convert() except commands.converter.BadArgument: await self.bot.say( '{} does not appear to be a valid member. If this member is not in this server, please provide ' 'their ID'.format(member)) return # Now lets try actually banning the member we've been given try: await self.bot.ban(member) await self.bot.say("\N{OK HAND SIGN}") except discord.Forbidden: await self.bot.say("But I can't, muh permissions >:c") except discord.HTTPException: await self.bot.say("Sorry, I failed to ban that user!")
def get_message(self, channel, mid): cached = self._message_cache.get(mid) if cached is not None: return cached before = discord.Object(id=str(int(mid) + 1)) async for m in self.bot.logs_from(channel, limit=1, before=before): if m.id != mid: return None self._message_cache[mid] = m return m return None # a custom on_message_edit
def on_member_join(self, member): if member.server.id != DISCORD_API_ID: return if member.bot: role = discord.Object(id=USER_BOTS_ROLE) try: await self.bot.add_roles(member, role) except: await asyncio.sleep(10) await self.bot.add_roles(member, role)
def announcement(self): logger.log('Posting announcements..') announcement = self.config.get('announcement') message = announcement.get('message', None) delay = announcement.get('delay', 300) if not message: logger.log('Please config your announcement message', 'red') return await self.client.wait_until_ready() # get arrays channels id need to post announcement_channels = [] for server in self.client.servers: for channel in server.channels: if channel.name in self.config.get('channels', []): announcement_channels.append( discord.Object(channel.id)) while not self.client.is_closed: for channel in announcement_channels: await self.client.send_message(channel, message) await asyncio.sleep(delay)