在Python中制作不和谐机器人-AttributeError

时间:2020-08-14 16:23:02

标签: python discord discord.py

我最近尝试创建一个与Python代码不一致的简单bot。

import os

import discord
from dotenv import load_dotenv

load_dotenv()  #load .env files

TOKEN = os.getenv('DISCORD_TOKEN')  
GUILD = os.getenv('DISCORD_GUILD')  

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)  

    print(
        f'{client.user} has connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )                                                            #debug
    
    members = '\n - '.join([member.name for member in guild.members])  

    print(f'Guild Members:\n - {members}')  #debug

@client.event
async def on_member_join(member):
    await member.creat_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord Server!'
    )

client.run(TOKEN) 
Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join
    await member.creat_dm()
AttributeError: 'Member' object has no attribute 'creat_dm'

有人可以帮助我解决这个烦人的错误吗? 我看过一些文章,显示正在使用member.create_dm()

2 个答案:

答案 0 :(得分:1)

您是对的,有一个member.create_dm()https://discordpy.readthedocs.io/en/latest/api.html?highlight=create_dm#discord.Member.create_dm 但是您将其拼写错误为“ member.creat e _dm()”

您可以尝试将DM通道存储到变量中,以便稍后使用它。 (只是我的意见,以使代码更好)

@client.event
async def on_member_join(member):
    dmChannel = await member.create_dm()
    await dmChannel.send(f'Hi {member.name}, welcome to my Discord Server!)

答案 1 :(得分:1)

发布的答案是正确的,但您不应该经常打电话给create_dm()member.send()的工作时间最多。

文档:create_dm()

@client.event
async def on_member_join(member):
    await member.send(f'Hi {member.name}, welcome to my Discord Server!)