Python discord 模块,DMChannel() 实例源码
我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用discord.DMChannel()。
def timer_list(self, ctx):
"""Lists all of your currently active timers."""
with db.Session() as session:
timers = session.get(Timer, user_id=ctx.author.id).all()
Now = datetime.utcNow()
e = discord.Embed(color=discord.Color.blurple())
def format_timer(timer):
channel = ctx.bot.get_channel(timer.channel_id)
return 'ID {id},in {channel}: {message} (in {duration})'.format(
id=timer.id,
channel='DMs' if isinstance(channel, discord.DMChannel) else channel.mention,
message=timer.message or 'no message',
duration=format.time(timer.end_time - Now)
)
e.description = '\n'.join(map(format_timer, timers)) if timers else 'No timers set.'
await ctx.send(embed=e)
def wait_for_response(self):
"""
Waits for a message response from the message author,then returns the
new message.
The message we are waiting for will only be accepted if it was sent by
the original command invoker,and it was sent in the same channel as
the command message.
"""
def check(m):
if isinstance(m.channel, discord.DMChannel):
# accept any message,because we are in a dm
return True
return m.channel.id == self.channel.id and m.author == self.author
return await self.bot.wait_for('message', check=check)
def on_message(message):
if message.author.bot or message.author.id in loadconfig.__blacklist__:
return
if isinstance(message.channel, discord.DMChannel):
await message.author.send(':x: Sorry,but I don\'t accept commands through direct messages! Please use the `#bots` channel of your corresponding server!')
return
if bot.dev and not await bot.is_owner(message.author):
return
if bot.user.mentioned_in(message) and message.mention_everyone is False:
if 'help' in message.content.lower():
await message.channel.send('Eine volle Liste aller Commands gibts hier: https://github.com/Der-Eddy/discord_bot#commands-list')
else:
await message.add_reaction('??') # :eyes:
if 'loli' in message.clean_content.lower():
await message.add_reaction('??') # :lollipop:
if 'instagram.com' in message.clean_content.lower():
await message.add_reaction('??') # :poop:
if len(message.attachments) > 0:
try:
await message.channel.send(await _fileCheck(message))
except:
pass
await bot.process_commands(message)
def on_message_delete(self,msg):
if isinstance(msg.channel,discord.DMChannel):
return
if msg.author.id == self.bot.user.id:
return
if self.config.get(msg.guild.id):
if self.config[msg.guild.id].get("delete"):
if msg.author.bot and self.config[msg.guild.id].get("bot"):
return
message = self.format_msg(msg.author)
if msg.attachments:
message += "*has deleted attachments*"
else:
message += "*has deleted the following message* in {}: ".format(msg.channel.mention)
message += "{}".format(msg.clean_content)
await self.send(msg.guild.id,message)
def command_checker(msg):
try:
if isinstance(msg.channel,discord.DMChannel):
if "!reply" in msg.content:
bot.command_prefix = commands.when_mentioned_or("!")
return
if bot.user.id == 181503794532581376:
bot.command_prefix = commands.when_mentioned_or("$")
bot.pm_help = False
return
cmd_prefix= await bot.db.redis.get("{}:Config:CMD_Prefix".format(msg.guild.id))
cmd_prefix= cmd_prefix.split(",")
if '' in cmd_prefix: #check if "none-space" as a command,if true,return,in order to prevent any spam in case,lower chance of getting kick heh.
return
bot.command_prefix = commands.when_mentioned_or(*cmd_prefix)
if "help" in msg.content: #changing setting for help,if guild owner want Help command to be via PM or to guild.
if await bot.db.redis.get("{}:Config:Whisper".format(msg.guild.id)) == "on":
bot.pm_help =True
else:
bot.pm_help=False
except:
pass
def connect(self, ctx, channel):
me, channel_name = (channel.me, '%s\'s DMs' % channel.recipient) if isinstance(channel, discord.DMChannel) else (channel.guild.me, channel.name)
if channel is None:
await ctx.send('BAKA! I can\'t access that channel!')
return
elif channel.permissions_for(me).send_messages is False:
await ctx.send('BAKA! I can\'t speak in that channel!')
return
await ctx.send('Connecting to %s' % channel_name)
portal_key = (ctx.author, ctx.channel)
self.portals[portal_key] = channel
return portal_key
def pm_check(self, ctx):
if rewrite():
return isinstance(ctx.channel, discord.DMChannel)
else:
return ctx.message.channel.is_private
def in_pm(ctx):
return isinstance(ctx.channel, discord.DMChannel) or isinstance(ctx.channel, discord.GroupChannel)
def on_command(self, ctx):
# some Metadata
author = ctx.message.author
checks = [c.__qualname__.split('.')[0] for c in ctx.command.checks]
location = '[DM]' if isinstance(ctx.channel, DMChannel) else '[Guild]'
# log command invocation
logger.info(
'%s Command invocation by %s (%d) "%s" checks=%s',
location, author, author.id, ctx.message.content, ','.join(checks) or '(none)'
)
def private_message_only(error_msg="This command can only be used in private messages"):
def predicate(ctx):
if isinstance(ctx.channel, (discord.GroupChannel, discord.DMChannel)):
return True
raise PrivateMessagesOnly(error_msg)
return commands.check(predicate)
def on_command(self, ctx):
if isinstance(ctx.channel, discord.DMChannel):
self.logger.debug(f"Command: '{ctx.command}' "
f"User: '{ctx.author}'/{ctx.author.id} (In DM's)")
else:
self.logger.debug(f"Command: {ctx.command} "
f"Channel: '#{ctx.channel.name}'/{ctx.channel.id} "
f"Guild: '{ctx.guild}'/{ctx.guild.id} "
f"User: '{ctx.author}'/{ctx.author.id}")
self.command_count += 1
def on_command(self, ctx):
"""Log command usage"""
# thanks dogbot ur a good
content = ctx.message.content
content = self.clean_content(content)
author = ctx.message.author
guild = ctx.guild
checks = [c.__qualname__.split('.')[0] for c in ctx.command.checks]
location = '[DM]' if isinstance(ctx.channel, discord.DMChannel) else \
f'[Guild {guild.name} {guild.id}]'
log.info('%s [cmd] %s(%d) "%s" checks=%s', location,
author.id, content,'.join(checks) or '(none)')
def log_command(self, command):
self.bot.commands_triggered[command] += 1
if isinstance(ctx.channel, discord.DMChannel):
destination = f'PM with {ctx.channel.recipient}'
elif isinstance(ctx.channel, discord.GroupChannel):
destination = f'Group {ctx.channel}'
else:
destination = f'#{ctx.channel.name},({ctx.guild.name})'
log.info(f'In {destination}: {command}')
# Cumstom Commands with prefix
def before_invoke(ctx):
bot.commands_triggered[ctx.command.qualified_name] += 1
if isinstance(ctx.channel, discord.DMChannel):
destination = f'PM with {ctx.channel.recipient}'
elif isinstance(ctx.channel, discord.GroupChannel):
destination = f'Group {ctx.channel}'
else:
destination = f'#{ctx.channel.name},({ctx.guild.name})'
log.info('In {}: {}'.format(destination, ctx.message.content.strip(ctx.prefix)))
def on_command(ctx):
bot.commands_used[ctx.command.name] += 1
msg = ctx.message
if isinstance(msg.channel, discord.TextChannel):
dest = f'#{msg.channel.name} ({msg.guild.name})'
elif isinstance(msg.channel, discord.DMChannel):
dest = 'Direct Message'
elif isinstance(msg.channel, discord.GroupChannel):
dest = 'Group Message'
else:
dest = 'Voice Channel'
logging.info(f'{msg.created_at}: {msg.author.name} in {dest}: {msg.content}')
def test_lookup(self):
m = utils.TypeMap()
m.put(discord.abc.User, "something")
m.put(discord.TextChannel, "something else")
m.put(discord.Guild, "another thing")
self.assertEquals("something", m.lookup(discord.abc.User))
self.assertEquals("something", m.lookup(discord.User))
self.assertEquals("something", m.lookup(discord.Member))
self.assertEquals("something else", m.lookup(discord.TextChannel))
self.assertEquals(None, m.lookup(discord.DMChannel))
def on_command(self,ctx):
if isinstance(ctx.message.channel,discord.DMChannel):
return
print("\033[96m<Event Command>\033[94m {0}:\033[96m {1.guild.name} ||| \033[93m {1.author} ||| \033[94m ({1.author.id})\033[92m ||| {1.clean_content}\033[00m".format(self.Time(), ctx.message))
def on_message(self,msg):
if self.bot.user.id == msg.author.id:
if isinstance(msg.channel,discord.DMChannel) is False:
try:
if self.bot.log_config.get(msg.guild.id):
if str(msg.channel.id) in self.bot.log_config[msg.guild.id]['channel']:
return
except:
pass
if isinstance(msg.channel,discord.TextChannel) is False:
utils.prCyan("PRIVATE")
utils.prGreen("<Event Send> {} : {} |||{}".format(self.Time(), msg.author.name, msg.clean_content))
else:
try:
if msg.embeds:
table = prettytable() #best to use it i guess
data = msg.embeds[0].fields
if data:
for x in data:
table.add_column(x.name,x.value.split("\n"))
content = str(msg.embeds[0].description) +"\n"
content +="\n" + str(table)
else:
content = msg.clean_content
utils.prGreen("<Event Send> {} : {} ||| {} ||| ({}) ||| {}".format(self.Time(),msg.guild.name,msg.guild.id, content))
except:
utils.prGreen("<Event Send> {} : {} ||| {} ||| ({}) ||| {}".format(self.Time(),msg.embeds))
def on_command_completion(self,ctx):
if ctx.command.cog_name is None or isinstance(ctx.message.channel,discord.DMChannel):
return
try:
print(ctx.command.cog_name)
check = await self.bot.db.redis.hgetall("{}:Config:Delete_MSG".format(ctx.message.guild.id))
if check.get(ctx.command.cog_name.lower()) == "on":
await ctx.message.delete()
await self.redis.hincrby("{0.guild.id}:Total_Command:{0.author.id}".format(ctx.message),ctx.invoked_with, increment=1)
await self.redis.hincrby("Info:Total_Command", ctx.invoked_with, increment=1)
await self.redis.hincrby("{0.guild.id}:Total_Command:User:{0.author.id}".format(ctx.message), increment=1)
except:
utils.prRed("Failed to delete user command - {0.name} - {0.id}\n".format(ctx.message.guild))
utils.prRed(traceback.format_exc())