Python discord 模块,User() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.User()。
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
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, 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, 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, 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, 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,
'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,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, *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, 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, 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, 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, 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,
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, *, 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))
def get_user(self, user):
"""Retrieves a Dwarf `User` object from the database.
Parameters
----------
user
Can be a Discord `User` object or `Member` object, discord.Member):
return get_user_model().objects.get_or_create(id=user.id)
else:
return get_user_model().objects.get_or_create(id=user)
def new_member(self, guild=None):
"""Creates a new Dwarf ?Member? object and connects it to 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.Server):
guild_id = guild.id
else:
guild_id = guild
return Member(user=user_id, guild=guild_id)
def user_warning(channel, warnings, max_warnings):
"""
Creates an embed UI containing an user warning message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
user (discord.User): The user to warn
warnings (str): The warnings for the user
max_warnings (str): The maximum warnings for the user
Returns:
ui (ui_embed.UI): The embed UI object
"""
username = user.name
if isinstance(user, discord.Member):
if user.nick is not None:
username = user.nick
warning_count_text = "warnings" if warnings != 1 else "warning"
warning_text = "{} {}".format(warnings, warning_count_text)
result_text = "at {} you will be banned".format(max_warnings)
if warnings >= max_warnings:
result_text = "you are being banned because you have more than the maximum warnings"
# Create embed UI object
gui = ui_embed.UI(
channel,
"Warning {}".format(username),
"You now have {} {},{}".format(warning_text, username, result_text),
modulename=modulename
)
return gui
def user_ban(channel, user):
"""
Creates an embed UI containing an user warning message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
user (discord.User): The user to ban
Returns:
ui (ui_embed.UI): The embed UI object
"""
username = user.name
if isinstance(user, discord.Member):
if user.nick is not None:
username = user.nick
# Create embed UI object
gui = ui_embed.UI(
channel,
"Banned {}".format(username),
"{} has been banned from this server".format(username),
modulename=modulename
)
return gui
def get_raid_members(channel):
"""Gets the raid members in this channel."""
return [target for target, _ in channel.overwrites if isinstance(target, discord.User)]
def is_admin(self, user: discord.User):
"""
Check if a user is an admin
:param user: the user to check
:return: is an admin or not?
"""
return user.id in self.admins
def is_muted(self, user: discord.User):
"""
Check if a user is prevented from using emotes
:param user: the user to check
:return: is muted?
"""
return user in self.muted
def _get_random_author_quote(self, author):
sid = ctx.message.server.id
if sid not in self.quotes or len(self.quotes[sid]) == 0:
raise AssertionError("There are no quotes in this server!")
if isinstance(author, discord.User):
uid = author.id
quotes = [(i, q) for i, q in enumerate(self.quotes[sid]) if q['author_id'] == uid]
else:
quotes = [(i, q in enumerate(self.quotes[sid]) if q['author_name'] == author]
if len(quotes) == 0:
raise commands.BadArgument("There are no quotes by %s." % author)
return randchoice(quotes)
def _apply_sort(album: list, user: User) -> list:
"""
Applys a user's sort to a card album.
:param album: Album being sorted.
:param user: User who requested the album.
:return: Sorted album.
"""
sort = _last_user_args[user.id]['sort']
# FIXME This var doesn't seem to have any use.
order = _last_user_args[user.id]['order']
if not sort:
return album
if sort == 'date':
sort = 'release_date'
if sort == 'unit':
sort = 'main_unit'
if sort == 'subunit':
sort = 'sub_unit'
if sort == 'newest':
sort = 'time_aquired'
sort_descending = sort in [
'rarity',
'attribute',
'release_date',
'time_aquired',
'main_unit',
'sub_unit'
]
return sorted(album, key=itemgetter(sort, 'id'), reverse=sort_descending)
def dispatch(self, event, *args, **kwargs):
""" Override event dispatch to handle plugin events. """
# Exclude blank messages
if event == "message":
message = args[0]
if not message.content:
return
# Find every event that has a discord.Member argument,and filter out bots and self
member = None
for arg in list(args) + list(kwargs.values()):
if isinstance(arg, discord.User):
member = arg
break
elif isinstance(arg, discord.Message):
member = arg.author
break
super().dispatch(event, **kwargs)
# We get the method name and look through our plugins' event listeners
method = "on_" + event
if method in plugins.events:
for func in plugins.events[method]:
# We'll only ignore bot messages if the event has disabled for bots
if member and member.bot and not func.bot:
continue
# Same goes for messages sent by ourselves. Naturally this requires func.bot == True
if member and member == client.user and not func.self:
continue
client.loop.create_task(self._handle_event(func, **kwargs))
def format_objects(*objects, attr=None, dec: str="", sep: str=None):
""" Return a formatted string of objects (User,Member,Channel or Server) using
the given decorator and the given separator.
:param objects: Any object with attributes,preferably User,Channel or Server.
:param attr: The attribute to get from any object. Defaults to object names.
:param dec: String to decorate around each object.
:param sep: Separator between each argument.
:return: str: the formatted objects.
"""
if not objects:
return
first_object = objects[0]
if attr is None:
if isinstance(first_object, discord.User):
attr = "display_name"
elif isinstance(first_object, discord.Channel) or isinstance(first_object, discord.Role):
attr = "mention"
sep = " "
elif isinstance(first_object, discord.Server):
attr = "name"
sep = sep if sep is not None else ","
return sep.join(dec + getattr(m, attr) + dec for m in objects)
def is_owner(user: discord.User):
""" Return true if user/member is the assigned bot owner.
:param user: discord.User,discord.Member or a str representing the user's ID.
:raises: TypeError: user is wrong type.
"""
if isinstance(user, discord.User):
user = user.id
elif type(user) is not str:
raise TypeError("member must be an instance of discord.User or a str representing the user's ID.")
if user == owner_cfg.data:
return True
return False
def _add_event(self, name, command, dest_server, dest_channel,
author, timedelta, repeat=False):
if isinstance(dest_server, discord.Server):
dest_server = dest_server.id
if isinstance(dest_channel, discord.Channel):
dest_channel = dest_channel.id
if isinstance(author, discord.User):
author = author.id
if dest_server not in self.events:
self.events[dest_server] = {}
event_dict = {'name': name,
'channel': dest_channel,
'author': author,
'command': command,
'timedelta': timedelta,
'repeat': repeat}
log.debug('event dict:\n\t{}'.format(event_dict))
now = int(time.time())
event_dict['starttime'] = now
self.events[dest_server][name] = event_dict.copy()
event_dict['server'] = dest_server
e = Event(event_dict.copy())
await self._put_event(e)
self.save_events()
def check_remindme():
await dclient.wait_until_ready()
while not dclient.is_closed:
try:
for reminders in con_ex.execute("SELECT * FROM reminder WHERE date <= Datetime('{}');".format(
datetime.now().strftime('%Y-%m-%d %X'))):
if reminders[1] == '0': # ME type
user = discord.User(id=reminders[2])
await dclient.send_message(user, '{}'.format(reminders[3]))
con_ex.execute('DELETE FROM reminder WHERE id={};'.format(reminders[0]))
con.commit()
log('REMINDER', 'Removed ID {} from database.'.format(reminders[0]))
elif reminders[1] == '1': # ALL type
user = dclient.get_channel(reminders[2])
await dclient.send_message(user, 'Removed ID {} from database.'.format(reminders[0]))
except sqlite3.Error as ex:
print('[{}]: {} - {}'.format(strftime("%b %d,
'Error when trying to insert/delete data: ' + ex.args[0]))
await asyncio.sleep(1)
# Custom cmd setup
def confirm(self, title: str, description: str, confirm_cancellation=False):
"""Confirms something."""
embed = discord.Embed(color=discord.Color.red(), title=title, description=description)
confirmation = await self.send(embed=embed)
for tick in (self.bot.tick(tick_type, raw=True, guild=self.guild) for tick_type in ('green', 'red')):
await confirmation.add_reaction(tick)
while True:
def check(reaction: discord.Reaction, adder: discord.User) -> bool:
return adder == self.message.author and reaction.message.id == confirmation.id
# wait for a reaction
reaction, adder = await self.bot.wait_for('reaction_add', check=check)
# ignore regular emoji
if isinstance(reaction.emoji, str):
continue
if reaction.emoji.id == 318595000311087105:
await confirmation.delete()
return True
elif reaction.emoji.id == 318595010385674240:
await confirmation.delete()
if confirm_cancellation:
await self.send('Operation cancelled.')
return False
def member_is_moderator(member: discord.Member) -> bool:
"""Returns whether a :class:`discord.Member` is a "Dogbot Moderator"."""
if isinstance(member, discord.User) or not member.guild:
return False
names = [r.name for r in member.roles]
has_moderator_role = any(name in mod_names for name in names)
has_manage_server = member.guild_permissions.manage_guild
is_server_owner = member.guild.owner == member
return has_moderator_role or has_manage_server or is_server_owner
def quoteadd(self, target: discord.User, text: str):
"""Add a quote.
Usage: quoteadd [member] [text here]"""
if len(text) > 360:
await ctx.send(ctx.mention + ' Your text is too long!')
return
if target == self.bot.user:
if not check_perms(ctx, ('bot_owner',)):
await ctx.send(ctx.mention + ' You can\'t add a quote as me!')
return
fmt_time = [int(i) for i in time.strftime("%m/%d/%Y").split('/')]
q_template = {
'id': 0,
'quote': 'Say-whaaaa?',
'author': ctx.author.display_name,
'author_ids': [''],
'date': fmt_time
}
mauthor = target
q_template['quote'] = text.replace('\n', ' ').replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
q_template['author'] = mauthor.display_name
if mauthor.display_name != mauthor.name:
q_template['author'] += ' (' + mauthor.name + ')'
q_template['author_ids'] = [mauthor.id, ctx.author.id]
q_template['id'] = len(self.bot.store['quotes']) # +1 for next id,but len() counts from 1
self.bot.store['quotes'].append(q_template)
await ctx.send(f'Quote **#{q_template["id"] + 1}** added!')
def avatar(self, target: discord.User):
"""Get someone's avatar.
Usage: avatar [member]"""
await ctx.send(target.avatar_url)
def nick(self, nick: str):
"""Set your nickname.
Usage: nick [new nickname]"""
if ctx.author.guild_permissions.change_nickname:
await ctx.author.edit(nick=nick, reason='User requested using command')
await ctx.send(':thumbsup: Done.')
else:
await ctx.send(':x: You don\'t have permission to change your nickname.')
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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。