如何在没有他们在服务器中做任何事情的情况下 DM 用户

时间:2021-06-30 15:20:22

标签: python discord discord.py

我正在创建一个简单的机器人 DM 部分,我已经尝试过这种方法,但它一直给我一个错误。

代码:

import discord
from discord.ext import commands

TOKEN = "Token Here"

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    me = await client.get_user_info('Snowflake ID Here')
    await client.send_message(me, "Message Here")

client.run(TOKEN)  

它一直给我这个错误:

NameError: name 'client' is not defined

这个方法看起来像用户需要发送一条消息,但有没有一种方法可以在不需要用户发送消息的情况下做到这一点。

2 个答案:

答案 0 :(得分:0)

import discord
from discord.ext import commands


client = disord.Client(intents=discord.Intents.all()) # define client
# could also be commands.Bot()


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    me = client.get_user(1234) # user id, must be int type
    await me.send("Message Here") # client.send(me, "message here") doesnt work in discord.py version 1.x

client.run("TOKEN")  

答案 1 :(得分:0)

客户端示例

import discord

class MyClient(discord.Client): # defineding client
    async def on_ready(self):   # event
        print('Logged on as', self.user)

    async def on_message(self, message): # event
        if message.author == self.user:
            return

        you = self.get_user(1234)
        await you.create_dm() # go to DM
        await you.send("Message Here") 


client = MyClient()
client.run('token')

机器人示例

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>') # defineding client

@bot.event
async def on_ready():
    print('Logged on as', bot.user)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    you = bot.get_user(1234) 
    await you.create_dm() # go to DM
    await you.send("Message Here")


bot.run('token')