beforehand: I tried already a lot of potential fixes which are available on stack overflow. Sadly none of them worked.
Here is the Code:
import discord
import asyncio
import datetime
from discord.ext import commands
bot = commands.Bot(command_prefix='!', case_insensitive=True)
#bot.event
async def on_ready():
print('bot is online')
return await bot.change_presence(activity=discord.Activity(type=2, name='bla'))
#bot.event
async def on_member_join(member):
embed = discord.Embed(colour=0x95efcc, description=f"Welcome! You are the {len(list(member.guild.members))} Member!"),
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", url=f"{member.avatar_url}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestemp = datetime.datetime.utcnow()
channel = bot.get_channel(id=012391238123)
await channel.send(embed=embed)
bot.run('Token')
The bot logs in but it won't execute on_member_join. Has anybody an idea what might be wrong? on_message works fine.
intents = discord.Intents.all()
client = discord.Client(intents=intents)
didn't help and in discord developer it's also checked (Server Members Intent).
The bot also has administrator privileges
Greetings Eduard
Solution in short:
imports
intents = discord.Intents(messages=True, guilds=True, members=True)
bot = commands.Bot(command_prefix='!', intents=intents, case_insensitive=True)
#bot.event
async def on_member_join(member):
embed = discord.Embed(colour=0x95efcc, description=f"Welcome to my discord server! You are the {len(list(member.guild.members))} member!")
channel = bot.get_channel(id=12931203123)
await channel.send(embed=embed)
bot.run('token')
Ah, so that's it.
Since you are using commands.Bot, the bot.get_channel is no longer a function (since it is no longer discord.Client). Try using member.guild.get_channel instead.
Documentation
Related
I am trying to set up a simple Discord bot for a server, but it only appears to be responding in DMs to commands and not in any server channels. The bot has admin permissions in the server I am trying to get it to respond in.
After doing some looking around I have found no fixes.
Here's the code:
import discord
token_file = open("bot_token.txt", "r+")
TOKEN = str(token_file.readlines()).strip("[]'")
token_file.close()
command_prefix = ">"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("Logged in as: {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(command_prefix):
if message.content == ">help":
await message.channel.send("What do you need help with?")
elif message.content == ">hello":
await message.channel.send("Hi there!")
else:
await message.channel.send("This command is not recognised by our bot, please use the help menu if required.")
else:
return
client.run(TOKEN)
Hope someone can help!
It‘s pretty simple…
For receiving message events in guilds (servers) you need the message intent (discord.Intents.message_content = True), you also have to enable it in the discord developer dashboard.
Discord added a message content intent that has to be used since the first September 2022. if you‘re doing a discord.py tutorial, be aware that it should be a 2.0 tutorial as many things have been updated since then.
Also, think of using the commands extension of discord.py as it is handling some annoying stuff and provides more easier interfaces to handle commands.
I‘ll help you with further questions if there are any
;-)
#kejax has given absolutely the right answer I just want to add how u
can make the use of 'intent' in your code:-
If you want to listen and have access to all available events and data
client = discord.Client(intents=discord.Intents.all())
Full Code :-
import discord
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
You can also specify specific intents by creating a set of the desired discord.Intents constants.
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
Full Code:-
import discord
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('....................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
I made a Discord bot that tells you a Minecraft's server status!
It works fine on the console with the print function, but it doesn’t work as a command! The bot just doesn’t respond. Also I tested it without the mcstatus library and the command worked. (Without what it's supposed to do, of course.)
This is my code:
import discord
from discord.ext import commands
from mcstatus import JavaServer
client = commands.Bot(command_prefix = "!")
client.remove_command("help")
server = JavaServer.lookup("mc.elitesmp.co:25588")
status = server.status()
#client.event
async def on_ready():
print('Logged in as: "' + str(client.user) + '"')
print(f"Elite SMP has {status.players.online} players online!")
#client.command() # <--- This is the command that doesn't work!
async def info(ctx):
await ctx.send("test")
client.run("token")
Any ideas?
I think it’s because you need to enable intents in your Discord bot, and also declare them in the code by adding:
intents = discord.Intents.default()
And also putting , intents=intents in the space where you declare your bot's prefix.
This is also an example of a bot I just made, to help with some command also.
import discord
from discord.ext import commands
from mcstatus import JavaServer
from mcstatus import BedrockServer
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='?', intents=intents)
TOKEN = "removed for obvious reasons"
#bot.event
async def on_ready():
print('ready')
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,name="Minecraft Servers"))
#bot.event
async def on_command_error(ctx, error):
if isinstance(error,commands.CommandInvokeError):
await ctx.reply("No such server was found")
#bot.command()
async def java(ctx, message):
server = JavaServer.lookup(message)
status = server.status()
embed = discord.Embed(title=f"{message}", description=f"info on {message}")
embed.add_field(name="Players Online :green_circle:", value=f"The server has {status.players.online} players online", inline=False)
embed.add_field(name="Server Response :warning:", value=f"The server replied in {status.latency}ms", inline=False)
await ctx.reply(embed=embed)
#bot.command()
async def bedrock(ctx, message):
server = BedrockServer.lookup("message")
status = server.status()
embed = discord.Embed(title=f"{message}", description=f"info on {message}")
embed.add_field(name="Players Online :green_circle:", value=f"The server has {status.players.online} players online", inline=False)
embed.add_field(name="Server Response :warning:", value=f"The server replied in {status.latency}ms", inline=False)
await ctx.reply(embed=embed)
bot.run(TOKEN)
The following code works fine for me, as you can see here.
The following image shows how the commands work: command image
I think the command isn't working, because you haven't declared what intents you need in code. Discord bots now need to declare what events they need to access, such as reading messages. You can read about intents in the discord.py documentation here.
I also moved the "players online" part to a variable, and printed that instead, and that got your command to work.
intents = discord.Intents.default()
client = commands.Bot(command_prefix = "!", intents = intents)
client.remove_command("help")
player_text = f"Elite SMP has {status.players.online} players online!"
#client.event
async def on_ready():
print(player_text)
#client.command()
async def test(ctx):
await ctx.send("test")
Screenshots of it working in code here and Discord here.
i have only started to look around and figure how things work with discord.py bot. Tried making a bot that welcomes people in a certain channel. But no matter what I do, it doesn't seem to be working. The code executes and the on_ready fires. But its not welcoming the user like its supposed to. Can someone help?
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord import Color
import asyncio
import datetime
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
client=commands.Bot(command_prefix="-")
client.remove_command("help")
#client.event
async def on_ready():
print("Created by Goodboi")
print(client.user.name)
print("-----")
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow
channel = client.get_channel(id=) #usedid
await channel.send(embed=embed)
client.run('token') #usedtoken
Hi you have to get channel like this
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server",)
embed.set_author(name=f"{member.mention}",icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
channel = member.guild.get_channel(channel_id) #usedid
await channel.send(embed=embed)
The only thing you did wrong is passing no brackets to your datetime.datetime.utcnow "function" which gives out the following error:
TypeError: Expected datetime.datetime or Embed.Empty received builtin_function_or_method instead
If you put brackets behind the definition of your timestamp it should work:
#client.event
async def on_member_join(member):
embed = discord.Embed(colour=0xe8744f,
description=f"Welcome to the discord server", )
embed.set_author(name=f"{member.mention}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow() # Added brackets
channel = client.get_channel(ChannelID) # No "id=" needed
await channel.send(embed=embed)
You can also have a look at the docs: https://docs.python.org/3/library/datetime.html#datetime.datetime
This should work for you, though, can be improved in many ways, but if you asked for this, then here is it.
#client.event
async def on_member_join(member) :
channel = client.get_channel(CHANNEL ID) # First we need to get the channel we want to post our welcome message.
embed = discord.Embed(
colour=0xe8744f ,
description='Welcome to the discord server' ,
timestamp=datetime.utcnow()
)
embed.set_author(name=f'{member.mention}' , icon_url=f'{member.avatar_url}')
embed.set_footer(text=f'{member.guild}' , icon_url=f'{member.guild.icon_url}')
await channel.send(embed=embed) #Send the embed
I have been trying to make a discord bot but I am facing problems with the on_member_join function. The bot has been given admin permissions and I face no error in the console either
Here is the code
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client()
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_member_join(member):
await member.send('welcome !')
client.run('TOKEN')
You need to pass intents in the Client() initializer
Below is the revised code:
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_member_join(member):
await member.send('welcome !')
client.run('TOKEN')
Try using intents. With this version you will need to use intents.
https://discordpy.readthedocs.io/en/latest/api.html?highlight=intents#discord.Intents
Intents are the new features required in discord.py version 1.5.0 +
If your bot doesn't use intents and you're using events such as on_member_join() it wont work!
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)
I just started with discord.py and found out that on_member_join and on_member_remove don't work for me. Keep in mind that on_ready function works perfectly fine.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print("""Bot ready""")
#bot.event
async def on_member_join(member):
channel = bot.get_channel(767370104814960640)
await channel.send(f"{member} has joined the server")
#bot.event
async def on_member_remove(member):
channel = bot.get_channel(766620766237753345)
await channel.send(f"{member} has left the server")
bot.run("my token")
So did I make a mistake with my code or something else went wrong?
discord.py 1.5.0 now supports discord API's Privileged Gateway Intents. In order to be able to exploit server data, you need to:
Enable Presence Intent and Server Members Intent in your discord application:
https://i.stack.imgur.com/h6IE4.png
Use discord.Intents at the beginning of your code:
intents = discord.Intents.all()
#If you use commands.Bot()
bot = commands.Bot(command_prefix="!", intents=intents)
#If you use discord.Client()
client = discord.Client(intents=intents)