Vodivanka Putra
Vodivanka Putra

Reputation: 23

Discordpy welcome bot

So, i tried to make a bot that send embed to specific channel everytime user join my server. The code is look like this

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)

and i got an error

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

Anyone know what is wrong in my code?

Upvotes: 2

Views: 157

Answers (2)

Dominik
Dominik

Reputation: 3592

You did not define guild. To define your guild you can do the following:

guild = bot.get_guild(GuildID)

It's the same method you used to define your channel, just for your guild now.

For further information you can have a look at the docs: https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_guild

Also take into account that we do not have a paramter like ctx in an on_member_join event. The event just has the parameter member in your case:

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

Upvotes: 0

Jacob Lee
Jacob Lee

Reputation: 4680

First of all, looking at the discord.py documention, ctx is not passed to the on_member_join event reference. However, you can use the attributes of member which is passed in order to get the values which you need.

@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)

Interestingly enough, you did this perfectly for getting the guild name, but it seems you forgot to do the same when retrieving channel.

Upvotes: 2

Related Questions