async def spam(self, ctx, message, times: int): """spams chat with what u make it say. If your message has spaces but them in double quotes Note: You will be responsible for any trouble you get into""" server = ctx.message.server serverid = server.id theconfesset = self.confession truestr = "True" falsestr = "False" owner = server.owner.id msgdude = str(message) user = str(ctx.message.author.name) msgdel = ctx.message await self.bot.delete_message(msgdel) for i in range(times): await self.bot.say(msgdude) await asyncio.sleep(1) await asyncio.sleep(5) confess = user + " made me spam ```" + msgdude + "```" nosetconfess = user + " made me spam ```" + msgdude + "``` To disable confession DMs do ```->pmconfession False```" for i, s in enumerate(theconfesset): if s["SERVER"] == theconfesset: continue if serverid in s["SERVER"]: if truestr in s["CHOICE"]: await self.bot.send_message(discord.User(id=owner), confess) return elif falsestr in s["CHOICE"]: await self.bot.say(confess) return await self.bot.send_message(discord.User(id=owner), nosetconfess)
def __init__(self, _http: http.SlashCommandRequest, _json: dict, _discord: typing.Union[discord.Client, commands.Bot], logger): self.__token = _json["token"] self.message = None # Should be set later. self.name = self.command = self.invoked_with = _json["data"]["name"] self.args = [] self.kwargs = {} self.subcommand_name = self.invoked_subcommand = self.subcommand_passed = None self.subcommand_group = self.invoked_subcommand_group = self.subcommand_group_passed = None self.interaction_id = _json["id"] self.command_id = _json["data"]["id"] self._http = _http self.bot = _discord self._logger = logger self.deferred = False self.responded = False self._deferred_hidden = False # To check if the patch to the deferred response matches self.guild_id = int( _json["guild_id"]) if "guild_id" in _json.keys() else None self.author_id = int(_json["member"]["user"]["id"] if "member" in _json.keys() else _json["user"]["id"]) self.channel_id = int(_json["channel_id"]) if self.guild: self.author = discord.Member(data=_json["member"], state=self.bot._connection, guild=self.guild) elif self.guild_id: self.author = discord.User(data=_json["member"]["user"], state=self.bot._connection) else: self.author = discord.User(data=_json["user"], state=self.bot._connection)
async def recruitUser(ctx, user: discord.Member): embed = discord.Embed(title="Let's Game!", description=ctx.message.author.display_name + " requests your holy presence!", color=0x00ffff) if type(ctx.message.author.voice.voice_channel) == type(None): print(ctx.message.author.voice.voice_channel) embed.add_field(name="In Server: ", value=ctx.message.author.server.name) else: embed.add_field(name="In Server: " + ctx.message.author.server.name, value="Voice Channel: " + ctx.message.author.voice.voice_channel.name) embed.add_field( name="Please reply with:", value="yes if you would like to play, and no if you cannot.", inline=True) embed.add_field(name="Time Requirement! :timer:", value="Please respond to this message within 60 seconds.") embed.set_thumbnail(url=user.avatar_url) await bot.send_message(discord.User(id=user.id), embed=embed) userDecision = await bot.wait_for_message(timeout=60, author=user) if type(userDecision) == type(None): await bot.send_message(discord.User(id=user.id), "You didn't make it in time!") await bot.say(user.display_name + " didn't respond in time.") elif str(userDecision.content) == "no": await bot.say(user.display_name + " is not going to join.") else: await bot.say(user.display_name + " is going to join!")
async def roulette(message, client): rolled = randint(1, 6) if rolled == 6: await client.send_message(message.channel, "BANG! :gun:") try: if message.server.id == Constants.CHAN_SERVER_ID: print("server={}".format(Constants.CHAN_SERVER_ID)) saint = discord.User() saint.id = Constants.SAINT_ID await client.send_message( saint, "Banned name: {} id: {} mention: {}".format( message.author.name, message.author.id, message.author.mention)) if message.server.id == Constants.GIDEOVAMES_SERVER_ID: print("server={}".format(Constants.GIDEOVAMES_SERVER_ID)) cat = discord.User() cat.id = '95840206191624192' await client.send_message( cat, "Banned name: {} id: {} mention: {}".format( message.author.name, message.author.id, message.author.mention)) await client.ban(message.author, 0) print("banned!") await client.send_message(message.channel, "Banned {}".format(message.author.name)) except Exception as e: print("failed to ban user: {} exception: {}").format( message.author.name, e) # await client.send_message(message.channel, "Failed to ban {}".format(message.author.name)) else: await client.send_message(message.channel, "You live.. for now")
async def ban(self, ctx): if not ctx.message.channel.permissions_for( ctx.message.author).ban_members: await self.bot.say("You don't have permission to do this.") return if len(ctx.message.mentions) == 1: try: await self.bot.send_message( discord.User(id=ctx.message.mentions[0].id), 'You have been banned from Miki server. If you believe this is an error, consult with mods.' ) except: pass try: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.ban(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') banned for ' + ctx.message.content.split(' ', 2)[2] + ' by ' + ctx.message.author.name) except: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.ban(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') banned for (blank) by ' + ctx.message.author.name) return try: await self.bot.send_message( discord.User(id=ctx.message.content.split(' ', 2)[1]), 'You have been banned from Miki server. If you believe this is an error, consult with mods.' ) except: pass try: temp_member = discord.Object( id=ctx.message.content.split(' ', 2)[1]) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.ban(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') banned for ' + ctx.message.content.split(' ', 2)[2] + ' by ' + ctx.message.author.name) except: temp_member = discord.Object( id=ctx.message.content.split(' ', 1)[1]) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.ban(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') banned for (blank) by ' + ctx.message.author.name)
async def kick(self, ctx): if not ctx.message.channel.permissions_for( ctx.message.author).kick_members: await self.bot.say("You don't have permission to do this.") return if len(ctx.message.mentions) == 1: try: await self.bot.send_message( discord.User(id=ctx.message.mentions[0].id), "You have been kicked from Miki server. You can rejoin via <https://discord.gg/39Xpj7K>; just don't make the same mistake again or it will lead to a ban." ) except: pass try: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ctx.message.mentions[0].name + ' (' + temp_member.id + ') kicked for ' + ctx.message.content.split(' ', 2)[2] + ' by ' + ctx.message.author.name) except: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ctx.message.mentions[0].name + ' (' + temp_member.id + ') kicked for (blank) by ' + ctx.message.author.name) return try: await self.bot.send_message( discord.User(id=ctx.message.content.split(' ', 2)[1]), 'You have been banned from Miki server. If you believe this is an error, consult with mods.' ) except: pass try: temp_member = discord.Object( id=ctx.message.content.split(' ', 2)[1]) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') kicked for ' + ctx.message.content.split(' ', 2)[2] + ' by ' + ctx.message.author.name) except: temp_member = discord.Object( id=ctx.message.content.split(' ', 1)[1]) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ' (' + temp_member.id + ') kicked for (blank) by ' + ctx.message.author.name)
async def kick(self, ctx): if not ctx.message.channel.permissions_for( ctx.message.author).kick_members: await self.bot.say("You don't have permission to do this.") return if len(ctx.message.mentions) == 1: try: await self.bot.send_message( discord.User(id=ctx.message.mentions[0].id), "You have been kicked from Miki server. You can rejoin via <https://discord.gg/39Xpj7K>; just don't make the same mistake again or it will lead to a ban." ) except: pass try: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ctx.message.mentions[0].name + ' (' + temp_member.id + ') kicked for ' + ctx.message.content.split(' ', 2)[2] + ' by ' + ctx.message.author.name) except: temp_member = discord.Object(id=ctx.message.mentions[0].id) temp_member.server = discord.Object(id=ctx.message.server.id) await self.bot.kick(temp_member) await self.bot.send_message( discord.Object(id=self.modlog_channel_id), ctx.message.mentions[0].name + ' (' + temp_member.id + ') kicked for (blank) by ' + ctx.message.author.name) return try: await self.bot.send_message( discord.User(id=ctx.message.content.split(' ', 2)[1]), 'You have been banned from Miki server. If you believe this is an error, consult with mods.' ) except: pass args = ctx.message.content.split(' ') if (len(args) == 1): # Skip if there's no arguments. return member = discord.Object(id=args[1]) member.server = discord.Object(id=ctx.message.server.id) reason = "(blank)" if (len(args) > 1): # Add a reason if there's more than 2 arguments reason = " ".join(args[2:len(args)]) await self.log( f'({member.id}) kicked for {reason} by {ctx.message.author.name}') await self.bot.kick(member)
def __init__(self, _http: http.SlashCommandRequest, _json: dict, _discord: typing.Union[discord.Client, commands.Bot], logger): """ Context of a component interaction.\n Similar to :class:`.SlashContext` .. warning:: Do not manually init this model. :ivar message_id: Message ID that the component is attached to. :ivar custom_id: The custom ID of the component. :ivar interaction_id: Interaction ID of the component message. :ivar bot: discord.py client. :ivar _http: :class:`.http.SlashCommandRequest` of the client. :ivar _logger: Logger instance. :ivar deferred: Whether the interaction is currently deferred (loading state) :ivar _deferred_hidden: Internal var to check that state stays the same :ivar responded: Whether you have responded with a message to the interaction. :ivar guild_id: Guild ID of the command message. If the command was invoked in DM, then it is ``None`` :ivar author_id: User ID representing author of the command message. :ivar channel_id: Channel ID representing channel of the command message. :ivar author: User or Member instance of the command invoke. """ self.__token = _json["token"] self.message_id = int(_json["message"]["id"]) self.custom_id = self.name = self.command = self.invoked_with = _json[ "data"]["custom_id"] self.interaction_id = _json["id"] self._http = _http self.bot = _discord self._logger = logger self.deferred = False self.responded = False self._deferred_hidden = False # To check if the patch to the deferred response matches self.guild_id = int( _json["guild_id"]) if "guild_id" in _json.keys() else None self.author_id = int(_json["member"]["user"]["id"] if "member" in _json.keys() else _json["user"]["id"]) self.channel_id = int(_json["channel_id"]) if self.guild: self.author = discord.Member(data=_json["member"], state=self.bot._connection, guild=self.guild) elif self.guild_id: self.author = discord.User(data=_json["member"]["user"], state=self.bot._connection) else: self.author = discord.User(data=_json["user"], state=self.bot._connection)
async def _deal(self, context): with open('data/supercog/players.json', "r") as players_file: players = json.load(players_file) for player in players: dealtWhite = [ self.generate_card("w"), self.generate_card("w"), self.generate_card("w") ] dealtBlack = [ self.generate_card("b"), self.generate_card("b"), self.generate_card("b") ] player['dealtWhite'] = dealtWhite player['dealtBlack'] = dealtBlack user = discord.User(id=str(player["player"])) wlist = "" blist = "" for card in dealtWhite: wlist += card + "\n" for card in dealtBlack: blist += card + "\n" await self.bot.send_message( user, "Your white cards:\n" + wlist + "\n" "Your black cards:\n" + blist) with open("data/supercog/players.json", "w") as players_file: json.dump(players, players_file) await self.bot.say("All cards sent out.")
async def convert(self, ctx, argument): # Try the local users first user = None matches = re.search(r"<@!?(\d+)>", argument) if matches: argument = matches.group(1) if isinstance(argument, int) or (isinstance(argument, str) and argument.isdigit()): user = ctx.bot.get_user(int(argument)) else: if len(argument) > 5 and argument[-5] == "#": discrim = argument[-4:] name = argument[:-5] predicate = lambda u: u.name == name and u.discriminator == discrim user = discord.utils.find(predicate, ctx.bot.users) else: predicate = lambda u: u.name == argument user = discord.utils.find(predicate, ctx.bot.users) if not user: data = await ctx.bot.cogs["Sharding"].handler( "fetch_user", 1, {"user_inp": argument}) if not data: raise commands.BadArgument("Unknown user.", argument) data = data[0] data["username"] = data["name"] user = discord.User(state=ctx.bot._connection, data=data) ctx.bot.users.append(user) ctx.user_data = await ctx.bot.pool.fetchrow( 'SELECT * FROM profile WHERE "user"=$1;', user.id) if ctx.user_data: return user else: raise UserHasNoChar("User has no character.", user)
async def convert(self, ctx, argument): # Try local users first user = None matches = re.search(r"<@!?(\d+)>", argument) if matches: argument = matches.group(1) if isinstance(argument, int) or (isinstance(argument, str) and argument.isdigit()): user = ctx.bot.get_user(int(argument)) else: if len(argument) > 5 and argument[-5] == "#": discrim = argument[-4:] name = argument[:-5] predicate = lambda u: u.name == name and u.discriminator == discrim user = discord.utils.find(predicate, ctx.bot.users) else: predicate = lambda u: u.name == argument user = discord.utils.find(predicate, ctx.bot.users) if user: return user data = await ctx.bot.cogs["Sharding"].handler("fetch_user", 1, {"user_inp": argument}) if not data: raise commands.BadArgument(ctx.message, argument) data = data[0] data["username"] = data["name"] user = discord.User(state=ctx.bot._connection, data=data) ctx.bot.users.append(user) return user
async def unban(self, ctx, user: int = None, *reason): '''Entbannt ein Mitglied mit einer Begründung (MOD ONLY) Es muss die Benutzer-ID angegeben werden, Name + Discriminator reicht nicht Beispiel: ----------- :unban 102815825781596160 ''' user = discord.User(id=user) if user is not None: if reason: reason = ' '.join(reason) else: reason = 'None' memberExtra = '{0} - *{1} ({2})*'.format(user.mention, user, user.id) await self.bot.send_message( self.bot.get_channel(loadconfig.__botlogchannel__), '`[{0}]` **:negative_squared_cross_mark:** {1} wurde entbannt vom Server {2} von {3}\n **Begründung:**```{4}```' .format(self._currenttime(), memberExtra, ctx.message.server, ctx.message.author, reason)) await self.bot.unban(ctx.message.server, user) else: tmp = await self.bot.say( '**:no_entry:** Du musst einen Benutzer spezifizieren!') await asyncio.sleep(15) await self.bot.delete_message(tmp)
async def convert(self): with open('data/danbooru/subs_old.db') as file: lines = file.readlines() if lines: for line in lines: sub = line.split('|') await self.bot.say( 'converting the following sub:`{}`'.format(sub[0])) server = self.bot.get_server(sub[3]) channel = self.bot.get_channel(sub[2]) users = sub[1].split(';') userlist = [] for user in users: if server: member = server.get_member(user) if not member: member = discord.User(id=user) userlist.append(member) tags = sub[0] tags = tags.split(' ') dansub = Dansub(userlist, tags, server, channel) dansub.old_timestamp = parser.parse(sub[4]) self.scheduler.subscriptions.append(dansub) dansub.write_sub_to_file() self.scheduler.write_to_file()
async def convert(self, message, bot, argument, discrim_required=False): match = self._get_id_match(argument) or re.match(r"<@!?([0-9]+)>$", argument) result = None state = message._state if match is not None: user_id = int(match.group(1)) result = bot.get_user(user_id) if result is None: try: data = await bot.bot_http.fetch_user(user_id) result = discord.User(state=bot._connection, data=data) except Exception: raise CommandError('User "{}" not found'.format(argument)) else: arg = argument # check for discriminator if it exists if len(arg) > 5 and arg[-5] == "#": discrim = arg[-4:] name = arg[:-5] predicate = lambda u: u.name == name and u.discriminator == discrim result = discord.utils.find(predicate, state._users.values()) if result is not None: return result if not discrim_required: predicate = lambda u: u.name == arg result = discord.utils.find(predicate, state._users.values()) if result is None: raise CommandError('User "{}" not found'.format(argument)) return result
async def check_reminders(): await dclient.wait_until_ready() while True: try: for row in db_ex.execute('SELECT id, loc_id, channel_user, message FROM reminder WHERE send_remind <= ' 'Datetime(?);', (datetime.now().strftime('%Y-%m-%d %X'), )): if row[2] == 'C': # remindall reminder_id = row[0] channel = dclient.get_channel(row[1]) message = row[3] await dclient.send_message(channel, message) db_ex.execute('DELETE FROM reminder WHERE id=?;', (reminder_id, )) db.commit() log.info('Reminder ID {} has been removed from the database!'.format(reminder_id)) else: # remindme reminder_id = row[0] user = discord.User(id=row[1]) message = row[3] await dclient.send_message(user, message) db_ex.execute('DELETE FROM reminder WHERE id=?;', (reminder_id, )) db.commit() log.info('Reminder ID {} has been removed from the database!'.format(reminder_id)) except sqlite3.Error: log.error('Unable to load reminders from the database!\n{}'.format(format_exc())) await asyncio.sleep(1)
async def check_reminders(self): await asyncio.sleep(60) serverid = self.reminders[0]["SERVER"] for server in self.bot.servers: if server.id == serverid: channel = server.get_channel(self.reminders[0]["CHANNEL"]) break while self is self.bot.get_cog("Reminder"): to_remove = [] for reminder in self.reminders[1:]: if reminder["FUTURE"] <= int(time.time()): try: await self.bot.send_message( channel, discord.User(id=reminder["ID"]).mention + " remember to {}".format(reminder["TEXT"])) except (discord.errors.Forbidden, discord.errors.NotFound): to_remove.append(reminder) except discord.errors.HTTPException: pass else: to_remove.append(reminder) for reminder in to_remove: self.reminders.remove(reminder) if to_remove: fileIO("data/reminder/reminders.json", "save", self.reminders) await asyncio.sleep(5)
async def prune_temp_channels(): global warned_channels while 1: old_channels = get_expired_channels(24 * 3600) for channel in old_channels: channel_id = str(channel["ChannelID"]) shinobu.log(channel) if channel_id not in warned_channels: try: await shinobu.send_message( shinobu.get_channel(channel_id), "This channel will soon be be pruned due to inactivity" ) except discord.errors.InvalidArgument as e: shinobu.log(e) delete_channel(channel_id) author_id = channel["ChannelCreator"] user = discord.User(id=author_id) await shinobu.send_message( user, "<#{}> will soon be deleted due to activity.".format( channel_id)) warned_channels.append(channel_id) else: shinobu.log("Deleting channel {}".format(channel_id)) delete_channel(channel_id) await shinobu.delete_channel(shinobu.get_channel(channel_id)) warned_channels.remove(channel_id) await asyncio.sleep(600)
async def pmannounce(self, ctx, *, message: str): """PM everyone subscribed an announcement""" person = self.subscribers for i, s in enumerate(person): msger = s["ID"] msger = msger[i] await self.bot.send_message(discord.User(id=msger), message)
def reminders_check_timer_event(client): print('In reminders_check_timer_event') f = open(Constants.REMINDERS_PATH, 'r+') lines = f.readlines() for line in lines: try: line_array = line.strip(' ').split(';') reminder_time_list = line_array[1].strip(' ').split('-') if reminder_expired(reminder_time_list): print('*********\nREMINDER HAS EXPIRED\n*********') user = discord.User(id=str(line_array[0].strip(' '))) msg = 'REMINDER: ' + line_array[2].strip(' ') send_msg = True f.seek(0) for line_ in lines: if line_ != line: f.write(line) f.truncate() f.close() # threading.Timer(Constants.REMINDERS_CHECK_POLLING_INTERVAL_SECS, reminders_check_timer_event, args=[client]).start() msg_list = [send_msg, user, msg] return msg_list except Exception as err: print('Exception: ' + str(err)) # threading.Timer(Constants.REMINDERS_CHECK_POLLING_INTERVAL_SECS, reminders_check_timer_event, args=[client]).start() msg_list = [False] return msg_list
def __init__(self, userId, userUrl): self.discordUser = discord.User() self.discordUser.id = userId self.id = userId self.kissUrl = userUrl self.malUrl = '' self.ttsChannel = ''
def __init__(self, payload: dict, client: discord.Client): self.client = client self.id: int = getattr(discord.utils, "_get_as_snowflake")(payload, "id") self.version = payload.get("version") self.type = payload.get("type") self.token = payload.get("token") self.application = getattr(discord.utils, "_get_as_snowflake")(payload, "application_id") self._state: ConnectionState = getattr(client, "_connection") self.guild_id = payload.get("guild_id") self.channel_id = payload.get("channel_id") if self.guild_id is not None: self.guild: Optional[discord.Guild] = self.client.get_guild(int(self.guild_id)) else: self.guild: Optional[discord.Guild] = None self.channel = self._state.get_channel(int(self.channel_id)) if self.guild is not None: member = payload.get("member") self.author = discord.Member(data=member, state=self._state, guild=self.guild) else: user = payload.get("user") self.author = discord.User(data=user, state=self._state) self.created_at = discord.utils.snowflake_time(self.id) self.deferred = False self.responded = False data = InteractionData(interaction_token=self.token, interaction_id=self.id, application_id=self.application) self.http = HttpClient(http=self.client.http, data=data)
async def check_completion(self): while 'PlantTycoon' in self.bot.cogs: now = int(time.time()) delete = False for id in self.gardeners: gardener = await self._gardener(id) if gardener.current: then = gardener.current['timestamp'] health = gardener.current['health'] grow_time = gardener.current['time'] badge = gardener.current['badge'] reward = gardener.current['reward'] if delete: delete = False if (now - then) > grow_time: self.gardeners[id]['points'] += reward if badge not in self.gardeners[id]['badges']: self.gardeners[id]['badges'].append(badge) message = 'Your plant made it! You are rewarded with the **{}** badge and you have recieved **{}** gro-cash.'.format( badge, reward) delete = True if health < 0: message = 'Your plant died!' delete = True if delete: await self.bot.send_message(discord.User(id=str(id)), message) self.gardeners[id]['current'] = False await self._save_gardeners() await asyncio.sleep(self.defaults['timers']['completion'] * 60)
def safe_get(id): get = requests.get(f'https://discord.com/api/v8/users/{id}', headers={'Authorization': f'Bot {auth.token}'}) if get.status_code == 200: user = discord.User(state=client._connection, data=get.json()) return user return False
def __init__(self, *, cog, data: dict): self.cog = cog self.bot = cog.bot self.http: SlashHTTP = cog.http self._state: discord.state.AutoShardedConnectionState = self.bot._connection self.id = int(data["id"]) self.version = data["version"] self.__token = data["token"] self._original_data = data self.guild_id = guild_id = discord.utils._get_as_snowflake(data, "guild_id") self.channel_id = discord.utils._get_as_snowflake(data, "channel_id") if guild_id: member_data = data["member"] self.author_id = int(member_data["user"]["id"]) self.author = discord.Member(data=member_data, state=self._state, guild=self.guild) else: member_data = data["user"] self.author_id = int(member_data["id"]) self.author = discord.User(data=member_data, state=self._state) self.sent = False self.interaction_data = interaction_data = data["data"] self.command_name = interaction_data["name"] self.command_id = int(interaction_data["id"]) self.options: List[ResponseOption] = [] self._parse_options( interaction_data.get("options", []), interaction_data.get("resolved", {}) )
async def _get_member(self, user_id): # # Return a member object # return discord.User(id=str(id)) # I made it a string just to be sure
def __init__(self, *, cog, data: dict): self.cog = cog self.bot = cog.bot self.http: SlashHTTP = cog.http self._state: discord.state.AutoShardedConnectionState = self.bot._connection self.id = int(data["id"]) self.version = data["version"] self._token = data["token"] self._original_data = data self.guild_id = guild_id = discord.utils._get_as_snowflake( data, "guild_id") self.channel_id = discord.utils._get_as_snowflake(data, "channel_id") self.application_id = discord.utils._get_as_snowflake( data, "application_id") if guild_id: member_data = data["member"] self.author_id = int(member_data["user"]["id"]) self.author = discord.Member(data=member_data, state=self._state, guild=self.guild) else: member_data = data["user"] self.author_id = int(member_data["id"]) self.author = discord.User(data=member_data, state=self._state) self.interaction_data = data["data"] self.sent = False self.deferred = False self.completed = False
async def get_user(self, ctx, user): """Send the username whatever argument is given.""" try: user = discord.User(state=user) except: user = await self.bot.fetch_user(id) await ctx.send(user)
def create_sub_from_file(self, json_path): with open(json_path) as sub_file: data = json.load(sub_file) user_list = [] if 'is_private' in data and bool(data['is_private']): is_private = True id = data['users']['0']['id'] name = data['users']['0']['name'] user_list.append(discord.User(username=name, id=id)) else: is_private = False if os.path.exists('data/danbooru/sub_channel.json'): with open('data/danbooru/sub_channel.json', 'r') as f: sub_channel_file = json.load(f) server = self.bot.get_server(sub_channel_file['server']) channel = self.bot.get_channel(sub_channel_file['channel']) else: server = self.bot.get_server(data['server']) channel = self.bot.get_channel(data['channel']) for user in data['users']: # try to get the member through Discord and their ID member = server.get_member(data['users'][user]['id']) # if that fails create own user with the necessary information if member == None: id = data['users'][user]['id'] name = data['users'][user]['name'] member = discord.User(username=name, id=id) user_list.append(member) tags = data['tags'] timestamp = data['old_timestamp'] if 'pools' in data: pools = data['pools'] else: pools = [] if is_private: retrieved_sub = Dansub(user_list, tags, pools, None, None, is_private) else: retrieved_sub = Dansub(user_list, tags, pools, server, channel, is_private) if timestamp != 'None': retrieved_sub.old_timestamp = parser.parse(timestamp) return retrieved_sub
def _store_user(self, data): user_id = int(data["id"]) try: return self._users[user_id] except: user = dpy.User(state=self, data=data) if (data["discriminator"] != "0000") and (not data.get("bot")): self._users[user_id] = user return user
async def softban(self, ctx, member: discord.Member): """Bans a member from the server, then unbans them. Equivalent to kicking and deleting 2 days worth of their messages. """ unban = member.id await self.bot.ban(member, delete_message_days=2) await self.bot.unban(ctx.message.server, discord.User(id=unban)) msg = "Softbanned {}".format(member.name) await self.bot.say(msg)