I'm trying to make a simple bot that will give out a role to a person who just joined the server.
The code:
import discord
import os
from discord.utils import get
bot_acces_token = os.environ['token']
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, id="123456789")
await client.add_roles(member, role)
#client.event
async def on_ready():
print('Bot is ready')
client.run(bot_acces_token)
but unfortunately I get this error:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 17, in on_member_join
role = discord.utils.get(member.server.roles, id="123456789")
AttributeError: 'Member' object has no attribute 'server'
The way your are trying to get the result is old and have changed.
You need to change the way you are defining your bot. You need to change this piece of code:
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
You have to use Command API to use event. Change these lines to:
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
Add an import statement as well on the top of the script:
from discord.ext import commands
Remove this as well:
from discord.utils import get
Try this instead:
#client.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, id="123456789")
await member.add_roles(role)
You need to use member.guild.roles instead of the one you have actually used. Also you need to use await member.add_roles(role) instead of the one you used. It would work for you. If you still have an error, ask away!
Thank You! :D
Thats the solution:
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
#client.event
async def on_member_join(member):
channel = client.get_channel(1234567)
role = discord.utils.get(member.guild.roles, id=1234567)
await member.add_roles(role)
Related
import discord
client = discord.Client()
#client.event
async def on_member_join(member):
# Send a message to the welcome channel
welcome_channel = member.guild.get_channel(CHANNEL_ID)
await welcome_channel.send(f"Welcome {member.mention} to the server!")
client.run(TOKEN)
Whenever I Try Running This Code Replacing The Token And The Channel ID It Shows Me A Error Like:
Traceback (most recent call last):
File "main.py", line 3, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
KeyboardInterrupt
As per the quickstart documentation (and the error message), you need to specify the intents you want to use.
Here's an example using the default intents.
import discord
intents = discord.Intents.default()
client = discord.Client(intents=intents)
#client.event
async def on_member_join(member):
# Send a message to the welcome channel
welcome_channel = member.guild.get_channel(CHANNEL_ID)
await welcome_channel.send(f"Welcome {member.mention} to the server!")
client.run(TOKEN)
Here is my code:
import discord
from discord.ext import commands
bot = discord.bot(command_prefix="!", help_command=None)
#bot.event
async def on_ready():
print(f"Bot logged in as {bot.user}")
bot.run("TOKEN")
The error i am getting:
File "c:\Users\user\OneDrive\Desktop\coding\discord\server bots\test.py", line 6, in <module>
bot = discord.bot(command_prefix="!", help_command=None)
TypeError: 'module' object is not callable
I haven't coded in a while and i just got back to coding. I tried a simple discord.py program but it didn't seem to work. Is there any way i could fix this?
yeah, you need to specify intents
here is the code to it works
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", help_command=None, intents = intents)
#bot.event
async def on_ready():
print(f"Bot logged in as {bot.user}")
#bot.command()
async def hello(ctx):
await ctx.send(f"hi {ctx.author.mention}")
bot.run("token")
The syntax is commands.Bot() with from discord.ext import commands before (which is your case).
Also don't forget to specify the intents.
Hello guys im trying to write a code that gives me the discord server owner but its giving Me 'None'
import discord
client = discord.Client()
TOKEN = 'token'
#client.event
async def on_message(message):
if message.content.find("getowner") != -1:
await message.channel.send(str(message.guild.owner))
client.run(TOKEN)
Can someone please help me with this bot thanks!!
I want to get the discord servers owner by typing getowner in a text channel.
I recommend using it as a command rather than doing on_message, you can do this:
from discord.ext import commands
token = "Token"
client = commands.Bot(command_prefix="!") #Use any prefix
#client.command(pass_context=True)
async def getOwner(ctx):
#await ctx.channel.send(str(ctx.guild.owner.display_name))
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
But if you don't want to use a command, you could use regular expression and just keep it as:
import discord
import re
client = discord.Client()
TOKEN = 'token'
#client.event
async def on_message(ctx):
if re.match("getowner", ctx.content):
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
EDIT: Also try using intents with your bot code.
import discord
import re
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
TOKEN = "token"
#client.event
async def on_message(ctx):
if re.match("getowner", ctx.content):
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
Same changes can be done with the command version.
It's very simple;
from discord.ext import commands
#client.command(name="getowner")
async def getowner(ctx):
await ctx.send(str(ctx.guild.owner))
So basically I have this code:
import discord
import os
bot = commands.Bot(command_prefix = "!")
TOKEN = (os.getenv("TOKEN"))
client = discord.Client()
#client.event
async def on_message(message):
if message.content.startswith('!help'):
embedVar = discord.Embed(
title="Help Page", description="Under development", color=0x00ff00)
await message.channel.send(embed=embedVar)
#client.command()
#commands.has_any_role("Owner")
async def ban (ctx, member:discord.User=None, reason =None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "Breaking Rules"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
# await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{member} is banned!")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
When I run this I get the sequent error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
bot = commands.Bot(command_prefix = "!")
NameError: name 'commands' is not defined
Can someone please help me?
In the documentation for commands, it states to add this to your imports:
from discord.ext import commands
commands isn't defined because it isn't imported in your code put from discord.ext import commands at the top of your code. And, you don't need discord.Client() bc commands.Bot() is a subclass of it so please remove it for it is redundant. and finally, change client.command to bot.command to make the code work.
st recent call last):
File "randomgg.py", line 1271, in \u003cmodule\u003e
client.run(token)
File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 708, in run
return future.result()
File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 687, in runner
await self.start(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 651, in start
await self.connect(reconnect=reconnect)
File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 586, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
my code was
import aiohttp
import discord
import asyncio
from collections import Counter
import typing
from discord.ext import commands
import os
from discord.ext.commands import has_permissions
import random
import json
from discord import Status
from asyncio import gather
from discord.utils import get
import datetime
from discord.utils import get
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=intents)
client.remove_command('help')
def check_if_it_is_me(ctx):
return ctx.message.author.id == 465946367622381578
#client.event
async def status_task():
while True:
await client.change_presence(status=discord.Status.idle, activity=discord.Game('status1'))
await asyncio.sleep(4)
await client.change_presence(status=discord.Status.idle, activity=discord.Game('status2'))
await asyncio.sleep(4)
await client.change_presence(status=discord.Status.idle, activity=discord.Game('status3'))
await asyncio.sleep(4)
#client.event
async def on_ready():
print(f'{client.user.name} is ready')
client.loop.create_task(status_task())
#client.event
async def on_member_join(member):
mem_join = member.joined_at
guild_create = member.created_at
join_days = (mem_join - guild_create).days
role = discord.utils.get(member.guild.roles, id=714805001918349344)
channel = discord.utils.get(member.guild.channels, id=771081754038501376)
if join_days < 10:
await channel.send(f'{role.mention} {member} is suspicious of being an alt, he joined {join_days} after creating his account. Pls keep an eye on him')
#client.event
async def on_member_remove(member):
pass
hope u can help me i alr tried everything
The error tells you exactly what to do.
Go to https://discord.com/developers/applications
Navigate to your application
Go to the Bot section
Scroll down and enable SERVER MEMBERS INTENT