Discord.py:将欢迎消息移动到另一个模块后无法发送欢迎消息

时间:2021-03-12 17:57:28

标签: python discord discord.py bots

我正在尝试使用 Discord.py 设置欢迎消息,这就是我目前拥有的:

hydrabot/hydra/settings.py

import discord

# Welcomer settings
welcomeChannel = "819624923445985310"

# Bot intents settings
intents = discord.Intents(members=True)

# Command prefix
command_prefix = '$'

# Bot help page
description = f'''Hydra Commands
Hydra's command prefix is "{command_prefix}"
'''

hydrabot/hydra/main.py

import os

import discord
from discord.ext import commands

from settings import(
    intents,
    command_prefix,
    description)
from welcome_message import welcomeMessage

bot = commands.Bot(command_prefix=command_prefix, description=description, intents=intents)
@bot.event

async def on_member_join(member):
    print(f"{member.name} has joined the server. Attempting to send welcome message...")
    await member.send(welcomeMessage)
    print(f'Sent welcome message to {member.name}.')

hydrabot/hydra/welcome_message.py

import discord

welcomeMessage = f'Welcome to the server, {member.mention}!'

每当我运行程序时,我都会收到此错误:

Traceback (most recent call last):
  File "C:\Users\liljo\OneDrive\Projects\hydrabot\hydra\main.py", line 12, in <module>
    from welcome_message import welcomeMessage
  File "C:\Users\liljo\OneDrive\Projects\hydrabot\hydra\welcome_message.py", line 3, in <module>
    welcomeMessage = f'Welcome to the server, {member.mention}!'
NameError: name 'member' is not defined

我导入 member 时不是定义了 discord 吗?如果我使用 from discord import member 而不是 import discord 会发生以下情况: hydrabot/hydra/welcome_message.py

Traceback (most recent call last):
  File "C:\Users\liljo\OneDrive\Projects\hydrabot\hydra\main.py", line 12, in <module>
    from welcome_message import welcomeMessage
  File "C:\Users\liljo\OneDrive\Projects\hydrabot\hydra\welcome_message.py", line 3, in <module>
    welcomeMessage = f'Welcome to the server, {member.mention}!'
AttributeError: module 'discord.member' has no attribute 'mention'

为什么没有名为 mention 的属性,但每当我将欢迎消息移回 main.py 时程序都能正常运行?

1 个答案:

答案 0 :(得分:0)

您没有提供从 membermain.pywelcome_message.py 变量。

  1. 解决方法:直接在main.py中定义欢迎信息即可,不值得在另一个文件中定义

  2. 解决方案:您可以将欢迎消息放在welcome_message.py 中的函数中,您可以在其中传递参数member

welcome_message.py:

def welcomemessage(member):
    ...
    return welcomeMessage

main.py:

import welcome_message
welcome_message.welcomemessage(member)