python 无法DM或直接消息不和谐,py-self最新版本

kknvjkwl  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(110)

我不能发送dm它给我一个错误使用模块discord. py-self
这是代码

import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('BOT IS RUNNING')

    async def on_message(self, message):

        if message.content.startswith('.hello'):
            await message.channel.send('Hello!', mention_author=True)
            for member in message.guild.members:
                if (member.id != self.user.id):
                    user = client.get_user(member.id)
                    await user.send('hllo')

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

误差

raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0)

在服务器中只有我和一个Offilne bot我试图发送一个消息给bot(正如你可以在代码中看到的)

yzuktlbb

yzuktlbb1#

我会尝试像这样定义你的机器人:

import discord
from discord.ext import commands

## (Make sure you define your intents)

intents = discord.Intents.default()

# What I always add for example:

intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True

## Define your bot here

client = commands.Bot(command_prefix= '.', description="Description.", intents=intents)

## Run bot here

client.run(TOKEN)

然后,我不再呈现客户端on_message事件,而是将其设置为一个命令,该命令将利用上面为bot定义的前缀。

@client.command()
async def hello(ctx):
    user = ctx.author
    await ctx.send(f"Hello, {user.mention}")
    dm = await user.create_dm()
    await dm.send('hllo')

更好的做法:(在我看来)

使用cog来保持代码整洁。在一个完全不同的文件中设置这个命令(比如在/commands文件夹中):
/commands/hello.py

import discord
from discord.ext import commands

class HelloCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def hello(self, ctx):
        user = ctx.author
        await ctx.send(f"Hello, {user.mention}")
        dm = await user.create_dm()
        await dm.send('hllo')

然后将cog导入到主文件中:

from commands.hello import HelloCog

client.add_cog(HelloCog(client))

希望这对你有帮助。

相关问题