Python discord.Object() Examples
The following are 30
code examples of discord.Object().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord
, or try the search function
.
Example #1
Source File: backups.py From xenon with GNU General Public License v3.0 | 6 votes |
def _load_voice_channels(self): log.debug(f"Loading voice channels on {self.guild.id}") for vchannel in self.data["voice_channels"]: try: created = await self.guild.create_voice_channel( name=vchannel["name"], overwrites=await self._overwrites_from_json(vchannel["overwrites"]), category=discord.Object(self.id_translator.get(vchannel["category"])), reason=self.reason ) await created.edit( bitrate=vchannel["bitrate"], user_limit=vchannel["user_limit"] ) self.id_translator[vchannel["id"]] = created.id except Exception: pass
Example #2
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_server_role_delete(self, role): try: sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(role.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if role.server.id != server: return target = discord.Object(id=channel) r_b = ', '.join(map(str, role.server.roles)) msg = "Server Role Deleted: {0}\n".format(role.name) await self.bot.send_message(target, "`[{0}]` :bangbang: **Server Roles Delete Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(role.server)
Example #3
Source File: Moderation.py From NotSoBot with MIT License | 6 votes |
def hackban(self, ctx, *users:str): banned = [] for user in users: u = discord.Object(id=user) u.server = ctx.message.server try: await self.bot.ban(u) banned.append(user) except: uu = ctx.message.server.get_member(user) if uu is None: await self.bot.say('`{0}` could not be hack banned.'.format(user)) else: await self.bot.say('`{0}` is already on the server and could not be banned.'.format(uu)) continue if banned: await self.bot.say(':white_check_mark: Hackbanned `{0}`!'.format(", ".join(banned)))
Example #4
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_server_role_create(self, role): try: sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(role.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if role.server.id != server: return target = discord.Object(id=channel) msg = "Server Role Created: {0}\n".format(role.name) await self.bot.send_message(target, "`[{0}]` :bangbang: **Server Roles Create Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(role.server)
Example #5
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_member_unban(self, server, member): try: if member == self.bot.user: return check = await self.is_ignored(None, user=True, global_only=True, u=member, server=server) if check: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) serverr = str(result[0]['server']) if server.id != serverr: return msg = "Unbanned User: {0} <{0.id}>\n".format(member) target = discord.Object(id=channel) await self.bot.send_message(target, "`[{0}]` :white_check_mark: **Member Unban Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(server)
Example #6
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_member_ban(self, member): try: if member == self.bot.user: return check = await self.is_ignored(None, user=True, global_only=True, u=member, server=member.server) if check: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(member.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return if member.server.id in self.banned_users: self.banned_users[member.server.id] += member.id else: self.banned_users[member.server.id] = [member.id] channel = str(result[0]['channel']) server = str(result[0]['server']) if member.server.id != server: return msg = "User: {0} <{0.id}>\n".format(member) target = discord.Object(id=channel) await self.bot.send_message(target, "`[{0}]` :outbox_tray: **Member Ban Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(member.server)
Example #7
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_member_remove(self, member): try: if member == self.bot.user: return check = await self.is_ignored(None, user=True, global_only=True, u=member, server=member.server) if check: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(member.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return if member.server.id in self.banned_users: if member.id in self.banned_users[member.server.id]: return channel = str(result[0]['channel']) server = str(result[0]['server']) if member.server.id != server: return a = member.server msg = "User: {0.name} <{0.id}>\n".format(member) target = discord.Object(id=channel) await self.bot.send_message(target, "`[{0}]` :outbox_tray: **Member Leave/Kick Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(member.server)
Example #8
Source File: extendedmodlog.py From Trusty-cogs with MIT License | 6 votes |
def initialize(self) -> None: all_data = await self.config.all_guilds() for guild_id, data in all_data.items(): guild = discord.Object(id=guild_id) for entry, default in inv_settings.items(): if entry not in data: all_data[guild_id][entry] = inv_settings[entry] if type(default) == dict: for key, _default in inv_settings[entry].items(): if not isinstance(all_data[guild_id][entry], dict): all_data[guild_id][entry] = default try: if key not in all_data[guild_id][entry]: all_data[guild_id][entry][key] = _default except TypeError: # del all_data[guild_id][entry] logger.error("Somehow your dict was invalid.") continue if await self.config.version() < "2.8.5": logger.info("Saving all guild data to new version type") await self.config.guild(guild).set(all_data[guild_id]) await self.config.version.set("2.8.5") self.settings = all_data
Example #9
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_member_join(self, member): try: if member == self.bot.user: return check = await self.is_ignored(None, user=True, global_only=True, u=member, server=member.server) if check: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(member.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if member.server.id != server: return a = member.server msg = "Member Joined: {0.name} <{0.id}>\n".format(member) msg += "Server: {0.name} <{0.id}>\n".format(a).replace("'", "") target = discord.Object(id=channel) await self.bot.send_message(target, "`[{0}]` :inbox_tray: **Member Join Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(member.server)
Example #10
Source File: backups.py From xenon with GNU General Public License v3.0 | 6 votes |
def _load_text_channels(self): log.debug(f"Loading text channels on {self.guild.id}") for tchannel in self.data["text_channels"]: try: created = await self.guild.create_text_channel( name=tchannel["name"], overwrites=await self._overwrites_from_json(tchannel["overwrites"]), category=discord.Object(self.id_translator.get(tchannel["category"])), reason=self.reason ) self.id_translator[tchannel["id"]] = created.id await created.edit( topic=self._translate_mentions(tchannel["topic"]), nsfw=tchannel["nsfw"], ) except Exception: pass
Example #11
Source File: Logs.py From NotSoBot with MIT License | 6 votes |
def on_channel_delete(self, channel): try: sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(channel.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return chan = str(result[0]['channel']) if channel.id == chan: remove_sql = "DELETE FROM `logs` WHERE server={0}" remove_sql = remove_sql.format(channel.server.id) self.cursor.execute(remove_sql) self.cursor.commit() return server = str(result[0]['server']) if channel.server.id != server: return a = channel.server msg = "{0} Channel: {1} <{2}>\n".format("Voice" if channel.type == discord.ChannelType.voice else "Text", channel.name, channel.id).replace("'", "") target = discord.Object(id=chan) await self.bot.send_message(target, "`[{0}]` :x: **Channel Delete Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(channel.server)
Example #12
Source File: converters.py From bot with MIT License | 6 votes |
def convert(self, ctx: Context, arg: str) -> t.Union[discord.User, discord.Object]: """Convert the `arg` to a `discord.User` or `discord.Object`.""" try: return await super().convert(ctx, arg) except BadArgument: pass try: user_id = int(arg) log.trace(f"Fetching user {user_id}...") return await ctx.bot.fetch_user(user_id) except ValueError: log.debug(f"Failed to fetch user {arg}: could not convert to int.") raise BadArgument(f"The provided argument can't be turned into integer: `{arg}`") except discord.HTTPException as e: # If the Discord error isn't `Unknown user`, return a proxy instead if e.code != 10013: log.info(f"Failed to fetch user, returning a proxy instead: status {e.status}") return proxy_user(arg) log.debug(f"Failed to fetch user {arg}: user does not exist.") raise BadArgument(f"User `{arg}` does not exist")
Example #13
Source File: candy_collection.py From seasonalbot with MIT License | 6 votes |
def ten_recent_msg(self) -> List[int]: """Get the last 10 messages sent in the channel.""" ten_recent = [] recent_msg_id = max( message.id for message in self.bot._connection._messages if message.channel.id == Channels.seasonalbot_commands ) channel = await self.hacktober_channel() ten_recent.append(recent_msg_id) for i in range(9): o = discord.Object(id=recent_msg_id + i) msg = await next(channel.history(limit=1, before=o)) ten_recent.append(msg.id) return ten_recent
Example #14
Source File: verification.py From bot with MIT License | 6 votes |
def unsubscribe_command(self, ctx: Context, *_) -> None: # We don't actually care about the args """Unsubscribe from announcement notifications by removing the role from yourself.""" has_role = False for role in ctx.author.roles: if role.id == constants.Roles.announcements: has_role = True break if not has_role: await ctx.send(f"{ctx.author.mention} You're already unsubscribed!") return log.debug(f"{ctx.author} called !unsubscribe. Removing the 'Announcements' role.") await ctx.author.remove_roles(Object(constants.Roles.announcements), reason="Unsubscribed from announcements") log.trace(f"Deleting the message posted by {ctx.author}.") await ctx.send( f"{ctx.author.mention} Unsubscribed from <#{constants.Channels.announcements}> notifications." ) # This cannot be static (must have a __func__ attribute).
Example #15
Source File: verification.py From bot with MIT License | 6 votes |
def subscribe_command(self, ctx: Context, *_) -> None: # We don't actually care about the args """Subscribe to announcement notifications by assigning yourself the role.""" has_role = False for role in ctx.author.roles: if role.id == constants.Roles.announcements: has_role = True break if has_role: await ctx.send(f"{ctx.author.mention} You're already subscribed!") return log.debug(f"{ctx.author} called !subscribe. Assigning the 'Announcements' role.") await ctx.author.add_roles(Object(constants.Roles.announcements), reason="Subscribed to announcements") log.trace(f"Deleting the message posted by {ctx.author}.") await ctx.send( f"{ctx.author.mention} Subscribed to <#{constants.Channels.announcements}> notifications.", )
Example #16
Source File: hockey.py From Trusty-cogs with MIT License | 5 votes |
def save_pickems_data(self): await self.bot.wait_until_ready() while self.save_pickems: for guild_id, pickems in self.all_pickems.items(): guild_obj = discord.Object(id=int(guild_id)) async with self.pickems_save_lock: log.debug("Saving pickems data") await self.config.guild(guild_obj).pickems.set( {name: p.to_json() for name, p in pickems.items()} ) await asyncio.sleep(60)
Example #17
Source File: Logs.py From NotSoBot with MIT License | 5 votes |
def on_channel_update(self, before, after): try: sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(before.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if before.server.id != server: return msg = "" if before.name != after.name: msg += "Name After: {0}\n".format(after.name) if before.is_private == False: if after.is_private == True: msg += "Channel Private: Changed from False to True\n" else: if after.is_private == False: msg += "Channel Is_Private: Changed from True to False\n" if before.topic != after.topic: msg += "Channel Topic Before: {0}\n".format(before.topic) msg += "Channel Topic After: {0}\n".format(after.topic) if before.position != after.position: msg += "Channel Position Before: {0}\n".format(str(before.position)) msg += "Channel Position After: {0}\n".format(str(after.position)) if before.bitrate != after.bitrate: msg += "Channel Bitrate Before: {0}\n".format(str(before.bitrate)) msg += "Channel Bitrate After: {0}\n".format(str(after.bitrate)) target = discord.Object(id=channel) if msg: await self.bot.send_message(target, "`[{0}]` :warning: **Channel Edit Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format("Channel Edited: {0} <{1}>\n".format(before.name, before.id).replace("'", "")+"Channel Type: {0}\n".format(str(after.type))+msg)) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(after.server)
Example #18
Source File: Logs.py From NotSoBot with MIT License | 5 votes |
def on_message_edit(self, before, after): try: if before.channel.is_private: return check = await self.is_ignored(before, user=True) if check: return if before.content == after.content: return if before.author == self.bot.user: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(before.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if before.server.id != server: return if before.channel.id == channel: return before.content = before.content after.content = after.content for s in before.mentions: before.content = before.content.replace(s.mention, s.name) for s in after.mentions: after.content = after.content.replace(s.mention, s.name) msg = "User: {0} <{1}>\n".format(after.author.name, after.author.id).replace("'", "") msg2 = "Channel: {0}\n".format(after.channel.mention) msg2 += "`Before:` \"{0}\"\n".format(before.content) msg2 += "`After:` \"{0}\"".format(after.content) target = discord.Object(id=channel) await self.truncate(target, "`[{0}]` :pencil2: **Message Edit Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)+msg2) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(after.server)
Example #19
Source File: Logs.py From NotSoBot with MIT License | 5 votes |
def on_command(self, command, ctx): try: if ctx.message.channel.is_private: return check = await self.is_ignored(ctx.message, user=True) if check: return sql = "SELECT server,channel FROM `logs` WHERE server={0}" sql = sql.format(ctx.message.server.id) result = self.cursor.execute(sql).fetchall() if len(result) == 0: return channel = str(result[0]['channel']) server = str(result[0]['server']) if ctx.message.server.id != server: return if len(ctx.message.mentions): for s in ctx.message.mentions: ctx.message.content = ctx.message.content.replace(s.mention, '@'+s.name).replace('<@!{0}>'.format(s.id), '@'+s.name) msg = "User: {0} <{1}>\n".format(ctx.message.author, ctx.message.author.id).replace("'", "") msg += "Command: {0}\n".format(ctx.invoked_with) msg2 = "`Channel:` {0}\n".format(ctx.message.channel.mention) msg2 += "`Context Message:` \"{0}\"".format(ctx.message.content) target = discord.Object(id=channel) await self.truncate(target, "`[{0}]` :exclamation: **Command Log**\n".format(time.strftime("%I:%M:%S %p"))+cool.format(msg)+msg2) except (discord.errors.Forbidden, discord.errors.NotFound, discord.errors.InvalidArgument): self.remove_server(ctx.message.server)
Example #20
Source File: premium.py From RulesBot with MIT License | 5 votes |
def on_member_update(self, before: Member, after: Member): if after.guild.id != 385848724628439062: return if any(role.id == ACTIVE_PATREON for role in after.roles) and not any( role.id == PREMIUM_RULESBOT for role in after.roles): await after.add_roles(Object(id=PREMIUM_RULESBOT), reason="Patreon")
Example #21
Source File: hockey.py From Trusty-cogs with MIT License | 5 votes |
def initialize_pickems(self): data = await self.config.all_guilds() for guild_id in data: guild_obj = discord.Object(id=guild_id) pickems_list = await self.config.guild(guild_obj).pickems() if pickems_list is None: continue if type(pickems_list) is list: continue # pickems = [Pickems.from_json(p) for p in pickems_list] pickems = {name: Pickems.from_json(p) for name, p in pickems_list.items()} self.all_pickems[str(guild_id)] = pickems
Example #22
Source File: discord_text_spam.py From discord-spam-bots with MIT License | 5 votes |
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(0.7) # Changes how fast the messages are posted. (Anything under 0.7 tends to break it (┛✧Д✧))┛彡┻━┻ )
Example #23
Source File: hockey.py From Trusty-cogs with MIT License | 5 votes |
def save_pickems_unload(self): for guild_id, pickems in self.all_pickems.items(): guild_obj = discord.Object(id=int(guild_id)) await self.config.guild(guild_obj).pickems.set( {name: p.to_json() for name, p in pickems.items()} )
Example #24
Source File: starboard.py From Trusty-cogs with MIT License | 5 votes |
def initialize(self) -> None: for guild_id in await self.config.all_guilds(): self.starboards[guild_id] = {} all_data = await self.config.guild(discord.Object(id=guild_id)).starboards() for name, data in all_data.items(): starboard = StarboardEntry.from_json(data) self.starboards[guild_id][name] = starboard
Example #25
Source File: bot.py From MusicBot with MIT License | 5 votes |
def get_voice_client(self, channel: discord.abc.GuildChannel): if isinstance(channel, discord.Object): channel = self.get_channel(channel.id) if not isinstance(channel, discord.VoiceChannel): raise AttributeError('Channel passed must be a voice channel') if channel.guild.voice_client: return channel.guild.voice_client else: return await channel.connect(timeout=60, reconnect=True)
Example #26
Source File: bot.py From MusicBot with MIT License | 5 votes |
def set_voice_state(self, vchannel, *, mute=False, deaf=False): if isinstance(vchannel, discord.Object): vchannel = self.get_channel(vchannel.id) if getattr(vchannel, 'type', ChannelType.text) != ChannelType.voice: raise AttributeError('Channel passed must be a voice channel') await self.ws.voice_state(vchannel.guild.id, vchannel.id, mute, deaf) # I hope I don't have to set the channel here # instead of waiting for the event to update it
Example #27
Source File: discord_insult_spam.py From discord-spam-bots with MIT License | 5 votes |
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(0.7) # Changes how fast the messages are posted. (Anything under 0.7 tends to break it
Example #28
Source File: discord_image_spam.py From discord-spam-bots with MIT License | 5 votes |
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(0.7) # Changes how fast the images are posted. (Anything under 0.7 tends to break it (┛✧Д✧))┛彡┻━┻ )
Example #29
Source File: antispam.py From bot with MIT License | 5 votes |
def __init__(self, bot: Bot, validation_errors: Dict[str, str]) -> None: self.bot = bot self.validation_errors = validation_errors role_id = AntiSpamConfig.punishment['role_id'] self.muted_role = Object(role_id) self.expiration_date_converter = Duration() self.message_deletion_queue = dict() self.bot.loop.create_task(self.alert_on_validation_error())
Example #30
Source File: music.py From mee6 with MIT License | 5 votes |
def on_schwifty_finished_playing(self, guild_id): server = discord.Object(id=str(guild_id)) music = await self.pop_music(server) if not music: return try: await self._play(server, music) except Exception as e: response = 'An error occurred, sorry :grimacing:...' print(e)