不和谐的欢迎机器人

时间:2021-03-02 17:20:21

标签: python-3.x discord.py

因此,我尝试制作一个机器人,每次用户加入我的服务器时都会将其嵌入到特定频道。 代码是这样的

import discord
import asyncio
import datetime
from discord.ext import commands

intents = discord.Intents()
intents.members = True
intents.messages = True
intents.presences = True

bot = commands.Bot(command_prefix="a!", intents=intents)

@bot.event
async def on_ready():
    print('Bot is ready.')

@bot.event
async def on_member_join(ctx, member):
    embed = discord.Embed(colour=0x1abc9c, description=f"Welcome {member.name} to {member.guild.name}!")
    embed.set_thumbnail(url=f"{member.avatar_url}")
    embed.set_author(name=member.name, icon_url=member.avatar_url)
    embed.timestamp = datetime.datetime.utcnow()

    channel = guild.get_channel(816353040482566164)

    await channel.send(embed=embed)

我有一个错误

Ignoring exception in on_member_join
Traceback (most recent call last):
  File "C:\Users\Piero\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Piero\Documents\Discord\a-chan\achan_bot\main.py", line 24, in on_member_join
    channel = guild.get_channel(816353040482566164)
NameError: name 'guild' is not defined

有人知道我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:2)

首先,查看 discord.py documentionctx 没有传递给 on_member_join 事件引用。但是,您可以使用 is 传递的 attributes of member 来获取您需要的值。

@bot.event
async def on_member_join(member):
    embed = discord.Embed(
        colour=0x1abc9c, 
        description=f"Welcome {member.name} to {member.guild.name}!"
    )
    embed.set_thumbnail(url=f"{member.avatar_url}")
    embed.set_author(name=member.name, icon_url=member.avatar_url)
    embed.timestamp = datetime.datetime.utcnow()

    channel = member.guild.get_channel(816353040482566164)
    await channel.send(embed=embed)

有趣的是,您这样做是为了获得公会名称,但您似乎在检索 channel 时忘记这样做了。

答案 1 :(得分:0)

您没有定义 guild。 要定义您的公会,您可以执行以下操作:

guild = bot.get_guild(GuildID)

这与您用来定义 channel 的方法相同,现在仅用于您的 guild

有关更多信息,您可以查看文档: https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild

还要考虑到我们在 ctx 事件中没有像 on_member_join 这样的参数。 在您的情况下,该事件只有参数 member

@bot.event
async def on_member_join(member): #Removed ctx