def _reaction_removed(self, reaction: discord.Reaction, user: discord.User):
if self.setting_emojis: return # Don't change karma whilst adding/removing emojis
server = reaction.message.server
author = reaction.message.author
if author == user: return # Users can't change their own karma
emoji = reaction.emoji
if isinstance(emoji, discord.Emoji):
emoji = emoji.name
else:
emoji = name(emoji)
try:
if emoji == self.settings[server.id][UPVOTE]:
self._add_karma(author.id, -1)
elif emoji == self.settings[server.id][DOWNVOTE]:
self._add_karma(author.id, 1)
except:
return
python类User()的实例源码
def add(self, ctx, user: discord.User):
"""Add a co-owner by mentioning them"""
self.bot.say("Are you sure you want to add **{}** as a co-owner?".format(user.display_name))
confirm = await self._confirm_owner(ctx)
if not confirm:
return
if user.id not in self.settings["USERS"]:
self.settings["USERS"][user.id] = {"RESTRICTED" : []}
dataIO.save_json(self.path, self.settings)
await self.bot.say("**{0.display_name}** *<{0.id}>* has been added as a co-owner".format(user))
return
elif user.id in self.settings["USERS"]:
await self.bot.say("That user is already a co-owner")
return
def deluser(self, ctx, user: discord.User, *, command):
"""Removes restriction on [command] for [user]"""
confirm = await self._confirm_owner(ctx)
if not confirm:
return
if user and user.id in self.settings["USERS"]:
pass
else:
await self.bot.say("That user is not a co-owner.")
return
if command in self.settings["USERS"][user.id]["RESTRICTED"]:
await self.bot.say("**{}** has been removed from {}'s' restricted list".format(command, user.display_name))
self.settings["USERS"][user.id]["RESTRICTED"].remove(command)
dataIO.save_json(self.path, self.settings)
elif command not in self.settings["USERS"][user.id]["RESTRICTED"]:
await self.bot.say("{} is not a restricted command for {}".format(command, user.display_name))
else:
await self.bot.say("{} is not a valid command.".format(command))
pass
def user_is_registered(self, user):
"""Checks whether a ?User? is registered in the database.
Parameters
----------
user
Can be a Discord `User` object or `Member` object, or a user ID.
"""
if isinstance(user, discord.User) or isinstance(user, discord.Member):
try:
get_user_model().objects.get(id=user.id)
return True
except get_user_model().DoesNotExist:
return False
else:
try:
get_user_model().objects.get(id=user)
return True
except get_user_model().DoesNotExist:
return False
def get_member(self, member=None, user=None, guild=None):
"""Retrieves a Dwarf ?Member? object from the database.
Either ?member? or both ?user? and ?guild? must be given as arguments.
Parameters
----------
member : Optional
Has to be a Discord ?Member? object.
user : Optional
Can be a Discord `User` object or a user ID.
guild : Optional
Can be a Discord ?Server? object or a guild ID.
"""
if isinstance(member, discord.Member):
user_id = member.id
guild_id = member.server.id
else:
if user is None or guild is None:
raise ValueError("Either a Member object or both user ID "
"and guild ID must be given as argument(s).")
if isinstance(user, discord.User):
user_id = user.id
else:
user_id = user
if isinstance(guild, discord.Server):
guild_id = guild.id
else:
guild_id = guild
return Member.objects.get(user=user_id, guild=guild_id)
def _add_quote(self, ctx, author, message):
sid = ctx.message.server.id
aid = ctx.message.author.id
if sid not in self.quotes:
self.quotes[sid] = []
author_name = 'Unknown'
author_id = None
if isinstance(author, discord.User):
author_name = author.display_name
author_id = author.id
elif isinstance(author, str):
author_name = author
quote = {'added_by': aid,
'author_name': author_name,
'author_id': author_id,
'text': escape_mass_mentions(message)}
self.quotes[sid].append(quote)
dataIO.save_json(JSON, self.quotes)
def __init__(self, bot: HahaNoUR, user: User,
box: str = "honour", count: int = 1,
guaranteed_sr: bool = False, args: tuple = ()):
"""
Constructor for a Scout.
:param session_manager: the SessionManager.
:param user: User requesting scout.
:param box: Box to scout in (honour, regular, coupon).
:param count: Number of cards in scout.
:param guaranteed_sr: Whether the scout will roll at least one SR.
:param args: Scout command arguments
"""
self.results = []
self._bot = bot
self._user = user
self._box = box
self._count = count
self._guaranteed_sr = guaranteed_sr
self._args = parse_arguments(args, True)
def _apply_filter(album: list, user: User):
"""
Applys a user's filters to a card album, removing anything not matching
the filter.
:param album: Album being filtered.
:param user: User who requested the album.
:return: Filtered album.
"""
filters = _last_user_args[user.id]['filters']
for filter_type in filters:
filter_values = filters[filter_type]
if not filter_values:
continue
# Looping backwards since we are removing elements
for i in range(len(album) - 1, -1, -1):
# Generic case
if album[i][filter_type] not in filter_values:
album.pop(i)
return album
def _splice_page(album: list, user: User) -> list:
"""
Splices a user's last requested page out of their album.
:param album: Album being spliced
:param user: User who requested the album.
:return: Spliced album.
"""
page = _last_user_args[user.id]['page']
max_page = int(math.ceil(len(album) / PAGE_SIZE)) - 1
if page > max_page:
page = max_page
if page < 0:
page = 0
_last_user_args[user.id]['page'] = page
start = PAGE_SIZE * page
end = (PAGE_SIZE * page) + PAGE_SIZE
return album[start:end]
def can_use_command(cmd: Command, author, channel: discord.Channel=None):
""" Return True if the member who sent the message can use this command. """
if cmd.owner and not is_owner(author):
return False
if channel is not None and not has_permissions(cmd, author, channel):
return False
if not has_roles(cmd, author):
return False
# Handle server specific commands for both server and PM commands
if type(author) is discord.User and cmd.servers:
return False
if type(author) is discord.Member and not is_valid_server(cmd, author.server):
return False
return True
def temp_channel_timeout():
await dclient.wait_until_ready()
while not dclient.is_closed:
try:
for channel in con_ex.execute("SELECT * FROM temp_channel WHERE date <= Datetime('{}');".format(
datetime.now().strftime('%Y-%m-%d %X'))):
remove_channel = dclient.get_channel(channel[0])
channel_name = channel[1]
owner = discord.User(id=channel[2])
await dclient.delete_channel(remove_channel)
con_ex.execute('DELETE FROM temp_channel WHERE id={};'.format(channel[0]))
con.commit()
await dclient.send_message(owner, 'Channel `{}` has expired and has been removed!'.format(channel_name))
log('TEMP_CHANNEL', 'Removed ID {} from database.'.format(channel[0]))
except sqlite3.Error as ex:
print('[{}]: {} - {}'.format(strftime("%b %d, %Y %X", localtime()), 'SQLITE',
'Error when trying to select/delete data: ' + ex.args[0]))
log_file.write('[{}]: {} - {}\n'.format(strftime("%b %d, %Y %X", localtime()), 'SQLITE',
'Error when trying to insert/delete data: ' + ex.args[0]))
await asyncio.sleep(1)
# Auto remove temporary channel from database if an admin force removes it from the server
def is_global_banned(self, user: discord.User) -> bool:
key = f'cache:globalbans:{user.id}'
if await self.redis.exists(key):
# use the cached value instead
return await self.redis.get(key, encoding='utf-8') == 'banned'
async with self.pgpool.acquire() as conn:
# grab the record from postgres, if any
banned = (await conn.fetchrow('SELECT * FROM globalbans WHERE user_id = $1', user.id)) is not None
# cache the banned value for 2 hours
await self.redis.set(key, 'banned' if banned else 'not banned', expire=7200)
# return whether banned or not
return banned
def format_member_departure(self, member: discord.Member, *, verb: str = 'left', emoji: str ='\N{OUTBOX TRAY}') -> str:
"""
Formats a member's departure from the server. Can be customized.
This function automatically adds the basketball emoji before the member's description if the joined recently.
If the provided member is a ``discord.User``, the joined and basketball emoji are always omitted.
Account creation information is always shown.
:param member: The member who left.
:param verb: The verb to append right after the name. For example, providing "was banned" will format the
departure as "User#1234 was banned [...]"
:param emoji: The emoji to place before the user's description.
:return: The formatted departure.
"""
# if it's a user, return bare info
if isinstance(member, discord.User):
return f'{emoji} {describe(member, before=verb, created=True)}'
# did they bounce?
bounce = '\U0001f3c0 ' if (datetime.datetime.utcnow() - member.joined_at).total_seconds() <= 1500 else ''
return f'{emoji} {bounce}{describe(member, before=verb, created=True, joined=True)}'
def sleep(ctx, member: discord.Member = None):
if member is None:
member = ctx.message.author
if member.id == '127188004216373248' or member.id == '126899976042184705' or member.id == '127010252934610944' or member.id == '146720848424861696':
await bot.type()
await asyncio.sleep(2)
await bot.say( "What, you don't like me?")
user = discord.User()
user.id = 127188004216373248
await bot.send_message(user, "I'm down")
print('message recieved')
bot.close()
exit()
else:
await bot.type()
await asyncio.sleep(2)
await bot.say("http://www.ozsticker.com/ozebayimages/620_dave_product.jpg")
def for_user(self, user):
"""
Returns the first PermissionGroup a user belongs to
:param user: A discord User or Member object
"""
for group in self.groups:
if user.id in group.user_list:
return group
# The only way I could search for roles is if I add a `server=None` param and pass that too
if type(user) == discord_User:
return self.default_group
# We loop again so that we don't return a role based group before we find an assigned one
for group in self.groups:
for role in user.roles:
if role.id in group.granted_to_roles:
return group
return self.default_group
def stealreset(self, ctx, *people: discord.User):
"""Reset someone's state in steal-related collections.
Deletes cooldowns, points and grace, resetting them
(cooldowns and points) to default on the person's
next use of j!steal.
"""
for person in people:
# don't repeat stuff lol
uobj = {'user_id': person.id}
cd_del = await self.cooldown_coll.delete_one(uobj)
pt_del = await self.points_coll.delete_one(uobj)
gr_del = await self.grace_coll.delete_one(uobj)
await ctx.send(f'Deleted {cd_del.deleted_count} documents in `cooldown`\n'
f'- {pt_del.deleted_count} in `points`\n'
f'- {gr_del.deleted_count} in `graces`')
def write(self, ctx, person: discord.User, amount: decimal.Decimal):
"""Overwrite someone's wallet.
This command does not check for incorrect values (like -2 or infinity).
"""
account = await self.get_account(person.id)
if account is None:
raise self.SayException('account not found you dumbass')
amount = round(amount, 3)
await self.jcoin_coll.update_one({'id': person.id},
{'$set': {'amount': str(amount)}})
self.cache_invalidate(person.id)
await ctx.send(f'Set {self.get_name(account["id"])} to {amount}')
def trigger_set_user(self, ctx: commands.Context,
user: discord.User):
"""Trigger if a message is from some user."""
emojis = await self._get_trigger_emojis(ctx)
if emojis:
self.triggers["user_triggers"][user.id] = emojis
_save(self.triggers)
emojis_str = " ".join(str(self._lookup_emoji(emoji)) for emoji in emojis)
await self.bot.say("Done - I will now react to messages from `{user}` with"
" {emojis}.".format(user=str(user),
emojis=emojis_str))
elif user.id in self.triggers['user_triggers']:
del self.triggers['user_triggers'][user.id]
_save(self.triggers)
await self.bot.say("Done - I will no longer react to messages from `{user}`."
"".format(user=str(user)))
else:
await self.bot.say("Done - no triggers were changed.")
def _reaction_added(self, reaction: discord.Reaction, user: discord.User):
if self.setting_emojis: return # Don't change karma whilst adding/removing emojis
server = reaction.message.server
author = reaction.message.author
if author == user: return # Users can't change their own karma
emoji = reaction.emoji
if isinstance(emoji, discord.Emoji):
emoji = emoji.name
else:
emoji = name(emoji)
try:
if emoji == self.settings[server.id][UPVOTE]:
self._add_karma(author.id, 1)
elif emoji == self.settings[server.id][DOWNVOTE]:
self._add_karma(author.id, -1)
except:
return
def __init__(self, app, parent, user, name):
"""
The widget within each tab of TabWindow, a display
for new private messages and user input
"""
super(__class__, self).__init__()
uic.loadUi(app.theme["ui_path"] + "/PrivateMessageWidget.ui", self)
self.user = user
self.app = app
self.parent = parent
# setattr(user, "display_name", friend)
self.userLabel.setText(name.join(["::", "::"]))
self.sendButton.clicked.connect(self.send)
self.userOutput.setReadOnly(True)
self.userOutput.setMouseTracking(True)
self.userOutput.anchorClicked.connect(self.anchorClicked)
self.userOutput.setOpenLinks(False)
if not isinstance(user, discord.PrivateChannel):
self.display_text(fmt_begin_msg(app, self.app.client.user, user.user if not isinstance(user, discord.User) else user))
ensure_future(self.get_logs())
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
await ctx.guild.unban(user, reason=reason)
else:
await ctx.send('**:no_entry:** Kein Benutzer angegeben!')
def bans(self, ctx):
'''Listet aktuell gebannte User auf (MOD ONLY)'''
users = await ctx.guild.bans()
if len(users) > 0:
msg = f'`{"ID":21}{"Name":25} Begründung\n'
for entry in users:
userID = entry.user.id
userName = str(entry.user)
if entry.user.bot:
username = '??' + userName #:robot: emoji
reason = str(entry.reason) #Could be None
msg += f'{userID:<21}{userName:25} {reason}\n'
embed = discord.Embed(color=0xe74c3c) #Red
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(text=f'Server: {ctx.guild.name}')
embed.add_field(name='Ranks', value=msg + '`', inline=True)
await ctx.send(embed=embed)
else:
await ctx.send('**:negative_squared_cross_mark:** Es gibt keine gebannten Nutzer!')
def perminfo(self, ctx, chn: discord.TextChannel=None, usr: discord.User=None):
"""Show permissions for a user."""
if usr is None:
usr = ctx.message.author
if chn is None:
chn = ctx.message.channel
perms = chn.permissions_for(usr)
info = utils.InfoBuilder()
for perm, value in perms:
info.add_field(perm.replace("_", " ").title(), value)
info.add_field("Value", "{:b}".format(perms.value))
await ctx.send(info.code_block())
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 _save_answer(self, server_id: str, survey_id: str, user: discord.User,
answer: str, change: bool) -> bool:
answers = self.surveys[server_id][survey_id]["answers"]
asked = self.surveys[server_id][survey_id]["asked"]
options = self.surveys[server_id][survey_id]["options"]
if change:
for a in answers.values():
if user.id in a:
a.remove(user.id)
if options != "any":
limit = options[answer]["limit"]
if answer not in answers:
answers[answer] = []
if answer in options and limit and len(answers[answer]) >= int(limit):
return False
answers[answer].append(user.id)
if user.id in asked:
asked.remove(user.id)
dataIO.save_json(self.surveys_path, self.surveys)
return True
def check_reminders(self):
while self is self.bot.get_cog("RemindMe"):
to_remove = []
for reminder in self.reminders:
if reminder["FUTURE"] <= int(time.time()):
try:
await self.bot.send_message(discord.User(id=reminder["ID"]), "You asked me to remind you this:\n{}".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/remindme/reminders.json", "save", self.reminders)
await asyncio.sleep(5)
def adduser(self, ctx, user: discord.User, *, command):
"""Restrict user from using [command]"""
confirm = await self._confirm_owner(ctx)
if not confirm:
return
AliasCog = self.bot.get_cog('Alias')
server = ctx.message.server
valid = True if self.bot.get_command(command) else False
if not valid:
valid = True if command in AliasCog.aliases[server.id] else False
if user and user.id in self.settings["USERS"]:
pass
else:
await self.bot.say("That user is not a co-owner.")
return
if valid and command not in self.settings["USERS"][user.id]["RESTRICTED"]:
await self.bot.say("**{} will be restricted from using**: {}".format(user.display_name, command))
self.settings["USERS"][user.id]["RESTRICTED"].append(command)
dataIO.save_json(self.path, self.settings)
elif command in self.settings["RESTRICTED"]:
await self.bot.say("{} is already a restricted command for {}".format(command, user.display_name))
else:
await self.bot.say("{} is not a valid command.".format(command))