#discord-bots
1 messages Β· Page 585 of 1
.max_age maybe
Yea that only
Whenever u fetch an invite
Just store it in cache, and first check if the invite is there in the cache
If it ain't, then fetch it
regex
He wasn't talking about that...
o
He wanted to get the guild information whose invite was sent
doesnt really matter , it usually keep running for a week or more until i update it
Source code: Lib/pickle.py
The pickle module implements binary protocols for serializing and de-serializing a Python object structure. βPicklingβ is the process whereby a Python object hierarchy is converted into a byte stream, and βunpicklingβ is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as βserializationβ, βmarshalling,β 1 or βflatteningβ; however, to avoid confusion, the terms used here are βpicklingβ and βunpicklingβ.
also , ill make the calls ( or check )only if a log channel is set for the guild which would me 10-15 at most for now
Wait, or I have an idea... Tho not a good idea, if u wanna hear...
Make raw requests to discord (don't use the client method), and just store the JSON received in a db
here
here ofc
people dont do dm help here afaik
hail aiohttp
Just use discord.Route() haha
a bit harder , but better
But handle the JSON yourself
ah that too
Imho, this is a better way
Since u will have access to the raw JSON and u can save it anywhere then
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
whats the afkppl variable?
mm so whats exactly wrong? the bot doesnt change your nick? you dont go afk?
ah
try using .listen() instead of .event at your on_message
you cannot split a dictionary ( line 3)
!e {}.split()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'dict' object has no attribute 'split'
!e
try():
...
except:
...
``` ~~try function~~
@boreal ravine :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | try():
003 | ^
004 | SyntaxError: expected ':'
if isinstance( .....
# stuff
else:
raise error```
that try's except works if the bot is unable to send the command not found message
No () btw
its reference
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
yes i was meming someone
you see
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
as the error states, you're inserting 6 values to 5 columns
the answer is in the error
U have actually put one extra ? in values
:)
Np π

Bro
that's weird
So I have 3 bots, like the following:
bots\
sir-funbot\
main.py
sir-modbot\
main.py
sir-multibot\
main.py
Each of these bots have their own token, how would I run all these three, at the same time? Like, do I need to connect them somehow?
u need 3 different terminals I think
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect").
Do I really? Can't I make a api wrapper and let 3 clients connect?
Wait nvm, Client.connect wont run any code after it
whats dat
So, is there a way?
To like connect all 3 bots with different tokens, and run them all?
You can use asyncio subprocessing
Is there a tutorial for that?
No
then how would that work?
!d asyncio.create_subprocess_shell
coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.
Important
It is the applicationβs responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands.
Most custom things don't have a tutorial.
from discord.ext import commands
from discord import Intents
import dotenv
import os
dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")
mod_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=mod_intents)
fun_intents = Intents.all()
fun_bot = commands.Bot(command_prefix=".", intents=fun_intents)
multi_intents = Intents.all()
multi_bot = commands.Bot(command_prefix=">", intents=multi_intents)
mod_bot.run(mod_token)
fun_bot.run(fun_token)
multi_bot.run(multi_token)
Wouldn't this work?

Well no since .run() is blocking
Yup just notices
So the 2 bots underneath will never see daylight.
So how would I use that?
Click on the blue stuff it takes you to the docs.
do u know how to make a verifu
I did but don't expect me to understand this, it's completely new for me
learn python
Yes, but we help with discord bot's not make it for you.
uh im excatly asking for a verify command
Bro what??
jk
coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Create a subprocess.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_exec()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_exec "asyncio.loop.subprocess_exec") for other parameters.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
is it plausible for a bot to detect if a user got betterdiscord?
Impossible.
Betterdiscord only modifies JS on the user side so not even normal users can tell if they are using it.
Could u at least give me a hint or an example? I don't understand the docs because of my english
Scroll up on that website
makes sense
thenks
my language is not there
No but an example is.
any possible way to use asyncio.sleep and as well as check for button clicks in the background?
In the same command?
yes
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
timeout will be the time it waits
I've already used it, but I want to use asyncio.sleep() in between command while listening to button clicks simultaneously
They are examples so not meant to be copy pasted.
Well that is what wait_for does.
but when I'm using asyncio.sleep, it stops listening to button clicks
I suggest going to the URL and check out what it does.
Yah I'm never gonna understand this it's completely new for me
I haven't learned async programming yet
Everyone started off like this, if you haven't learned async programming yet. I recommend doing that first, we also don't recommend a discord bot as starting project.
I'm already using it
Asynchronous programming is not something you learn as a "beginner" and no I'm not a beginner, the exact reason to why I do this project (discord bot) is because I need to learn how decorators and asynchronous programming works. I'm not doing this just to do this
Learning stuff in programming separately is bad when it's something intermediate or advanced stuff, therefor I do a project that covers these two
So why do you want to use asyncio.sleep()? 
thats bad.
creating a game like command where user need to press correct button in 5 seconds else it'll skip to next step after 5 secs
I completely agree with this statement, but not the fact you looked at for not even 5 minutes and said " I'm never gonna understand this". You need to do some research before coding, that is part of the job.
generally bare excepts are not a good idea as they hide real errors
I'm not such a fan of the while true in a discord bot either.
ur right mb
ik it's not the actual error, just in case if user has an active session then remove it else just go ahead..
also, why are you defining your functions inside the while True: loop?
for continuous wait_for I've to use it
So try it out copy the example in a separate py file and debug something small. Then if you got it working or get into trouble you can always ask here.
currently I'm just testing it, I'll make it cleaner later after it works
i think you should await the 2nd call
Sure, thanks
!d asyncio.create_subprocess_exec
coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Create a subprocess.
The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).
Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.
See the documentation of [`loop.subprocess_exec()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_exec "asyncio.loop.subprocess_exec") for other parameters.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatβs New in 3.10βs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
I recommend looking at this (tip: read the args & kwargs)
CTRL+F is your best friend
multiple bots with same file?
You can but i recommend using x amount of files for x amount of bots since things can get messy fast.
nah i mean , the X-FRST person ,
are they trying to do that or something related?
Not that i know of.
no?
why'd I?
oh so maybe i gussed wrong because of the subprocess_exec
truth is busy with that.
Yay I fixed it but I ran into a issue
ooh
I saw another method that looked way more simple in the docs
i see , wrong person
from discord.ext import commands
from discord import Intents
import asyncio
import dotenv
import os
dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")
bot_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=bot_intents)
fun_bot = commands.Bot(command_prefix=".", intents=bot_intents)
multi_bot = commands.Bot(command_prefix=">", intents=bot_intents)
@mod_bot.event
async def on_ready():
print(f"Connected to {mod_bot.user.name}")
@fun_bot.event
async def on_ready():
print(f"Connected to {fun_bot.user.name}")
@multi_bot.event
async def on_ready():
print(f"Connected to {multi_bot}")
loop = asyncio.get_event_loop()
loop.create_task(mod_bot.start(mod_token))
loop.create_task(fun_bot.start(fun_token))
loop.create_task(multi_bot.start(multi_token))
loop.run_forever()
Connected to Sir Modbot
Connected to <discord.ext.commands.bot.Bot object at 0x000001D0FF4A2EB0>
Connected to Sir Funbot
This is the output, it seems to confuse inbetween the names?
What could I do?
wdym by confuse between the names?
@mod_bot.event
async def on_ready():
print(f"Connected to {mod_bot.user.name}")
@fun_bot.event
async def on_ready():
print(f"Connected to {fun_bot.user.name}")
@multi_bot.event
async def on_ready():
print(f"Connected to {multi_bot.user.name}")
Returns:
Connected to Sir Funbot
Connected to Sir Multibot
Connected to Sir Modbot
It's wrong names
order of the printing statement?
doesnt depend on the order you defined the on_ready events
it gets print as per when they are ready
Ah I see
Thanks guys
But is there a easier way of doing this btw?
like, shorter
wdym?
Nvm I was wrong, it was correct
Not that i recall since you are working with multiple bots
Right
That's why i said to use x amount of files for x amount of bots since it can get messy fast
maby there is a way to make it shorter but i'd need to do research myself to find that out. Not many people do this so there will likely not be any examples.
Can no one help me
Who knows is not helping and others doesn't know

I see whatchu mean I also ran into a issue when I tried to make cogs for all of the bots
How so?
from discord.ext import commands
from discord import Intents
import asyncio
import dotenv
import os
dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")
bot_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=bot_intents)
fun_bot = commands.Bot(command_prefix=".", intents=bot_intents)
multi_bot = commands.Bot(command_prefix=">", intents=bot_intents)
# File handler for Sir Modbot
for file in os.listdir("sir-modbot/events"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"events.{name}")
for file in os.listdir("sir-modbot/commands"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"cog.{name}")
# File handler for Sir Funbot
for file in os.listdir("sir-funbot/events"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"events.{name}")
for file in os.listdir("sir-funbot/commands"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"cog.{name}")
# File handler for Sir Multibot
for file in os.listdir("sir-multibot\events"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"events.{name}")
for file in os.listdir("sir-multibot/commands"):
if file.endswith(".py"):
name = file[:-3]
mod_bot.load_extension(f"cog.{name}")
loop = asyncio.get_event_loop()
loop.create_task(mod_bot.start(mod_token))
loop.create_task(fun_bot.start(fun_token))
loop.create_task(multi_bot.start(multi_token))
loop.run_forever()
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'events'
bots/
run.py (the main file for all the bots)
sir-multibot/
events/
on_ready.py
commands/
[no files yet]
sir-funbot/
events/
on_ready.py
commands/
[no files yet]
sir-modbot/
events/
on_ready.py
commands/
[no files yet]
reason why one should not use multiple bot this way , also the error says it all
no module named events exist
is there anytn like if guild.community == true:? like the bot gets to know if community is enabled
It does tho
!d discord.Guild.community
No documentation found for the requested symbol.
!d discord.Guild.features
A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.
They are currently as follows:
beat me to it :(
and check if COMMUNITY is in the list
thenks youse
your wellcame
cya panda , have fun
Can no one help me
Who knows is not helping and others doesn't know
your problem?
did you forget to add __init__.py files to your folders?
I don't need to?
Or do you mean if i initialize my event classes?
if so yes, i do call the __init__ method on my classes
Here is a example of one of the on_ready.py file:
from discord.ext.commands import Cog, Bot
import discord
class OnReady(Cog):
def __init__(self, bot: Bot):
self.bot = bot
@Cog.listener()
async def on_ready(self):
print(f"Started client as: {self.bot.user}")
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Commands: >help"))
def setup(bot):
bot.add_cog(OnReady(bot))
ah wait I see you imported the modules by individual filenames
how do i make inventory check for the amount i have
if you'd like you can just add __init__.py files (like this https://github.com/OpenDebates/OpenDebates/blob/master/plugins/debate/__init__.py to your folders and just load them as extensions.
you never assigned a value to variable amount so it can't find it
help i no brain ok
also replit has a built in database that you should use instead of external json files
I first need to figure out how I can add cogs π€·
i have a stupid in my brain
the on ready cog looks good aside from loading activity in an on_ready event which I've heard some people complain about but it honestly doesn't matter
oh wait
Im an idiot I see your issue, you're prefixing these filenames with simply events. or cogs. which aren't actual relative filepaths to run.py's working directory
you should prefix them with sir-funbot.events or their other respective paths
Ohhh im an idiot too XD
It works now, thanks
I saw someone importing clean_content from disocrd.ext.commands What is it?
It converts the mentions etc to raw text
oh
<@tawdry perch> instead of @tawdry perch
Can't really format it on discord
Can no one help me
Who knows is not helping and others doesn't know
good step is to tell the problem
Problem is my music command. Till yesterday it was working but today not working. Shows some error
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
code = clean_code(code)
local_variables = {
"discord": discord,
"commands": commands,
"bot": bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message
}
stdout = io.StringIO()
try:
with contextlib.redirect_stdout(stdout):
exec(
f"async def func():\n{textwrap.indent(code, ' ',)}", local_variables
)
obj = await local_variables["func"]()
result = f"{stdout.getvalue()}\n-- {obj}\n"
except Exception as e:
result = "".join(format_exception(e, e, e.__traceback__))
pager = Pag(
timeout=100,
use_defaults=True,
entries=[result[i : i + 2000] for i in range(0, len(result), 2000)]
length = 1,
prefix="```py\n",
suffix="```"
)
await pager.start(ctx)
im trying to make a eval command
the prefix thing its prefix = '''py\n and suffix='''
share the code + error or it's a bit hard to help
how do i make inventory checker for how much amount i have
for thing in users[str(ctx.author.id)]["inventory"]:
thingy = thing["amount"]
print(f"{thingy} found")```
We won't help with music bots, other than that, that is prob the reason why you are not getting helped.
breh what..?

Wdym
how do i make that it check how much item amount i have in my inventory
^^
if thing in f.read():
#do your stuff here```
or .json or what ever
can someone give me the code for a suggest command so where do u !suggest and it makes a suggestion
tank you veri mach
np
ok idk where to put it
i need help
Error says all
what do it do?
Create a suggest command
how?
im new to py
Have you learned Python before starting your bot?
yea
Then follow this tutorial to know how to create commands
https://vcokltfre.dev/tutorial/04-pong
And use the documentation to help you
https://discordpy.readthedocs.io
can someone help me with a eval command?
have you defined the suggest command
hello
no
do it
define it then
so
how
please?
fix it urself
create that suggest command
what do you want to help with
have u done the @bot.command() async def suggest
i share u my replt and u help me with the code, bc idk
im gonna sleep very soon, just show me the thing
where?
do i do it in main.py?
yes?
@bot.command()
async def suggest(ctx, and something more):
at the top of your function
I suggest you to learn the basics of discord.py
^
@slate swan do u know how to make a eval command? bc i have no idea
Copy pasting code won't make you learn
i saw a tutorial but it doesnt work
might be old code + you are copy pasting, are you?
im not
Welcome back to the discord.py series! Here's a overwhelmingly requested command :D
Read description for links!
----------------------------------------ΒΒ---------------------------------------Β-Β--
Need Help?
Require help with your code? Why not head on over to our dedicated support discord where you can receive only the best support: https:...
I have few checks in my code but how do I handle them in error handlers? eg, this can raise CheckFailure bΓΉt bot can't yet handle it ```py
async def cog_check(self, ctx):
'''Allow only moderators to invoke these commands'''
user_role_ids = [role.id for role in ctx.author.roles]
return ctx.author.id == SPECIAL or any(role in user_role_ids for role in check_author())
from discord.ext.commands import command, Context, Cog, Bot, has_permissions, bot_has_permissions
from discord import Embed, Colour
import random
from discord.ext.commands.core import bot_has_permissions
class Catify(Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
@has_permissions(change_nickname=True)
@bot_has_permissions(manage_nicknames=True)
@command(name="catify")
async def catify(self, ctx: Context) -> None:
responds = ["Certainly not.", "Not likely.", "Nah."]
cats = ["ααα’", "α‘αα’", "α¦αα’", "ααα’", "α£αα’"]
catify = random.choice(cats)
if len(str(ctx.author.name)) == 23 or len(str(ctx.author.nick)) == 23:
respond = random.choice(responds)
embed = Embed(
title=f"{respond}",
description="Your display name is too long to be catified! Please change it to under 26 characters.",
color=Colour.brand_red()
)
await ctx.send(embed=embed)
else:
await ctx.author.edit(nick=f"{ctx.author.name} | {catify}")
await ctx.send(f"Your catified nickname is: `{ctx.author.nick}`")
def setup(bot: Bot) -> None:
bot.add_cog(Catify(bot))
Error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
What am I doing wrong?
!cod
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
put the code and error in it
@client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
role = discord.utils.get(member.server.roles, name='Muted')
await client.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="{0} was muted by {1}!".format(member, ctx.message.author), color=0xff00f6)
await client.say(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await client.say(embed=embed)```
erm so server permissions
@client.has_permissions(administrator=True) next to the
anyone know how to send a message to a user using their user id?
specifically here
what?
Then what to do how to fix that
I don't know that
A dm or a msg with a mention
Getting the guild id in an on_user_update event in discord.py does anyone know how to do this??
You've already been told that we do not help with any projects that use ytdl here, as it's against YouTube's terms of service. Please stop asking about it.
u there?
Error ?
You cannot add parameters as you wish
Remove the *, message parameters
does not work either
how do i edit the most recent message in a channel
the most recent message from the bot
By using get_user(id) and saving it in a variable, then you can use .send() on that variable
like this?
No
do i have to use send?
Yes
or send message
oh
|send_message` is old code
You shouldn't copy paste from internet old code
And it's get_user
And the IDs are integers, not strings
true
thank you
And it's not bot.send but just user.send
thanks again
And?
That's what your code does, it's correct
Add .mention if you want to mention the user
i think i did something wrong here
i did not get any error but when i type shoot nothing happened
Then just ctx.message....
how do i edit the most recent message in a channel
the most recent message from the bot
It's just user.send("stuff")
Remove the message argument, already told you
do i have to use prefix while using in server?
@slate swan
And no you don't, it checks for every message, as the event name says
ah okay
message.content, basic python objects...
still π¦
it doesnt send me a dm
why doesnt it work
where
No
Don't mislead people
π
The user is not in cache, so you'd need to use ...get_user(id) or await bot.fetch_user(id)
It's not a command, read the code please....
And I'm not your bro
oh god
^^
Anyways, enjoy getting mislead, have a great day 
what no , i am just trying to make it work
i did use it still doesnt work
any idea why?
Again, remove the unneeded user,
Just user.send("blah")

yes still same
Do you even get errors
no it just did not send me any dm
oh wait i have an idea i'll use a print()
!code ;-;
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I have few checks in my code but how do I handle them in error handlers? eg, this can raise CheckFailure bΓΉt bot can't yet handle it ```py
async def cog_check(self, ctx):
'''Allow only moderators to invoke these commands'''
user_role_ids = [role.id for role in ctx.author.roles]
return ctx.author.id == SPECIAL or any(role in user_role_ids for role in check_author())
An on_message event only takes a message argument
So stop misleading people
okay so IF block is not triggered
I already told you that a few minutes ago....
this does not print the print statement
so if block is FALSE?
What message do you send
shoot
right?
Wait, why do you use await get_user
await is only for fetch_user
bot.get_user(id)
await bot.fetch_user(id)
Like that
Only fetch_user is a coroutine
oo
get user doesnt have to be coroutine
you are right
No, get_user is not a coroutine, nothing to do with having to be one or not
right
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
Check at the end of that section, you need to raise your own error
same
if loop evaluates to false
What is your code now
Print the message content
message.content ?
Yes
in the IF loop or out
Before your if statement of course
ok
all how write code in frem ?
nothing gets printed on console
π€¨
not even this
other commands work tho
Do you have another on_message event?
no
only one
!!!!????????
only one
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
async def GetMessage(
bot, ctx, contentOne="Default Message", contentTwo="\uFEFF", timeout=100
):
embed = discord.Embed(title=f"{contentOne}", description=f"{contentTwo}",)
sent = await ctx.send(embed=embed)
try:
msg = await bot.wait_for(
"message",
timeout=timeout,
check=lambda message: message.author == ctx.author
and message.channel == ctx.channel,
)
if msg:
return msg.content
except asyncio.TimeoutError:
return False
def clean_code(content):
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:])[:-3]
else:
return content
code = clean_code(code)
local_variables = {
"discord": discord,
"commands": commands,
"bot": bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message
}
stdout = io.StringIO()
try:
with contextlib.redirect_stdout(stdout):
exec(
f"async def func():\n{textwrap.indent(code, ' ',)}", local_variables
)
obj = await local_variables["func"]()
result = f"{stdout.getvalue()}\n-- {obj}\n"
except Exception as e:
result = "".join(format_exception(e, e, e.__traceback__))``` my eval command doesnt says anything
bro how you wrtie this command in Framework
idk xd
everone
Hi, how can i run a exit function inside a class and use commands for discord in it?
not suitable for this server
I didn't posted any n#de content π€·
I don't think this is best place to ask in, I can be wrong as well
Search for nsfw APIs
There're a few out there
Is that from my repository?
Ah, no it's not.
dpy is just to communicate with discord. Discord does not supply any images for you
i know, i just added that because then it wont be related with that channel ig
@bot.command()
async def move(ctx, user : discord.Member, channel:int):
await user.move_to(channel)
await ctx.send(f"He movido a {user.mention} al canal de voz {channel.mention}!")```
why does this not work?
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
Type hint your channel argument to discord.VoiceChannel instead of an int
tnxxx
async def strike(ctx, member: discord.Member, *, reason):
current_strike_count = len(
await client.strike.find_many_by_custom(
{
{user_id: member.id, guild.id: member.guild.id}
}
)
) + 1
strike_filter = {user_id: member.id, guild.id: member.guild.id, number: current_strike_count}
strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "striked by": ctx.author.id}
await client.strike.upset_custom(strike_filter, strike_data)
await ctx.send(f" you have been striked {reason}, {current_strike_count} ")````
it give me an error and i dont know what it wants
''The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'strike' ````
thats the error
its not all my code
trying to learn how to do somthing like this so used somone elses code to base off of to make mine
its how i have been learning
Is it possible to edit this icon on the playing status?
message.content was removed
anybody have an announce command code i can use pls
that i can !announce 'message'
or something like that
We don't give code, we help you progress with the issues you face
run the coroutine before you subscript from it. IDK if that makes sense but:
https://leo.actually-needs-more.tech/5eXyS4ath
you cannot do stuff = await func()['key']
it will first run the ['key'] and then the await
You need to surround await get_entry with round brackets before indexing
(await ...())[i]
if you want it the other way around, first do the await func, get the result, and subscript that
or surround it with round brackets
Just like in math, basically your forcing the order of operations
Hello, how can we make our bot create a role or what they have the role can see it?
?
Is it possible to change this icon
Bots cant use rich presences, last i checked.
Can I have some easyish bot command ideas?
They can't and it seems like this user is using a selfbot
my user info command shows account creation date and user badges, im trying to make it find badges for users outside of shared guilds, i understand that i have to use fetch with this, but id have to also use a memberconverter to do so, which i dont know how to do, so ive thought of alternatives, could i do something like (user: Union[discord.User, discord.Member, id:int)]
Why do you need to use the member converter?
A member is connected to a guild, it wouldn't be possible if you don't have a shared guild
using fetch, id have to redefine it wouldnt i?
thats just what i was told lol
i mean via user id
so if the user id that the author sent in the userinfo command belongs to a user not in the guild, then it doesnt return the rest of the command like status, presence, and joined time (which is what i also have in the command)
just badges and creation time (which i have defined)
You just typehint Member | User like you are doing right now
Then you isinstance the user variable
To check whether or not its a User or Member
so (user: Union[discord.User, discord.Member, id: int)] could work?
Why do you have the id??
so it can pull data that i want for users that arent in the guild
You can just typehint User
There is no point of id here
And that isn't even valid
whats typehint..
Union[...] is a typehint,
ohh
You are typehinting User | Member currently
alright
so to clarify, ...(user: Union[discord.User, discord.Member]): can work for what i need it to do?
Yes, then you isinstance user to check if its a User or Member
If it is a user you pass the id attr of user to fetch_user
alright, that doesnt seem all that difficult
by chance, is there a doc for this?
fetch_user returns a discord.User object, this object has an id attribute
You can access it via dotnotation or getattr
The userβs unique ID.
ty
stop sending the file and embed together
only send one, in this case the embed.
that should work
Oh ok
Yep your fix is the only fix
what I said up above does not work
just tried
time wasnt an int
Read. The. Error.
your command expects the input tempmute (user) 60 m, you did tempmute (user) 60m
also
for role in guild.roles:
if role.name == "Muted":
await member.add_roles(role)
``` is an extremely inefficient way to achieve this, you should either do guild.get_role(id), or if you insist on using the name, use `discord.utils.get(guild.roles, name='Muted')`
How do you put int in the time para?
read my response
Yeah ik that but i forgot to change it
discord.utils.get literally does the same thing he is doing internally iirc
I mean, all get methods in dpy are O(n) iirc so
Yea it should be
i assume it would be more efficiently made, and is also a LOT cleaner in terms of code
so even if only for that last part it's better
discord/utils.py lines 436 to 449
if len(attrs) == 1:
k, v = attrs.popitem()
pred = attrget(k.replace('__', '.'))
for elem in iterable:
if pred(elem) == v:
return elem
return None
converted = [(attrget(attr.replace('__', '.')), value) for attr, value in attrs.items()]
for elem in iterable:
if _all(pred(elem) == value for pred, value in converted):
return elem
return None```
By far def not efficiently made
How do i make it remove the role?
member.remove_roles(role)
No i mean doing the command to remove the role?
I'm gonna retract that claim, cause I cba rn to analyse
my code wont work
how do i mention a specific channel and a specific role
ive done everything
<@#channel_id> <@&role_id>
i did that
or channel.mention/role.mention will generate these for you
give me an error
except show us your code and error
uh?
no error it just wont work but ill send
import discord
from discord.ext import commands
import discord
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, MissingPermissions
from discord.utils import get
import os
import datetime
import asyncio
import time
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix = "$", intents=intents)
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#response messages
@client.event
async def on_message(message):
if message.content == "ok":
await message.channel.send("ok is gay")
if message.content.startswith("lol"):
await message.channel.send("Hi nub")
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await ctx.message.delete()
await member.kick(reason=reason)
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permission to kick people")
@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
my_secret = os.environ['TOKEN']
client.run(my_secret)
show your code, tell us what you mean with "won't work"
- Why do you have client = commands.Bot? That's just bad naming convention
- It's the on_message
Your overwriting the default on_message event, which is where the bot internally does process_commands
Either change your on_message to a listener via .listen() instead of .event
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
async def shopclose(ctx):
embed = discord.Embed(
title=' Shop Status ',
description=f' Keep and eye on {channel.mention_866571652518641684} for the reopening . ',
colour=discord.Colour.red())
embed.add_field(name=f" {role.mention_866837934611234838} :",
value=" WARZ shop is closed ",
inline=True)
embed.set_image(url='https://www.bing.com/images/search?view=detailV2&ccid=D4b7Nqnb&id=EC0104FDB53D8D309F68E2144FBCC1B208B68AF9&thid=OIP.D4b7NqnbO0MtNZHjAAb_ngHaEK&mediaurl=https%3a%2f%2fth.bing.com%2fth%2fid%2fR.0f86fb36a9db3b432d3591e30006ff9e%3frik%3d%252bYq2CLLBvE8U4g%26riu%3dhttp%253a%252f%252fmarketingland.com%252fwp-content%252fml-loads%252f2015%252f03%252fwere-closed-sign-ss-1920.jpg%26ehk%3d%252bzG3XCKcq0Tziqc7a3lKRQSq9I7avPDVigdXMI2wTEQ%253d%26risl%3d%26pid%3dImgRaw%26r%3d0&exph=1080&expw=1920&q=closed++sign&simid=608027194431859752&FORM=IRPRST&ck=3F58E2BEAD445516EFCA189E39308CE6&selectedIndex=8')
await ctx.send(embed=embed)```
the error
Traceback (most recent call last):
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'channel' is not defined```
channel isnt defined
channel doesn't exist, and even if it did, mention_866571652518641684 is not an attribute of a channel
i get that but when i put it in like
async def shopclose(ctx, channel.mention, role.mention)
Bruh
i just seen his mssage
you cannot use attributes as argument names
ok
you must supply a descriptive name, and a . character is NOT permitted
ok
just get the channel then mention it
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
if you have the ID, this is rather overkill, and error prone if the cache isn't in check
just do <#id> at that point
Fetch it then?
ah
API calls should be avoided at all costs
π
so for the channel just do {id}
Imo API calls should be avoided when they aren't needed for an action, they shouldn't be avoided to the point where it becomes cumbersome to do what you want effectively
.....?
@blazing coral
okay different wording: avoid API calls when you can
That sounds a lot better
[#python-discussion](/guild/267624335836053506/channel/267624335836053506/) like this
#python-discussion == [#python-discussion](/guild/267624335836053506/channel/267624335836053506/)
alright
<@&764802720779337729> = <@&764802720779337729>
<@!user_id> or <@user_id> (discord really is inconsistent when it comes to user mentions. It accepts both as input, and returns either with or without !)
<@&role_id>
<#channel_id> (can be any channel type)
Channel
I know, I'm just saying so
Cause some people don't know you can
<@!user_id> or <@user_id> (discord really is inconsistent when it comes to user mentions. It accepts both as input, and returns either with or without !)
This used to be here for nicknames iirc
But now there is no difference
it's the same yes, but discord returns either one or the other and it's just 
like just remove the one without ! to make it consistent a special character for each case
alright the channel one worked but the role one didnt
How didn't it work
the thing that bothers me is that if you want to make something that can find mentions in a message, you need to check both cases because discord just doesn't return one or the other, but a mixmash
π€¨
So your just gonna throw backwards compatibility out for visual preference?
it's been deprecated for quite a while, and it's not just visual but actually a logical thing programmers have to keep in mind
why does this not work?
define "doesn't work"
Unless you are parsing it raw, the wrapper you use should be handling everything already
This isn't a normal usercase
if looop evaluates to false
jokes on you, i am that user that makes a wrapper
Plus, keeping it allows for backwards compatability
when i type shoot in server nothing happens
Is disthon still being worked on?
definitely
What stage are you guys at right now
tho a lot of devs are currently very busy with school so it's been a bit slower the last few weeks
currently being very busy with getting everything working again because someone decided to push a major update without testing it properly and it's riddled with errors, but it's also a lot of valuable code and not worth it to just revert
Why do non maintainers have power to push directly?
https://github.com/AA1999/Disthon/tree/import-fix current state
it was a maintainer
Ah....
it was literally the owner of the library
Yikes
Me and blanket are grinding lefi down right now pushing hella commits, thats why I added a lot of CI
So I don't break anything
Blanket alr finished voice impl, and now I just need to finish interactions and its off to v1.0.0
It mentions the channel just not the role
you cannot mention a role in that field
But it did thou like I said it mentions the channel not the role in the embed
did u realize blanket got banned
I do, because the mods think he joined on an alt
you can mention things in the value or description of an embed/embed field, not in the title or name of an embed/embed field
Oh alright
he joined on an alt?
Makes sense
i'd say this isn't the place to discuss infractions and whatnot
No, he was calling someone a beginner and someone joined and insulted the user
Mods thought it was him
ah thats what he told me
I was hoping once we got these major errors out the way we could start implementing our models into the API handling stuff and hopefully push for an early first build to be published
i mean i could push to pypi right now, but once you import the library you get an error right away haha
Your codebase owner should really learn how to do packages correctly
At least repo's getting serious development
i've tried to tell him a lot, just he pushed without thinking since he did a ton of work
he sometimes just is a bit overambitious and just spurs out random things that aren't exactly...right
A tip from me is to add a lot of CI
Catches a lot of things
Like if you take a look at lefi's repo, you can see a lot of CI and tests
I even went a bit overboard and wrote shell scripts and a Makefile
i have no idea what a CI even is and i doubt anyone else knows apart from maybe alec
Workflow stuff, continuous integration
if i have some time i might just see if i can take a look
And you should start documenting all your models in disthon, it gets really hard to catchup later on
I would know
π
issue is we're still making major changes atm so documenting was put off a bit
we are aware and it's on the agenda
we'll try to add at least docstrings to everything in the near future
Are you gonna be doing RST docs
owner already claimed a RTD page for it, it's just empty atm: https://disthon.readthedocs.io/en/latest/
I'm talking about your docstrings format
so how would i go about getting my command message to delete after the embed is sent
ah that
Command message?
!pep 287
Ah RST, gl
yeah so when i type the command pp!d shopopen
Does disthon have a support server or a group dm, cause I have time to do code reviews, seems like you guys need it
i want the command to delete after the embed has been sent
A fellow wrapper maintainer gotta communicate with others
there is a discord server yes

Where do I find this
how do i get my command message to delete after the embed has been sent
sorry to be a bother by the way
ctx.message.delete()
so it would be somthing like
also next time, just put the message, no need to reply to a random message
? im lost what you mean by just delete
it takes no arguments he means
oh alright
discord/message.py lines 1109 to 1116
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
Your own messages could be deleted without any proper permissions. However to
delete other people's messages, you need the :attr:`β~Permissions.manage_messages`β
permission.```
smile
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleβs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
yes
Is there an error
async def shopclose(ctx, delete):
await delete('pp!d shopclose', delay=None)
embed = discord.Embed(
title=' Shop Status ',
description=f' Keep and eye on #audit-log for the reopening . ',
colour=discord.Colour.red())
embed.add_field(name=f" :",
value=" WARZ shop is closed <@&907084137490448435> ",
inline=True)
await ctx.send(embed=embed)```
there is the code
it didnt work
here is the error
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: delete is a required argument that is missing.```
ah
delete doesnt take any arguments only keyword arguments
what about this? any ideas?
so ....
well now you created a delete argument, which must be passed
So remove the string and delay from it
alright
The message that triggered the command being executed.
but if i remove the string im going to get a syntax error
you aren't?
but i did
Whats the error
await delete(pp!d shopclose)
^
SyntaxError: invalid syntax```
Do you know what a string is
those are quotation marks
i know what an f string is
"string" <= this is a string
i didnt say f string
yes so a " " is a string
your supposed to delete the string not remove the quotation marks from it
@blazing coral read that first click the link
# Server is mc.hypixel.net
async with aiohttp.ClientSession() as session:
async with session.get(str('https://api.mcsrvstat.us/2/') + str(server)) as OpenURL:
theJSON = await OpenURL.json(content_type=None)
Keep getting Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0) error, don't know why
so i figured out this whole block is not running
any idea why?
ok
bot.listen()
@bot.event
what?
JSON link doesn't exist?
i am using bot.listen so it doesn't over ride bot.command
it works for me.....
Well click the link can you show me the JSON output
as you see in the code, I am adding a string set to mc.hypixel.net
str('https://api.mcsrvstat.us/2/') + str(server)
o
ohhhh
the slash is canceling the '
nvm
I don't need help anymore 
nvm, didn't fix lol 
its not
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
^
check the example
When I using on_member_join/remove, how do I tell what guild they left?
member.guild
@commands.Cog.listener()
async def on_guild_remove(self, guild):
print(guild.name)
^
Ah yeah, that makes sense. Thanks anyways haha
nah you sent the right thing
well I mean it works
Wait how would I get the member then?
I sent on_guild_remove, not on_member_leave
#bot-commands
nvm lol
ok
yeah
need help mentioning someones tag when i ban them
idk what it is
if its like user.tag
user.discriminator
!d discord.Member this returns the member name/tag iirc
or member.tag
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
so i should not use listen?
ok ty
Why wouldn't you?
.listen() is already great why would you change it
so what do u recommend?
what's causing the problem
you tell him then
I have no experience with .listen() which is why I wouldn't use it.
why does it not get triggered
if you have no experience with it why'd you comment on him?
you should understand things first before commenting on stuff
didnt work
that showed this <class 'discord.member.Member'>
from what part does it stop executing
what u mean?
other commands still work
does it not print anything at all?
use the member object not the class
embed.add_field(name = "test", value = discord.Member, inline = True)
why u using the class
listen is great, it should be prefered over .event depending on condition
π€¨
oh
didja put parenthesis?
that's what someone told me here earlier that's why i am using it
the way it's often done: .event with on_message to check if the message is by a bot, if it is, return ,if not process_commands
cause I thought he meant event
i've seen it be done in danny's bot that way
then why does my code not work?
what do you mean by "not work"
was your bot online when u ran the event
and can you send your code?
it just doesnt work, neither it prints the print() command nor it does anything when i type shoot
okay, can we see the code ?
whats the object again lol
yes there is another commands they work
sure
maybe the event isnt getting triggered
u want the full code?
no just the .listen
the print isn't getting triggered?
is this bot verified? are the message intents on?
sorry what?
is your bot verified?
do u mean this?
no
enable message intents
where?
in the dev portal, also in the code
hmm
intents.messages = true
U can think object as car which has different attributes(color,etc) and method(driving etc)
@sick birch its on
i meant like
what about in the code?
an example with code
!d discord.Intents.messages
Whether guild and direct message related events are enabled.
This is a shortcut to set or get both guild_messages and dm_messages.
This corresponds to the following events...
and in the code as well
intents.messages = true
like so
roles = discord.utils.get(member.guild.roles,"Member", "β¬β¬β¬ Reaction Roles β¬β¬β¬", "β¬β¬β¬ Member Roles β¬β¬β¬")
Is that how you add multiple roles when a member joins?
or is it autorole
no
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
get the role
utils.get takes an iterable, and an attribute
@robust ridge
Ok so thats not how a member gets a role when he joins
Glad to helpπ
No documentation found for the requested symbol.
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
^
alright done
get the roles one by one
^
or use a map()
a = discord.utils.get()
b = discord.utils.get()
``` and so on
it still doesnt work
map/list comp works just as well
π
that's odd, try intents.all() just for testing
.
where
It take iterator so in () write (ctx.guild.roles, name= "your name")
It will return the first match
instead of intents.default() do intents.all()
alright
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
right?
_role = discord.utils.get(ctx.guild.roles,name= "your role name")
still
Is there any await type with that code?
if that make sense
If u check documentation it has mentioned where to use await
async def on_member_join(member):
guild = client.get_guild(730651046459998218)
channel = guild.get_channel(885464532959526913)
myEmbed = discord.Embed(title = f"Welcome",
description= f"You are member {guild.member_count}, \n Enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)", color=0x0ff00)
myEmbed.set_image(url=f"{member.avatar_url}")
await channel.send(embed=myEmbed)
autorole = discord.utils.get(member.guild.roles, name='Unverified')
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
roles = discord.utils.get(ctx.guild.roles,name= "your role name")
await member.add_roles(autorole)
Here is my code
Try once and see
Wait aren't u storing in variable?
discord.utils.get line will find and return obj
my bot perms
U need to store it in order to work with it
Your on_message is indented inside your on_ready
He forgot process command line too
so what should i do
Client doesnt have commands
Ahh
i dont get it i am new
Got it
no i am wanting to do where a user/member joins he gets autoroles
Do you know what a indent is
U need to store roles in variable obj in variable mate
Then only u can assign
yes
here is the full code
https://www.toptal.com/developers/hastebin/dagevolodu.py
if someone can take a look
@slate swan make if both in same vertical line
So i cant let the bot assign these roles for me?
Check your 2nd if ,it has more space
Yes u can but how bot will know which role to assign
ohh ik this is where i would write the variable like this
you want me to backspace?
!intents learn more python
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
roles = discord.utils.get(ctx.guild.roles,name= "Levels")
Yes 2nd if has more space
especially code from line 21 to 30
Ty didn't know this existed
Check 2nd if mate

Make it same as 1st if
Doesnt need it
yeah make the both if on the same line
2nd if has more space at starting
Intents are for commands that use stuff related to members
Can someone tell me how to make music bot
If on yt no
Wdym
In python indentation is important in your case after return everything is ignored
Dont think he needs intents
I search it, but it is outdated
i meant indents typo oops
Yeah i figured
If on yt cant help you its against yt tos
Ok
look at yt