在 Discord.py 中,可以通过循环事件来发送直接消息(DM)给其他 Discord 用户。下面是一个实现这一功能的示例代码:
首先,确保已经安装 discord.py 库。可以使用以下命令安装:
pip install discord.py
然后,可以使用以下代码来发送直接消息:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.direct_messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print('Bot is ready.')
@bot.command()
async def send_dm(ctx, member: discord.Member, *, message):
try:
await member.send(message)
await ctx.send("直接消息已发送!")
except discord.Forbidden:
await ctx.send("无法发送直接消息!")
bot.run('YOUR_BOT_TOKEN')
上述代码使用 discord.py 库创建了一个 Bot 对象,并设置了权限。send_dm
命令用于发送直接消息。在命令中,member
参数用于指定要发送消息的成员,message
参数用于指定要发送的消息内容。
请注意,要使 Bot 能够发送直接消息,您需要有相应的权限。在创建 Bot 时,需要为其生成一个 Bot Token,将其替换到代码中的 'YOUR_BOT_TOKEN'
处。
该代码的运行示例:
bot.py
文件。python bot.py
命令来启动 Bot。!send_dm @成员名 消息内容
命令来发送直接消息。这是一个简单的示例,您可以根据自己的需求对代码进行修改和扩展。希望对您有帮助!
领取专属 10元无门槛券
手把手带您无忧上云