I've recently tried to create a simple bot in discord with Python Code.
I'm testing just the first features to DM a user when he joins the server
Here is my code:
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'
Can anyone help me with this annoying bug?
I've seen articles that show member.create_dm() being used
You are right, there is a member.create_dm() https://discordpy.readthedocs.io/en/latest/api.html?highlight=create_dm#discord.Member.create_dm
But you spelled it wrong "member.create_dm()"
You may try to store the DM channel into a variable, so you can call it later.
(Just my opinion on making the code better)
#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!)
The answer posted is correct but you should not call create_dm()frequently, member.send() works the most time.
Docs: create_dm()
#client.event
async def on_member_join(member):
await member.send(f'Hi {member.name}, welcome to my Discord Server!)
Related
I made discord bot that should give someone role upon joining but I get error which can be seen here:
Traceback (most recent call last):
File "C:\Users\jarda\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: on_member_join() missing 2 required positional arguments: 'after' and 'member'
And almost full code is here:
import discord
from discord.ext import commands
from discord.utils import get
from discord.ext.commands import Bot
intents = discord.Intents.all()
client = commands.Bot(command_prefix="!", intents=intents)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
#client.event
async def on_message(message):
if message.content.startswith("AboutMe"):
await message.channel.send("Hello world!")
#client.event
async def on_member_join(before, after, member):
channel=client.get_channel(channelID)
emb=discord.Embed(title="New member has joined",description=f"Thanks {member.mention} for being part of the bros!")
await channel.send(embed=emb)
print(f"{member.name} has joined the server")
#Adds role
TheGreatLegendWarriors = Bot.get_guild(serverID)
if 'inTraining' in after.roles:
if not 'inTraining' in str(before.roles):
await after.add_roles(discord.utils.get(TheGreatLegendWarriors.roles, name="inTraining"))
print(f"INFO: {after.name} Has been given inTraining role!")
Iam new to py and discord api so really unsure what the issue is. I tried using 2 on_member_join which gave me error as 2 of those can't run at the same time. Then this appeared and I have struggled for way too long now.
The docs specify that on_member_join should accept a single parameter, member.
You can remove the before and after parameters from your on_member_join function signature.
i'm trying to make my first discord bot in python. It worked well, untill I wanted to add function, when bot greets new member on specific channel.
Here is my code:
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
intents = discord.Intents.all()
client = commands.Bot(command_prefix='.',intents=intents)
#client.event
async def on_ready():
await client.change_presence(activity=discord.Game(name="chess with your mum"))
print("Bot is ready")
#client.event
async def on_member_join(member):
channel = client.get.channel(828249420784205824)
await channel.send(f'{member} dolaczyl do serwera!') #in english: "joined the server!"
#client.event
async def on_member_leave(member):
channel = client.get.channel(828249420784205824)
await channel.send(f'{member} opuscil serwer!') #in english: "leaved the server!"
#client.command()
#has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'Uzytkownik {member} dostal bana!') #in english: "got banned"
#client.command()
#has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'Uzytkownik {member} zostal wyrzucony!') #in english: "got kicked"
client.run('TOKEN')
And error:
2022-12-17 20:21:24 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/runner/Bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 16, in on_member_join
channel = client.get.channel(828249420784205824)
AttributeError: 'Bot' object has no attribute 'get'
I would be very happy if anyone can help me. Thanks
I think you're looking for the client.get_channel method instead of client.get.channel, which doesn't exist.
Discord Bot Not Sending Messages To Specified Channels
Hello,
I'm creating a discord bot to log actions and send them to specific channels. Every time I run my code I get no errors but as soon as I type in the command/word used I get an error. I am just trying to log actions into another channel.
I haven't set this section up yet:
bot = discord.ext.commands.Bot(command_prefix = "$");
Here is my code:
import os
import discord
from discord.ext import commands
bot = discord.ext.commands.Bot(command_prefix = "$");
client = discord.Client()
# #client.event
# async def on_message(message):
# id = client.get_guild(940403791092670464)
#client.event
async def on_ready():
print(f"{client.user} logged in now!")
#client.event
async def on_message(message):
if message.content.startswith("$help"):
response = print (f"#help command was used")
await message.channel.send(f"{message.author.mention} help stuff")
elif "fudge" in message.content:
await message.delete()
response = print(f"You're not allowed to say those words {message.author.mention} Word Used: Fudge")
await message.channel.send(f"You're not allowed to use those words {message.author}.")
elif "female dog" in message.content:
channel = bot.get_channel(943040534165991485)
await channel.send(f"{message.author.mention} Said the word female dog.")
await message.channel.send(f"You're not allowed to say those words {message.author.mention}")
await message.delete()
response = print (f"Logging actions.")
my_secret = os.environ['TOKEN']
client.run(my_secret)
Here is my Err:
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Discord-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs)
File "main.py", line 31, in on_message
await channel.send(f"{message.author.mention} Said the word Food.")
AttributeError: 'NoneType' object has no attribute 'send'
Anything helps!
Use fetch_channel() instead of get_channel(). In discord.py as a rule of thumb fetch_something() makes an API call while get_something() tries to get it from the cache.
First off, I tried googling this and could never really find an answer so here I am on stackoverflow. So, I'm trying to add a greeting effect to my discord bot but can't seem to be able to send a message. I know the bot isn't sending the message because "message" is not defined when using message.channel.send but I don't know the correct way to do so.
Error:
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "<string>", line 20, in on_member_join
NameError: name 'message' is not defined`)
import discord
bot = discord.Client()
#bot.event
async def on_ready():
print('Logged in')
print("Username: %s" % (bot.user.name))
print("Userid: %s" % (bot.user.id))
#bot.event
async def on_member_join(member):
print(f'{member} has joined the server')
await message.channel.send('{member} has joined the server'.format(message))
#bot.event
async def on_member_remove(member):
print(f'{member} has left the server')
await message.channel.send('{member} has left the server'.format(message))
bot.run(Token)
Use get_channel to get your #welcome channel, assign it to a variable, then send the welcome message.
#client.event
async def on_member_join(member):
channel = client.get_channel(730064641857683581) # Replace with your Welcome channel ID
await channel.send(f"{member} has joined the server")
The error is correct. message.channel.send will never work if message is not defined, which it's not. message is a parameter of some discord.py functions, but not on_member_join or on_member_remove, since these don't happen in a specific channel. You will have to pre-specify which channel to send the message to.
So I am trying to make my bot leave welcome and removed messages using discord.py.
import discord
from discord.ext import commands
import random
client = commands.Bot(command_prefix = '.')
#client.event
async def on_member_join(ctx, *, member):
channel = member.server.get_channel("channel id")
fmt = 'Welcome to the {1.name} Discord server, {0.mention}'
await ctx.send_message(channel, fmt.format(member, member.server))
#client.event
async def on_member_remove(ctx, *, member):
channel = member.server.get_channel("channel id")
fmt = '{0.mention} has left/been kicked from the server.'
await ctx.send_message(channel, fmt.format(member, member.server))
client.run('client id')
The error
File "C:\python\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_join() missing 1 required keyword-only argument: 'member'
comes up.
I am not sure why it isn't working. I have very little experience with it, so I am not sure what I am doing wrong. Could anyone tell me what I am missing?
#client.event
async def on_member_join(member):
await client.get_channel(idchannel).send(f"{member.name} has joined")
#client.event
async def on_member_remove(member):
await client.get_channel(idchannel).send(f"{member.name} has left")
On event you can't get ctx, because it isn't a command, who must write. It is event
#client.event
async def on_member_join(member):
await client.get_channel(idchannel).send(f"{member.name} has joined")
#client.event
async def on_member_remove(member):
await client.get_channel(idchannel).send(f"{member.name} has left")
also keep in mind that idchannel is int, not string