#discord-bots
1 messages ยท Page 832 of 1
Just typehint your userid arg to discord.Member
PoV: They copy paste what u said and come with a required arg error
how do i do that?
๐ฟ
Do you know how to typehint
: user ?
i.e
my_var: str = "my string"
no ๐ก
my_var was type hinted to str
im not dumb ๐ก
ok
no i just obsered i mistakely copy paste the same code somewhere in other cogs file which was pending it was giving error
elif not channel1:
channel1 = await ctx.guild.create_voice_channel("PRVC-1", category=category)
await channel1.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await channel1.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
s = disnake.Embed(title="Created a Private voice PRVC-1",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
```succesfully creates channel + sends message but didnt append the item @slate swan
- no error at all
ownvc = []
When you print ownvc what gets printed
two pings?
both mine
Send your entire function
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

๐ฅฒ
whole command i edited till now
@final iron
why
Command groups be like : 
๐
why
never heard of that
Hey @grim topaz!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hey @grim topaz!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Was meant as a joke, calm down
all died after seeing my code
What did I just see...
.
Hey @grim topaz!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Dude please use a for loop and list
if channel with that name already exists: skip
where
Just make a list with all the channel named and do something like
for cnl in cnl_list:
channel = utils.get(...)
if not channel:
await guild.create_voice_channel(name=cnl)
lol
Uhhh?
i have a toatal 10 channels
!d discord.ext.commands.Bot.group v cool
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
Sooo?
channel = what
ok..
It will either return None or the Channel object
elif type == "address":
try:
for i in range (0, len(Json_Items)):
for x in Json_Items[i]:
for c in Json_Items[i][x]:
if (','.join(Json_Items[i][x]["Payment Address"])) == str(id):
print("hello")
done = True
break
else:
if done == False:
print("bye")
done = True```
yo how do I make this code stop if it detects a real address? and only print "bye" once if it detects a fake one? right now it just prints both depending on the number of items in Json_Items
and what can i chnage
break?
has nothing to do with discord bots tho
True
@bot.command()
async def new(ctx, member:discord.Member=None, *,message=None):
guild = ctx.guild
if member == None:
return await ctx.reply("ื ื ืืชืืื ืืืฉืื")
if message == None:
return await ctx.reply("ืืจืฉืื ืืืืขื.")
embed=discord.Embed(title=f"{message}", description="ืืืฅ ืืื ืืืฆืืืข")
embed.add_field(name="Owner", value=f"{member.mention} ({member})", inline=False)
new_channel = await ctx.guild.create_text_channel(name=f"{message}", category="Servers")
channel = ctx.guild.get_channel(new_channel.id)
msg = await new_channel.send(embed=embed)
await msg.add_reaction("")```
Not working, Error:
Which line raises it
what ya mean break
break keyword
U want to break the loop if the bot found a real address
Ye
ye but the problem is
is that when it finds a fake one
first, it still outputs the fake one
how do I like make it only output once its done
I just explained it to you
and found the issue bro was stuck on that for lik ean hour
if statement and continue keyword, idk if you're working with an api to check the address is real or fake, anyways if the api print "fake" if the address is fake then you gotta do py if idk == "fake": print("bye") continue
idk tbh
try and see
it will most likely not work, and you should perfectly know why
can anyone help me?

also that ^ AND the if statement will never be True
there's more to your error normally
Yes
Mmmmm i suggest u to use discord.utils.get instead of ctx.guild.get_channel
you can't pass a string as a category
you need to get the category with utils get
Okay, but is that the problem?
your "Servers" is the problem
^
Oh, ok
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
tanks
@maiden fable
for channel in vclist:
get = disnake.utils.get(ctx.guild.voice_channels, name=channel)
if not get:
channel12 = await ctx.guild.create_voice_channel(name=channel, category=category)
await channel12.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await channel12.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
s = disnake.Embed(title=f"Created a Private voice {channel}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=s)
```fine
terrible variable names tbh
huh
- error says it all
- you should know why your if statement will never be True
you use a-to connect the name and discriminator
s, channel12, ...
all terrible names
who cares
people who try to help you
lol
all fun and games until someone has to decypher whatever those variables actually represent
ok
else:
for channel in vclist:
get = disnake.utils.get(ctx.guild.voice_channels, name=channel)
if not get:
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category)
await createdchannel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {channel}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
``` fine
get, channel
channel is fine?
what channel? a vc/ textchannel/categorychannel / ...
and what's its purpose? like a send_message_channel, so you know you'll need it in the end etc etc
else:
for channelname in vclist:
gettingchannel = disnake.utils.get(ctx.guild.voice_channels, name=channelname)
if not gettingchannel:
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category)
await createdchannel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {channelname}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
now you just made get a gettingchannel, that's like a bit of help, but not that much
you could make it current_vc, to refer to it as you're looping through it, ...
else:
for vcchannelname in vclist:
gettingchannel = disnake.utils.get(ctx.guild.voice_channels, name=vcchannelname)
if not gettingchannel:
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category)
await createdchannel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {vcchannelname}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
ok.
so vclist is a list of voicechannelnames?
yes
then you could call that vc_names, etc etc etc
else:
for vcchannelname in vclist:
current_vc = disnake.utils.get(ctx.guild.voice_channels, name=vcchannelname)
if not current_vc:
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category)
await createdchannel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {vcchannelname}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
tf
also if I were to type out vcchannelname, it basically is voice channel channel name
so just vc_name is clear ig
stop
you'll thank yourself later, you see it as a struggle
yeah, you clearly hate it
nvmd
Set the permission in the create channel itself
huh
in your category, you probably want to loop through OR text channels OR voice channels, not both
permissions = ?
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
overwrites*
woah who deleted not me
Automatically
ok..
for vcchannelname in vclist:
current_vc = disnake.utils.get(ctx.guild.voice_channels, name=vcchannelname)
if not current_vc:
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category , overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {vcchannelname}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
tf fine?
ownvc is a list of IDs?
nightmares
you'll have them for sure
yes
createdchannel = await ctx.guild.create_voice_channel(name=channel, category=category , overwrite=overwrite)
await createdchannel.set_permissions(ctx.author, overwrite=overwrite2)```
this can be one line
how do i make subcommands such as ,settings add {param1} {param2}
subcommand such as "add"
ok
you need a commands.group() decorator
i dont know anything about that
yes hikari suggest me
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
alright ty
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local
variable 'channel' referenced before assignment
error says it all
finaly gets error rofl
cuz of u this error occure
shouldn't be because of me, I never said to use a bad variable name like channel
change the varaible name
yeah, of ALL the variables in that function ofc
i forgot to change variable
yeah, only the if statement needs a fix and you're done
not my fault
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create_voice_channel() got an unexpected keyword argument 'overwrite'
``` overwite didnt work
it's overwrites
ok..
if channelname not equal to "username - user discriminator":
then send message and return
RecursionError: maximum recursion depth exceeded
I'm getting this in return
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: overwrites parameter expects a dict.
+1
well, you only need a group decorator for the main command
?
@bot.group()
async def lf(ctx):
if ctx.invoked_subcommand is None:
await ctx.send_help(ctx.command)
@lf.command()
async def np(ctx, user=None):
await np(user)
.
current attempt?
!tags
โข
ยป args-kwargs
ยป async-await
ยป blocking
ยป botvar
ยป class
ยป classmethod
ยป codeblock
ยป comparison
ยป contribute
ยป customchecks
ยป customcooldown
ยป customhelp
ยป decorators
ยป defaultdict
<h1>hi</h1>
yes
no
I want to see it, it's not a yes no question
ok
!source tags
Show all known tags, a single tag, or run a subcommand.
else:
for vcchannelname in vclist:
current_vc = disnake.utils.get(ctx.guild.voice_channels, name=vcchannelname)
if not current_vc:
createdchannel = await ctx.guild.create_voice_channel(name=vcchannelname, category=category , overwrites=overwrite)
await createdchannel.set_permissions(ctx.author, overwrites=overwrite2)
ownvc.append(ctx.author.id)
messageembed = disnake.Embed(title=f"Created a Private voice {vcchannelname}",description="use : `!prvc modify`",color=green,timestamp=datetime.utcnow())
await ctx.reply(embed=messageembed)
```'
your np function doesn't make any sense ofc
overwrites requires a dictionary datatype
its calling a command that i have created before
where did you define overwrite
..
well, then change the function name of your subcommand at least, it's shadowing
huh?
i was not using dict for that/??~?~/
well, you should OFC
lol
overwrite = disnake.PermissionOverwrite()
overwrite.connect = False
working tho
nope, not anymore
ok...
remove the overwrite connect
oh why oh why-
ok
!d disnake.abc.GuildChannel.overwrites
property overwrites: Dict[Union[Role, Member], PermissionOverwrite]```
Returns all of the channelโs overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role") or a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://docs.disnake.dev/en/latest/api.html#disnake.PermissionOverwrite "disnake.PermissionOverwrite").
removed
why don't you compare the channel name?

@bot.group()
async def lf(ctx):
if ctx.invoked_subcommand is None:
await ctx.send_help(ctx.command)
@lf.command()
async def np(ctx, user=None):
await nowplaying(user)
AttributeError: 'str' object has no attribute 'author'
why isnt it getting ctx.author
Bye ill come tmrw
you have a full error traceback
Error?
error isnt in these lines, send full traceback
Could you try to explain the problem?
Nothing im here in for more than 4 hours
i fixed it, i needed to change nowplaying(ctx, user)
I want to study my exam are close 10 days after my exams and i didnt learned anything
seems like your if statement was false then
you should better read this code
#discord-bots message
it implements the overwrites the way YOU SHOULD
above the if, print ch.name and f"{interaction.user.name}-{interaction.user.discriminator}"
you can check for yourself
I know what the problem is tho, it has to do with casing
Got it
Ill add tmrw im done for now
Thankd for handling me im a trolling/irritating guy
Thanks for help
just fix your variable names and your questions and you should be golden when asking questions
Sniper helped me a lot today
sniper too good
Yes
if you just want the fix:
it's interaction.user.name.lower()
Epic fail
that'll fix it all
since channel names don't have casing, you were basically comparing
shit-151 with ShiT-151
which isn't the same ofc
correct
good luck
you're not taking a lot of stuff into account tho, you'll stumble upon some problems in the future
like: what if the user changes his username? he'll be able to keep on creating channels and his previous channel will never be deleted, ...
I dont want to lewrn about sql rn can i copy the code from somewhere
you should go to #databases for a basic understanding
yeah, but you'd have to be online for that etc, that's still a manual fix
also, if he does it once, you won't notice and the channel will just stay there or whatever
You could make a countdown, which deleted it x seconds / minutes after creation, the bot could optionally check if there's still movement in the channel and extend the deletion period
but that's just me brainstorming
just know that anything is possible and thinking about all possible outcomes is like 90% of the work
Use MongoDB as an alternative, using SQL drivers are still recommended though
*aiosqlite or asyncpg => async wrappers of sqlite and postgres
mongo might be a last resort
aiosqlite/asyncpg still requires you to use the SQL language
true, I'm talking about best case scenario's
How to turn on community mode without audit record
@boreal ravine i have a doubt bro
Help pls
im trying to make the bot invoke a command on a button interaction
this is the button
@button(emoji="\u23F9")
async def stop_command(self,button: button, interaction: disnake.MessageInteraction):
"""Stop button."""
ctx = await interaction.bot.get_context(interaction.message)
ctx.command = interaction.bot.get_command("stop")
await interaction.bot.invoke(ctx)
the error i get
ctx = await interaction.bot.get_context(interaction.message)
AttributeError: 'NoneType' object has no attribute 'get_context'
what i tried:
print(interaction.bot)
# outputs: None
print(dir(interaction))
#outputs:
"""
['__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_cs_channel', '_cs_followup', '_cs_me', '_cs_response', '_from_data', '_original_message', '_permissions', '_session', '_state', 'application_id', 'author', 'bot', 'channel', 'channel_id',
'client', 'component', 'created_at', 'data', 'delete_original_message', 'edit_original_message', 'followup', 'guild', 'guild_id', 'id', 'me', 'message', 'original_message', 'permissions', 'response', 'send', 'token', 'type', 'user', 'values',
'version']
"""
additional info : I'm using disnake version: 2.1.0 on windows
update disnake
so old
The latest is 2.4.0
any code breaking changes?
you can't
no
ight
@boreal ravine i too knew it, btw some body changed my perception, global occult made a tool and he literally created a lots of community channels without any audit records
Howww??????
How did he do it, discord bug?
.
๐คทโโ๏ธ
@boreal ravine i think he made request with any other id
And due to bug it got create on anogher guild
how can I do a cooldown for an on_message event response?
yup that was the issue thanks
exact use case?
a role ping triggers a command
if I use ctx.invoke on a on_message message, does the cooldown for the command apply?
checks and error handlers will not run either
not sure if the cooldown does something
also converters won't trigger
concrete use case?
you want to run sync functions async?
No i want to use it like - async with taskpool(5_000) as pool:
Await pool.put(my def function) @potent spear
Will it work?
for what use tho?
@potent spear i need to to take some commands and combine them together
Anybody got the docs or api for coding discord gui i cant seem to find it on google
you can put all the commands in a list and then use "gather"
The gui is included in there?
yeah, it's a time waster
discord gui? wdym? you want to check out the CSS of the front-end?
@potent spear no i need to use taskpool for fast loop
https://docs.python.org/3/library/asyncio-task.html
can perfectly work with asyncio.gather
as long as your created tasks are all in there
@potent spear using taskio
@potent spear ok simply tell me i dont want loop but how do i call any async function
async def shit(...):
# async stuff
async def other_shit(...)
await shit(...)```
what're you asking? how to make a command?
I know how to btw dont know how to call async function
by using await <function_name>(args, kwargs)
no
in def, you need to use run_in_executor
I need that only
.
Cant i use target thread?
@potent spear ok leave this
I need to know another thing
import asyncio
async def shit(...):
#async stuff
def sync_shit(..):
loop = asyncio.get_event_loop()
loop.run_until_complete(shit(...))```
@potent spear how to make my bot check everyone's sttaus at regular intervals automatically?
by using a task loop
Ok
@potent spear example?
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
@slate swan did u block me?
click on the link, you will get an example
Ok
https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#recipes
pay attention, this is in a cog! it doesn't have to be per se
no, my dms are now closed.
Ok
@slate swan ok, what to write in loop? Async def func or wott
or just normally
Put code
see the example sniperglitcherz sent
for ctx.invoke, if I have a command
async def example(ctx, member : disnake.Member):
pass```
and i have an on_message event
```py
async def on_message(message):
if message.content == 'somethinng':
await ctx.invoke(bot.get_command('example', member=message.author)```?
@slate swan can we use taskpool(10_000)?
Hello, what can I do about AttributeError: 'NoneType' object has no attribute 'clone' error?
is replit down for anyone else rn
show code, and full traceback
@maiden fable would you happen to know
!d discord.ext.commands.Bot.get_context
await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
if possible show json file structure aswell
Use this for the ctx arg
ah okay also how do I put cooldown for it?
Idrk tbh... Why will u want to do that thing tho
because a role mention triggers a command
!d discord.ext.commands.Command.is_on_cooldown
is_on_cooldown(ctx)```
Checks whether the command is currently on cooldown.
wtf?
I can use this?
u didn't install those
on the command object? why not
it'll apply right?
and next restart vs code
?
nvm nvm
Ah okay
SyncWarning: Failed to overwrite commands in <Guild=123123123123> due to 400 Bad Request (error code: 50035): Invalid Form Body
Why does it occur?
you probably have some incorrect guild ID somewhere lol
Only possible wrong place must be here, but it's correct..
print it to be sure...
?
python -m
guild_id should be int. Can you make sure it is?
I recently decided to make a database wrapper for my bot for the sake of cleanliness, but it keeps inserting NULL when I change my prefix
This is insert_prefix
async def insert_prefix(self, guild_id: int, prefix: str):
"""Called only while executing update_prefix"""
await self.db.execute(
"INSERT INTO prefixes (guild_id, prefix) VALUES (?1, ?2)",
[guild_id, prefix],
)
return await self.db.commit()```
"guild_id": 943525427652210768,
is it going be a verified bot?
or is it personal one
Also, please don't call a bot client, for everyone's sake
so u want it to be published?
who's doing that?
oh sink
what do you mean?
umm like
But it's not gonna fix the problem so idc xd
public ok
yeah
mongo ?
aiosqlite
or sql
okk
I can see the guild id being 123123...
Oh i just spammed random nr's to hide if for no reason
um u dont wanna know the guild id do u
someone know what do?
actually follow up question, how will it know when to be able to invoke again
I tried with my insert_prefix and update_prefix methods just to make sure, and I believe it is my insert_prefix method
Wym
like the command I want to invoke on an on_message event has a cooldown
Yea
how do I apply the cooldown exactly?
So u want to know when the command will be ready to be used again?
May some driop menu be the cause of this error?
yeah basically
update your disnake version
to atleast 2.4.0
Thanks bud
!d discord.ext.commands.Command.get_cooldown_retry_after
get_cooldown_retry_after(ctx)```
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
ah I can asyncio.sleep that time
Hello, I asked this question before but can I use absolute path to map to a different env than the one in the folder?
ofc...
/ starts on root...
some?
wut problem
dont works?
error says it all or run as admin...
ok
Can I see an example on how todo it with my setup?py load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') intents = discord.Intents.default() intents.members = True
what editor
do you have python3?
i install 3.10.2 10 minutes ago
try useing python3 - m pip install --upgrade pip
Try python -m ensurepip --upgrade
Seems like it worked?
You already have discord.py installed
ok
@potent spear
I personally use a config.py file
and I just import config
then I can access variables via config.TOKEN etc
how do i use bot.get_context?
why do you need it?
it's var = await bot.get_context(message) right?
for a on_message event
you want to invoke another command in on_message?
yes
have you looked at the docs before?
for?
questions like yours
@bot.command()
@commands.cooldown(1,20,commands.BucketType.member)
async def test(ctx):
await ctx.send('this is a test on_message command invokation')
@bot.listen()
async def on_message(message):
ctx = await bot.get_context(message)
if message.content == 'test':
await ctx.invoke(bot.get_command('test'))
else:
return
the @commands.cooldown for the test command doesn't work, I guess doing ctx.invoke ignores cooldown how do I prevent this?
๐ณ
Bruv
no no I want to make it when I ping a role, a command is triggered
I know...
๐ณ
well i need it to be that way so is it possible just to fix the way i have it setup?
If you really need to use on_message, either use @bot.event and then await bot.process_commands(), or use @bot.listen()
In this example, you DONT NEED to use on_message, as the default bot processes commands by default
Hello, what can I do about this error? TypeError: on_ready() missing 1 required positional argument: 'ctx'
do you know how to appply cooldown?
why don't you make it a requirement for the user to put the env file in the project folder?
It happens when I have this here
because i already have one in the project folder
Iirc as the bot owner you bypass cooldowns
wrong arguments, on_ready doesn't have any
an even in general doesn't have ctx
what...no
No idea, I don't invoke commands via events
okay, thanks
yes
Yes, remove on_message event and it'll work
no that's not what I want
Should work*
I have 2 different bots in one folder because they do close to the same thing but not quite
@commands.cooldown(1,<cooldown seconds>,commands.BucketType.user)
Sniper stop take some rest
@spring flax
you just changed member to user?
no
Woah
someday
I already had cooldown deco @gaunt ice
@potent spear
I don't encourage spam, remove that
Do discord have an auto spam or we need to make it
well, you can have 2 different config file names
we need to make it
Ok..
Discord bans some links by itself
ok i have never done your way so can you explain how to do it?
we can use on_message event
I'm not experienced with multiple .env files, so I can't say...
Do disnake support timeouts
i am meaning with your config.py file
As it is easy mute
best thing I suggest you to do is OR have multiple folders for different bots
OR have all your variables in 1 env file
have all variables in 1 env
it's as simple as
#main.py
import config
print(f"my token is {config.TOKEN}")
#config.py
SHIT = True
TOKEN = "515151"
Shit = True
what is the "shit = True' for?
just some random extra variable
Lol
ok like discord intents
Or some lists
no, just skip the shit
No
is it a cog or same folder as the main file
ok
else you'd have to use another import notation, that's what relative imports are
you just import the whole file with all variables etc...
Hey everybody:) I started a discord bot using my own wrapper for nasa api, and i need somebody to just test out the 2 commands i have as of now and review it
i would be greatful
in the main file, you should
import config
then use any variable by
config.TOKEN or whatever
ok i fixed it i forgot the ' ' and how do i make the client.run(TOKEN)
with the config file?
nvm
client.run(config.TOKEN) ofc
that's useless and you know it
Check the pins
is that replit?
I mean, no hate, but if it is, your token isnt safe anyways
lmao
okay, I'll go cry now
ok.........................
she's kidding dw
I've had enough of mine already today here, so ig i'll pass
now i wish i never said that
except:
pass
waits for the message to fit in the context
U do know that it is the MOST best stupidest thing someone can do, right?
๐
Light mode in discord
used to use that
Lol I removed it but they are fun lol
I use light and dark discord at the same time
Replit is better than light vs code
It is trash than vscode
And I mean light mode vs code
Light vs code is worst than a jumpscare
No
I mean, you have 2 people test the bot already
imagine ur coding at night someone changed to light mode meanwhile : ๐ต
It is 9 am dude
def not me.
Did that
sad(True) #ur pfp
I got a question, I created a server, added a bot and then suddenly I can't interact with any of my servers, e.g. if I right-click one of them, it just keeps loading forever, even after kicking the bot. (he had no abilities, 0 code) I also can't delete my server because when I want to go the ther server settings it just crashes
Toatally cursed
wtf is that syntax-
Lol nvmd
i dont think so :p
its a discord bug, restart discord or check your internet connection, also I like the fact that you gave pronouns to your bot, welcome, no need of thanks
but it is true
who
no need of thanks.
you and yourself
lmao good one
Mushrrom guy in chat
lol
dyno guy in chat
!ot in discord bot chat
Hello there
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
sup. its off topic so
await ctx.send("no ot guys")
#ot2-never-nesterโs-nightmare go there ||maybe I'll be there too||
Cooking with alexa
restarted almost everything, is there a way to just easily repair discord?
cooking with tf
re-install
Toatally cursed by the bot
its alright, try restarting your device, plus its ot
the bot itself is cursed, I'm sure you could create a better one
oki
nvm I'll just switch to canary bc it works much smoother lol
....
def -> definately
but you "maked" "an" function
we makeding functions?
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
๐
you're welcome (:
Huh 2 pings
!d def
8.7. Function definitions
A function definition defines a user-defined function object (see section The standard type hierarchy):
not ot ยฏ\_(ใ)_/ยฏ
Hunter, you're really helpful and the only one of your kind
I know I am unique
i don't know if this is under discord.py
But yeah
dat = {'embeds':
[
{
'title': 'emoji []',
'description': ':KekDoge:'
}
]
}
I tried posting this in discord rest api
It gave me {'embeds': ['0']}
and?
why u doing this tho
@sweet geyser @maiden fable this isnt the right channel
so the history?
Anyone have a good hosting platform? our bot keeps having dataloss, it's not good especially since it's verified, dm me some solutions :/
Who says so
me
This is about discord bots?
I already tried using replit
no
U got a credit card? If yes, then just get an Oracle Free VPS
lol
Yea it is
if no?
it isnt
Heroku is the only option but its kinda not made for bots
Then.... u r stuck
๐
No not channel's history
Then
Ah create_message?
{'embeds': ['0']}
Yea
r = requests.post("https://discord.com/api/channels/channel.id/messages", headers=header, data=dat)
the embeds must be a list of Embed objects
It is
Not 0
here
requests
Yea i k
We're gonna try a VPS, idk if it'll work or not ๐
Cool
So what is the issue?
It doesn't send anything
And when i tried .json()
{'embeds': ['0']}
Mind showing me the whole code after removing the token?
This came up
i wanna embed videos to embeds
Yea sure
Don't remove anything else except the token itself
There are many unused imports since i changed stuff
Ignore the imports
I just want the header, dat dict and the function where u r calling the requests.post
import requests
import json
import time
header = {"Authorization": "Bot <token>"}
r = requests.get("https://discord.com/api/guilds/920267012936754856", headers=header)
emj = []
for i in r.json()["emojis"]:
if i["animated"]:
emj.append("<a:" + i["name"] + ":" + i["id"] + ">")
else:
emj.append("<:" + i["name"] + ":" + i["id"] + ">")
dat = {
'embeds':
[
{
'title': 'emoji []',
'description': ':KekDoge:'
}
]
}
r = requests.post("https://discord.com/api/channels/921665743797420063/messages", headers=header, data=dat)
print(r.json())
Here
and token is the original token, right?
Yea
why don't you use an existing API wrapper?
Its not a self bot
Well its was just for fun
Not like i am gonna make an entire api
there are already complete existing ones, that would be a waste indeed
Nvm i am dumb as hell
Fixed it?
Nope same issue
I removed the old request
Since i didn't use it
Yet the issue percists
dat = {
'embeds':
[
{
'title': 'emoji []',
'description': ':KekDoge:'
}
]
}
re = requests.post("https://discord.com/api/channels/921365743797420063/messages", headers=header, data=dat)
print(re.json())
!d requests.post
requests.post(url, data=None, json=None, **kwargs)```
Sends a POST request.
It really did
i changed data= to json=
Hmm cool then
Thanks a lot
you should also use the discord api version 9, since not specifying it will use v6, which is deprecated
https://discord.com/api/v{version_number}
bump, possible?
Not possible with bots
awh, alr
yea i just did
i am using v8
The only type of embed you can send with a bot is RICH
Finished procrastinating?
No
;-; why
that's quite sad
Because last time I did a lot of stuff in one day my fingers died, Iโm still recovering ๐
U do know that u have until the 28th of Feb to complete the wrapper with all the latest stuff, right? ๐
!pypi disnake
rin ๐
What where did the deadline come from
its not even done yet
From Hunter, a min ago
we should start suggesting once its done!

u know....
||u r correct tbh||
:P
Why
There is no way Iโll be done by then
I am sure Nova will be more than happy to help u complete the core of the lib ๐
Not gonna let him
Why
Lmao they both working together bruv
I better not ping him, imagine me pinging the wrong one
jeez there are 8 nova's
only
The default is v9, according to disnake dev(s)
no nvm
Lmao
I can bet there are more
Discord takes time to load members
I donโt like his code ๐
Lmao
Neither
Or I will make PRs with my ugly code style ๐
๐๏ธ๐๐๏ธ
@pliant gulch mind helping with something?
Might have time
I have
@bot.event
async def on_message(message):
ctx = await bot.get_context(message)
if message.content == 'test':
await ctx.invoke(bot.get_command('test'))
else:
return
This doesn't apply the cooldown to the command when test is written. How do i make it have the cooldown? I was told to do bot.invoke but I'm not sure how to
I can make them uglier
Didn't I tell u tho
You told to use bot.invoke?
I know, but I don't want andy procrastinating more due to headache after reading our code
!d discord.ext.commands.Command.get_cooldown_retry_after
get_cooldown_retry_after(ctx)```
Retrieves the amount of seconds before this command can be tried again.
New in version 1.4.
Told u this too
I don't think itll work
xD
Imagine the code full of uwu's
Huh?
and hunters
Idk about that
invoke ignores cooldowns, use process_commands
With this code #discord-bots message
I can keep writing test and it'll keep invoking the command
wdym?
Yea but I just told u first to use is_on_cooldown and then use get_cooldown_retry_after if it is on cooldown
Process commands will actually call the command properly with cooldowns
He wants to invoke a single command on mention iirc
Instead of getting and invoking, just use that
I can have it triggered with a normal message? Like test invoke ?test
You can strip off the prefix with string slicing
Whoops wrong reply
Haha
I'm a bit confused here lol
guys does anyone know why my bot does not send a message when i run a commmand
mind giving an example?
Ok what is on channel create?
does anyone know basic python here?
on_channel.create????
i don't have an on_message event
yes
@maiden fable Iโm out of time so you should help, but really just slice the prefix off with string slicing
why
because there is a problem in either yr code or discord perms
no sorry, nobody in the server knows about python, what is that though?
Lmao
yeah, this is a python server, why'd anyone know python
fools
U r rarely sarcastic
hunter can ya help?
Strange, Iโm checking via the discord docs itselfโฆ maybe they havenโt updated yet?
raven?
Sure, ig
where can i find all the def?
man
let me explain what I want
Yups
bru
the one whom am replying to rn
what do you mean?
won't be able to help u without ur code bruv
rofl
U forgot ::
I need to know what on_channel_create is
If I write test, I want it to invoke a command and the command checks and cooldown have applied to when that command is run
why not just pass in an empty string to command_prefix?
command_prefix=["", "?"]
import disnake
from disnake.ext import commands
bot = commands.Bot(
command_prefix="--", intents=disnake.Intents.all(), help_commmand=None
)
@bot.event
async def on_ready():
print(bot.latency * 1000)
class coolHelpCommand(commands.MinimalHelpCommand):
def __init__(self):
super().__init__(no_category="Help")
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
Helpemby = disnake.Embed(description=f"{page}", color=0xCD08FF)
await destination.send(embed=Helpemby)
bot.help_command = coolHelpCommand()
def loadShit():
extensions = ["utility"]
for i in extensions:
bot.load_extension(i)
loadShit()
bot.run("token")
for some reason my bot doesnt send a message when i type --help
no...why
that seems like a super bad idea
tbh it doesnt seem like the best idea
empty string as a prefix...
you can just invoke a command with a context object via get_context
if its only certain words
I mean, u r just wasting extra resources to do the same thing as an empty string prefix would do
why help command none first?
What is on channel create?
When a member pings a role, I want the bot to invoke a command
!d discord.on_guild_channel_create
d!on channel create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
removing it doesnt do anything or affect anythign
i was tryna get help and someone told me to do that
weird
you would make an on_message event and check for message.role_mentions
and then use get_context
yeah got that part
and invoke
!d discord.on_channel_create does not exist?
No documentation found for the requested symbol.
this is my cog btw:
import disnake
import string, random
from disnake.ext import commands
class utility(commands.Cog, name="Utility"):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_role("staff")
@commands.guild_only()
async def modnick(self, ctx, member: disnake.Member):
new_nick = "Moderated Nickname "
for i in range(5):
new_nick += random.choice(string.punctuation)
await member.edit(nick=new_nick)
await ctx.send(
f"Changed {member.mention}'s nick to `{new_nick}` | **{member.id}**"
)
new_nick = "Moderated Nickname "
def setup(bot):
bot.add_cog(utility(bot))
th
!d discord.on_guild_channel_create is what u r looking for
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
await bot.get_context(message)
but what does this do and how does it invoke a specific command? @manic wing
try printing bot.commands
{<disnake.ext.commands.help._HelpCommandImpl object at 0x103c6e710>, <disnake.ext.commands.core.Command object at 0x103c6e530>}
ctx = await bot.get_context(message) and then you would do await ctx.invoke(command) where command is the instance of your comand
this is what i got lmfao
So it did register the cmd
it just doesnt send messag
Caeden drunk
DUDE I have send the docs for channel create like 3 times now
guild_channel
but ctx.invoke ignores cooldowns
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
cooldowns are whack af and i wouldnt bother fucking with em
Keep it up, once more
!d discord.ext.commands.MinimalHelpCommand.send_pages
await send_pages()```
A helper utility to send the page output from [`paginator`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MinimalHelpCommand.paginator "discord.ext.commands.MinimalHelpCommand.paginator") to the destination.
DUDE
huh
i was told to use bot.invoke
!d discord.on_guild_channel_update
discord.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
ARGHHHHHHHHHHHH WHY U DOING THIS
Caeden.exe is corrupted
hunter will u help me or will i have to figure this out
"darling", indeed hunter's everyone's darling
yeah hunter, stop moaning just help
why not use commands.HelpCommand
Stop. It.
whats the problem with using commands.MinimalHelpCommand
I don't think i am doing this right py @commands.Cog.listener() async def on_guild_channel_create(self,ctx): ctx.channel.send('place holder')
I am already sleepy, please don't piss me off
you asked so nicely so i must comply
ctx argument uwu
anyways #discord-bots message
ctx.channel.send(...)
no problem, I just know how to use the other one properly haha
self, channel
await
I'm going to cry
Take me with youuu
it takes channel, hence why you dont do channel.channel
everything __looks__wrong, usually on an event that starts with on_ it should have a before after or something, the indents are wrong and i think you await sending a message
ps you await
indents are fine
and why would there be a before lol
its a channel being created
i have never played with this stuff so i have no expericence
tf is the before gonna be
None??
i am meaning with the on channel create stuff
not really they make no sense to me
ok do i pass it ctx or do i just pass self and channel
self, channel
because it takes channel; not ctx
think about it, where would ctx come from? no command is being invoked...
so you would do await channel.send('wow...')
Can someone tell what's is different between guild.fatch_ban() and guild.bans()
just bumping this again
ctx....
guild.bans returns a list of the bans fetch_ban returns a specific one
just bumping this
what argument fatch ban takes?
its fetch dude
make it error when a command given is not a bot command?
user (abc.Snowflake) โ The user to get ban information from.
async def help(ctx, command_name):
command = bot.get_command(command_name)
if command:
#command eists
else:
#command doesn't exist
frick
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
em = discord.Embed(title = 'Ticket Format' description = 'This is the ticket format' \n 'Username: (Your Roblox User)' \n 'Claiming: (What your claiming)' \n 'Invites: (Number of invites that you are using)' \n 'Proof: (Your invite count using -invites)')
await channel.send(embed= Em)``` invaild syntax
u forgot commas and the \n isn't inside the quotes
wait where does the commas go?
after every kwarg...
To convert matplotlib objects(py module which give graph) and display them as discord embeds in jpeg form
how can i do that ?
Are there any changes that I have to make to write slash commands?
what library?
disnake
If it's Disnake just updating it will make the code which now shows error work again
pip install -U disnake
I haven't used matplotlib before, but if you're getting a JPEG/PNG file outputted from it, you can just give its URL to a discord Embed.
I'm already using disnake and I'm not getting any errors either. But my command doesn't show up to the user when they type /
How would i make a command for my bot so if i ran the command it would send a message though a webhook of what i just typed? like for say &webhook Hello there this is a test message and it sends it though the webhook to what ever server it is
it usually takes an hr for global slash commands to appear
that why i don't use slash commands
I don't wanna use them too
then don't
You can specify guild ids for testing
how can i simply let my bot delete a command response if the command is used a 2nd time? so the command is used - response from bot - command is used 2nd time - 2nd response and deletes 1st response
true
ashley would you know how to do this
But there's this thing for which I have to use Modals for, and as far as I understand from reading the disnake Github they only work with slash commands.
oh i see
Yeah I do
can you explain how to do it?
Is it just me or the example about modals with dpy is just too damn neat? https://gist.github.com/JeyyGit/2618ca611a2ac2955d2d193b68c214b7
Rough implementation of modal in discord.py 2. GitHub Gist: instantly share code, notes, and snippets.
Imagine dpy with this type of code quality
okkay thanku and yes i'm getting jpeg
can you explain how to do it or point me to docs where i can attempt?
