[英]Python - DM a User Discord Bot
我正在使用 Python 開發 User Discord Bot。如果機器人所有者輸入!DM @user
那么機器人將 DM 所有者提到的用戶。
@client.event
async def on_message(message):
if message.content.startswith('!DM'):
msg = 'This Message is send in DM'
await client.send_message(message.author, msg)
最簡單的方法是使用discord.ext.commands
擴展。 這里我們使用轉換器來獲取目標用戶,並使用僅關鍵字參數作為可選消息來發送它們:
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
@bot.command(pass_context=True)
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await bot.send_message(user, message)
bot.run("TOKEN")
對於較新的 1.0+ 版本的 discord.py,您應該使用send
而不是send_message
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
@bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
bot.run("TOKEN")
由於大遷移到 v1.0, send_message
不再存在。
相反,他們已遷移到每個端點(成員、公會等)上的.send()
) 。
v1.0 的一個例子是:
async def on_message(self, message):
if message.content == '!verify':
await message.author.send("Your message goes here")
這將 DM 的發件人!verify
。 像聰明人一樣,你可以這樣做:
for guild in client.guilds:
for channel in guild.channels:
channel.send("Hey yall!")
如果您想向您的所有服務器和機器人所在的所有頻道發送“嗨 yall”消息。
由於它可能並不完全清楚(根據評論判斷) ,棘手的部分可能會從客戶端/會話獲取用戶身份句柄。 如果您需要向尚未發送消息的用戶發送消息,並且在on_message
事件之外。 您必須:
但是發送給用戶的唯一方法是通過客戶端身份句柄,該on_message
位於on_message
位於message.author
,或者位於guild.channels[index].members[index]
中的頻道中。 為了更好地理解這一點,我建議閱讀有關如何發送 DM的官方文檔? .
我過去使用過這個命令,我認為它最適合我:
@bot.command(pass_context=True)
async def mall(ctx, *, message):
await ctx.message.delete()
for user in ctx.guild.members:
try:
await user.send(message)
print(f"Successfully DMed users!")
except:
print(f"Unsuccessfully DMed users, try again later.")
@bot.command()
async def dm(ctx, user: discord.User, *, message=None):
if message == None:
message = "Hi!"
embed = make_embed(title=f"Sent by {user}", desc=message)
await user.send(embed=embed)
await ctx.send("Message sent!")```
我注意到我放入代碼行的每個代碼都不能完全工作,所以我向它們添加了我自己的代碼,然后它就可以工作了! 將此添加到您的機器人代碼時,不要忘記在此處顯示 bot name 的位置添加機器人名稱。 它只會向發送它的人發送 DM,但您可以每天更改它所說的內容,以便為使用該命令的每個人帶來驚喜。 它每次都對我有用。
@client.command()
async def botdm(ctx):
await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.