Python discord 模块,PrivateChannel() 实例源码
我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用discord.PrivateChannel()。
def on_channel_update(self, before, after):
if type(before) is discord.PrivateChannel:
return
entries = []
if before.name != after.name:
entries.append('Channel rename: %s renamed to %s' %
(before, after))
if before.topic != after.topic:
entries.append('Channel topic: %s topic was set to "%s"' %
(before, after.topic))
if before.position != after.position:
entries.append('Channel position: {0.name} moved from {0.position} '
'to {1.position}'.format(before, after))
# Todo: channel permissions overrides
for e in entries:
await self.log(before.server, e)
def get_response(message, send_typing=True):
"""Gets a response. Split up so messages can be edited."""
# Check if the message is a valid command and the server or channel is not muted
if (message.content and message.content[0] in configmanager.config['command_invokers'] and message.author.id != client.user.id): # Valid invoker from not the bot
is_private = (type(message.channel) is discord.PrivateChannel)
if parser.is_command(message.content.partition(' ')[0][1:].lower(), private=is_private): # Valid command
if is_private or (not is_private and # Private - skip checks. Not private - do server checks.
not servermanager.is_banned(server_id=message.server.id, user_id=message.author.id) and # Author is not banned
(not servermanager.is_muted(server_id=message.server.id, channel_id=message.channel.id) or # Server or channel is not muted or
(servermanager.is_admin(message.server.id, message.author.id) and message.content[1:].startswith('admin')))): # Admin is unmuting bot
try:
global last_responses_dictionary
if send_typing:
await client.send_typing(message.channel)
return await parser.parse(
message.content,
message.server.id if not is_private else '0',
message.channel.id if not is_private else '0',
message.author.id if not is_private else '0',
message.author.voice_channel.id if (not is_private and message.author.voice_channel) else 0, # PrevIoUsly type None
is_private)
except bot_exception as e: # Something bad happened
return [str(e), False]
return ['', False]
def on_message(self, message):
"""Called on `Client.on_message`,Message handling happens here"""
if message.content.startswith("_") and message.content.endswith("_"):
message.content = "/me " + message.content[1:-1]
if isinstance(message.channel, discord.PrivateChannel):
if not message.channel.name:
message.channel.name = ",".join(map(lambda m: m.display_name, message.channel.recipients))
if message.channel.type is discord.ChannelType.group:
tab = self.gui.start_privmsg(message.channel)
else:
tab = self.gui.start_privmsg(message.channel)
fmt = fmt_disp_msg(self, message.content, message, user=message.author)
if fmt:
tab.display_text(fmt)
else:
if self.gui.memosWindow:
if message.server in self.gui.memosWindow.open.keys():
fmt = fmt_disp_msg(self, user=message.author)
if fmt:
try:
self.gui.memosWindow.display_message(message.channel, fmt)
except AttributeError as e:
print(e)
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 is_owner(ctx):
"""Check owner."""
if isinstance(ctx.message.channel, discord.PrivateChannel):
# Yes,I keep a "backdoor" in the bot
author = ctx.message.author
return author.name + "#" + author.discriminator == "Maël Pedretti#1416"
return ctx.message.channel.server.owner == ctx.message.author
def should_log(self, location):
if self.settings.get('everything', False):
return True
default = self.settings.get('default', False)
if type(location) is discord.Server:
if location.id in self.settings:
loc = self.settings[location.id]
return loc.get('all', False) or loc.get('events', default)
elif type(location) is discord.Channel:
if location.server.id in self.settings:
loc = self.settings[location.server.id]
opts = [loc.get('all', False), loc.get(location.id, default)]
if location.type is discord.ChannelType.voice:
opts.append(loc.get('voice', False))
return any(opts)
elif type(location) is discord.PrivateChannel:
return self.settings.get('direct', default)
else: # can't log other types
return False
def process_attachment(self, message):
a = message.attachments[0]
aid = a['id']
aname = a['filename']
url = a['url']
channel = message.channel
path = PATH_LIST.copy()
if type(channel) is discord.Channel:
serverid = channel.server.id
elif type(channel) is discord.PrivateChannel:
serverid = 'direct'
path += [serverid, channel.id + '_attachments']
path = os.path.join(*path)
filename = aid + '_' + aname
if len(filename) > 255:
target_len = 255 - len(aid) - 4
part_a = target_len // 2
part_b = target_len - part_a
filename = aid + '_' + aname[:part_a] + '...' + aname[-part_b:]
truncated = True
else:
truncated = False
return aid, url, path, filename, truncated
def log(self, location, text, timestamp=None, force=False, subfolder=None, mode='a'):
if not timestamp:
timestamp = datetime.utcNow()
if self.lock or not (force or self.should_log(location)):
return
path = PATH_LIST.copy()
entry = [timestamp.strftime(TIMESTAMP_FORMAT)]
if type(location) is discord.Server:
path += [location.id, 'server.log']
elif type(location) is discord.Channel:
serverid = location.server.id
entry.append('#' + location.name)
path += [serverid, location.id + '.log']
elif type(location) is discord.PrivateChannel:
path += ['direct', location.id + '.log']
else:
return
if subfolder:
path.insert(-1, str(subfolder))
text = text.replace('\n', '\\n')
entry.append(text)
fname = os.path.join(*path)
handle = self.gethandle(fname, mode=mode)
await handle.write(' '.join(entry) + '\n')
def _command_check(self, ctx):
# if the channel is not private,delete the command immediately regardless of the response
if not isinstance(ctx.message.channel, discord.PrivateChannel):
self._bot.loop.create_task(self._bot.client.delete_message(ctx.message))
# if privileged,check the member role
if hasattr(ctx.command, 'privileged'):
if not self._bot.is_operator(ctx.message.author):
raise dec.CommandError('You don\'t have a permission to use the *{}* command'.format(ctx.command))
return True
#
# Listeners
#
def _on_command_error(self, exception, ctx):
# non-existing commands won't trigger check thus are not deleted
if isinstance(exception, dec.CommandNotFound) and not isinstance(ctx.message.channel, discord.PrivateChannel):
await self._bot.client.delete_message(ctx.message)
# get a cause if the exception was thrown inside the command routine
if isinstance(exception, dec.CommandInvokeError):
exception = exception.__cause__
# Now inform the author of the command on the failure using PMs
await self._bot.client.send_message(ctx.message.author, str(exception))
# log the error for debugging purposes
log.debug('Command \'{}\' invoked by {} raised an exception\n{}'
.format(ctx.command, ctx.message.author, ctx.message.content), exc_info=exception)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。