#discord-bots
1 messages · Page 986 of 1
I agree
lmao
enough to get replit blacklisted
yeah maybe
they stopped accepting replit urls for a while
Hey, I know a free host
oh
hey, uhhhh, I work on discord.py v2 and wanna know if someone want to work with me
When collaborating people are interested in.
- Your skill level
- GitHub
- Hosting
- What
Could you delete this? Since I don't think this is something friendly.
How to set cooldowns for commands
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
add @commands.cooldown(...)
@junior verge @maiden fable @sick birch @vocal plover thx for help 🫀
and sorry for ping
good night
Robin loves to get pinged dw
What's bucket type
Type of cooldown
the type of cooldown you want to implement
!d discord.ext.commands.BucketType
class discord.ext.commands.BucketType```
Specifies a type of bucket for, e.g. a cooldown.
Oh
Like, if its commands.BucketType.user is a cooldown to each user, if it is commands.BucketType.channel is a cooldown to the channel and if it is commands.BucketType.guild is a cooldown to the guild
Thank you
I get it now
Anyone up for a challenge? ||aka my problem lol||
@bot.event
@event.cooldown(1, 15, event.BucketType.user)```
Hello my code says event isn’t defined when it clearly is
It's just BucketType.user
Not event.BucketType.user
Ok
from discord.ext.commands import BucketType this for the next error
I already did that next error is event not defined
Oh lol you are doing this
lemme grab the docs
It's just cooldown not event
You also can't apply a cooldown on an event
what is your problem man ?
So it’s not possible
Is there another way to do it
Got Pycharm error Unnecessary non-capturing group '(?:Overview:\s+)'
Using re (?:Overview:\s+)(?s:.)*(?=\WThread) ```py
Overview:
lorem ipsum text etc
should still catch here
Thread until here catching the word thread
Yeah I think youtube_dl is not welcome in that server..
Not that i know of.
oh lemme see
this is the error on your terminal ?
currently have it like this but pycharm is saying it's wrong.
Pycharm warn.
what
I uh don't remember helping
Robin you got experience with re groups?
this is the first time it shows it ?
Yeah I just made the reg
very strange... I never used pycharm so Im scared i won’t be able to help you that much but I will do my best...
I tried removing the group but then the re won't match for some reason.
why does that warn appeared ?
Since it doesn't want me to group (?:Overview:\s+)(?s:.)*(?=\WThread)
Yeah it is
re.findall(r"(?:Overview:\s+)(?s:.)*(?=\WThread)", self._desc)
self._desc == the lorem text or in this case the test case.
\u00bb : RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK - »
Im French I don’t know how we call it in English 😅
they're quotes in french
fr?
ok thanks 🙏🏻
yes, "fr"

Hard to please per usual
You know how to fix my issue? :3
Anyone coding on Pycharm to help him ?
let's see it
yep
how can i play an in-memory ogg file?
@pure sparrow I fixed it
I removed the group then used a single search that returns a re object then cast to string ```py
str(re.search(r"(Overview:\s+)(?s:.)*(?=\WThread)", self._desc))
awesome ! great job how have you done ?
Oh... very nice
why would you convert a match object to str
Since __str__ will be the matched part anyways.
True but it returns the same.
>>> str(re.search("uwu", "amoguwusu"))
"<re.Match object; span=(4, 7), match='uwu'>"
oh yeah lol
np
I'm extracting data from a website but it's a literal hell since it's pretty inconsistent :(
I did but there are whole parts of text like the desc that contains multiple parts of data.
Or even text outside tags
whatever suits you best
I have a combination of both rn.
hey i was wondering if there is a way for me to search for something through my discord bot by adding what i want to search after the command instead of sending a separate message of what i want to search up.
ie;
what i currently have:
me: ..search
discordbot: what do you want to search?
me: google
what i want to do:
me: ..search google
discordbot: desired search results
just use an argument
and if you want to search for something in google just use their api
sorry that was just an example but im just curious if its possible to make the command one message instead of two
yes an argument after the context argument just add another one which if you just want the word of the platform you want to search with a positional argument would do fine.
oh ok i think i understand what you mean. will test to see if i understood what u said correctly and then check back here again if i need further help. ty! ❤️
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see !tags decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
yw💜
@commands.command(name="leave",help="Leaves the server")
@commands.is_owner()
async def leave(self, ctx, *, guild_name):
guild = discord.utils.get(self.client.guilds, name=guild_name)
if guild is None:
await ctx.send("I don't recognize that guild.")
return
await self.client.leave_guild(guild)
await ctx.send(f":ok_hand: Left guild: {guild.name} ({guild.id})")```
attribute error : bot has no attribute "leave_guild"```
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.delete "discord.Guild.delete").
i want the bot to leave the server when call the command
yes?
isn't this for a member to leave a guild
and i would recommend you just give a snowflake so then you could just get the guild with your bot instance so then you dont need to use utils which it iterates through all guilds
no
you cant leave a guild for a member, only ban/kick the member, the coroutine that has been given is for your bot
!d discord.ext.commands.Bot.get_guild | this uses dict.get which i think its a hash lookup im not sure as its average time comp is O(1) and its worse case is O(n)
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
but its still better than using utils as the bot class already has a method for it, yes you could use utils for names etc but you can just use a for loop but i still wouldnt recommend it
i hate how i close my mobile client on a thread and then when i open it again i get riderected to the default guild channel smh
Remove the ()
does anyone have an article or something that i can look at that shows how to write slash commands for discord.py?
hello
it has examples
thx
i need help
with?
on discum code
sorry, we dont help with that wrapper here nor with self bots.
ah ok
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
how instant is syncing slash commands to a specific guild?
ask discord
ok
💀
but it sometimes takes a couple of seconds, depends on the library you're using
oh then mine just isnt syncing for some reason
nvm im being an idiot
nope i literally just can't do slash commands
pog
Hello, can I somehow use the bot to download all the images that are in the chat? (only images in the chat, no text)
Or if there is already such a bot, its name please
nextcord !
can SlashOption choices be a function which return a dict ?
yeah its nice to have that
is anyone able to give me some pointers on doing slash commands with discord.py as they don't seem to sync to my server at all
Sync as in register?
yeah basically they don't show up
Have you invited the bot to your guild with the application.commands scope?
You bot requires this scope to be enabled in order to even register commands
yes i forgot that at first but it has that now
You should probably show the code in question & any errors you get
!paste
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.
thats it thx
bear in mind this code is gonna look bad because i just couldn't figure it out and started trying random stuff
is it possible to only allow people with a certain role to use my bot
@pliant gulch sorry for the ping but if you take a look at that you will see basically what i have so far in regards to slash commands
ok then.....
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
anyone willing to actually help me with slash commands without just disappearing?
if this is the code u have, from what i've been shown u dont need to explicitly create a tree because commands.Bot already comes with one. Plus u have to sync the commands
ok so how exactly am i syncing the command is it through putting this?
await tree.sync(guild=discord.Object(id=MY_GUILD_ID))
@discord.ext.commands.has_role('Machiavelli')
so i typed this thinking that only the people with the role Machiavelli would be able to use the bot but still anyone is able to use it
im v new so please excuse any absolutely stupid mistakes
it says how to do that on here https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
well first u dont need 2 clients. u only need 1
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
2: No need to manually create a tree because commands.Bot already comes with one. So u can create ur slash command like so
@bot.tree.command(name="...", description="...", guild=discord.Object(id=...))
async def test(inter: discord.Interaction):
...
- Put the sync in
on_ready
async def on_ready():
await bot.tree.sync(guild=discord.Object(id=...))
Now i've been told put the sync in on_ready, ive been told to not do it in on_ready, idk but it works for me
oh thank you
Hello, is anyone available that can help a beginner?
I have this code:
elif message.content == "!list": f = open('output.rtf', 'w') movies = plex.library.section('Movies') for video in movies.all(): await message.channel.send(video.title)
that sends a message for each movie I have on my plex server. However, I'd like it to send as one message. It currently sends one message per movie, which at 800 movies takes forever. Is there a way for it to send as one message? I have tried outputting it to a txt file and sending that file, but even though the file is complete, once it is sent through discord the list is incomplete up to the same movie every time.
Along with this, i start the bot with a coroutine
async def load_and_start():
await bot.load_extension("cogs.test")
await bot.start("REDACTED")
asyncio.run(load_and_start())
But that's just me. Idk if thats a good way to do it or not, but it works
They tell u not to do it on_ready just to reduce the amount of api requests
Not any big change
Also u should use the async with bot: context manager to make sure the bot cleans up properly
i thought the context manager was only for using the loop?
idk if im blind but i cant see it on there sorry
ive tried googling it but cant find it
ok i got a slash command to work for me

now i just need to figure out how to do this with things other than message responses
wdym?
like banning etc
also an alternative to this:
if ctx.message.author.id == 473842262317596672:
im trying to make my discord bot private so nobody can add it to their servers but its coming up with, cannot add install fields on private application
anyone know the resolution for thi
im not sure what is meant by install fields
You could of simplified it to ctx.author.id
you can prevent people except you adding the bot to servers in the discord developer settings
thats what im trying to do now but im getting that error
well i can't for slash commands, at least not that i know of
it shouldn't be in your code
Oh is it slash commands?
no not in my code
on the site, im getting a red bar at the top
yeah i am trying to convert my code to slash commands now
what error?
"Cannot have install fields on a private application"
if you want people to not be able to use your bot use a global check
and you are just turning off the public bot setting?
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
yeah
i am not sure then
No it’s like a simpler try finally to close the bot
i have like no clue how to ban with slash commands at the moment
Like a normal command
turns out it was because i had an authorisation in app on, you have to have that setting set to none
yeah but how do you pass through the user?
get a Guild/Member object then ban them
Add a parameter to the slash command
Make an arguement type hinted to discord.Member
i don't know how to do that, literally anything to do with slash commands has literally just driven me mad
I don't understand why this won't work
embed.set_thumbnail(url=ctx.channel.guild.icon.url)
error
AttributeError: 'NoneType' object has no attribute 'url'
The guild doesn't have an icon
ctx.guild.icon_url
its .url???
it changed in newer versions
ohh
how can i restrict bot usage to only members with the bot role
sry ive asked this before but just bumping it
its on the documentation it shows how its done
could you explain this a bit more
how can i send a custom emoji from a different server that the bot is in? using disnake
are you still able to help me with this?
it would be nice if people just said they were going rather than saying nothing and disappearing
because then we are just waiting here thinking they could come back when we could be figuring out how to sort our code
member = ...
await member.ban()
``` or what moster said earlier.. ```py
async def slash_command(interaction: discord.Interaction, member: discord.Member):
await member.ban()
I see no reason why it would it not work
yeah it does ok
is there any way i can now just make it so the commands only work with my id because if i can get that done i am golden
basically an alternative to this if ctx.message.author.id == 473842262317596672:
i mean if anyone has any ideas please let me know
!d discord.ext.commands.is_owner use this decorator
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Youre using Disnake right?
is that a slash command or a normal one?
slash command
im not sure if it would work, but try using this
i have read the documentation on the @commands.has_role, but still not sure on what i need to put to implement this
i am pretty sure that won't since thats not formatted correctly for discord.py
@commands.has_role('Machiavelli')
so far i have that so that only people with that role can use my bot😂 not sure what else i would need to put
If hybrid commands it works
wdym thats an discord.py internal
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
how do u run a python discord bot on your computer using python? can someone help me?
ive read this but still not sure what i need to put for the function of that command for has_role
python/py <filename>.py is the most common way
i am not sure that would work either as i need it to run the command only if i trigger it and if i don't then it needs to tell them that they don't have permissions
if you are on a windows system you are likely to have py as your python namespace
are you doing the same as me? trying to add it so that only those with permissions can use the bot?
You need to make your own is_owner check yeah.
kinda
I recently got a new PC and my old pc had python installed on it and when someone made a discord bot for me they told me how to run it but now on my new pc i dont know how to re install python and i installed it using there website and added the PATH option but when ever I open the bot file it automatically closes
right click> open with IDLE> select IDLE
(me who does ctrl+shift+f10 on pycharm) 
only options are python and microsoft store
Still the same except yours is handled by your IDE
well then you know what to choose..
python automatically closes when I press it
i don't think running a 2 gb application just to run a single file is efficient
Run it from your terminal to see any errors or prints
1 gb
clearly said, python/py
Ah, is it py on windows?
oh maybe
Im on windows, ye
Cool, try py <filename>.py in that case
Correct me if I'm wrong, I'm only familiar with the python3 ... way to do it
they work same except for the namespace
Great, then just use py instead of python3
But whoever gave you that discord bot should've probably dockerized it
@slate swan
So, you run the script, it closes immediately, and you got this from someone else... is this someone else a trustworthy person?
yes they are perfectly trustworthy i had the bot for over a year and would run it but just got a new laptop and am trying to re run it on this laptop
navigate to the file's directory first, then use that command
or py "full path to file"
aight, just checking :)
huh.. what does that mean
Is the censored part elija
no it elias lol
Nice
its a hispanic name
It's just bot.py, not bot.py.py
ye i tried both of them
I was close
What happens when you run py bot.py?
I don't think it's all that important
I'm not saying it's important
are you in the same folder that your script is in?
Oh yeah that makes sense
im in command prompt
what i type
Where's your file located? Like what's the path?
done
Your prompt should change to
C:\Users\<username>\Downloads>
Yes?
Then you can run the command py bot.py
Looks like your person didn't tell you how to get all the dependencies
Did they provide any other files or just bot.py?
you either need to be in the same directory where the bot.py file is located
or need to provide the complete path to that file
We've got that issue solved
Oh its solved
Hey @inland shell!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
install discord.py first
py -m pip install discord.py
They probably should've provided you with a requirements.txt file
Or dockerized it which is the preferred way
But I'm going to assume the only dependency is discord.py
In which case so as Sarth said to get that installed
or poetry 🗿
And putting everything in one file isn't the best but it works I suppose
I sure hope you didn't pay that person to make you the bot
its done installing it
Most of the "bot" makers are like 5 bucks since people don't want to pay as much.
Explains why they're low quality 99% of the time
and i did pay the person to make the bot and it works really well for what I need it has 3rd party APIs interegated in it
100%
what now its done installing
how to do listener event in cog?
Oh that's unfortunate
commands.Cog.listener
Oh it works
@commands.Cog.listener()
Its opening the file and hosting the bot
Cool, looks like discord.py was the only dependency
Still don't really agree with the whole thing but it works
is there anyway to host it 24/7 without my computer
thx
Yeah, buy a VPS
Yeah that exists now doesn't it
Alright thanks for the help. Peace ✌️
wow, turns out i only need one on_error event for all cogs
Be careful about global error handlers
lol yeah
If you're not they'll end up eating all your errors
They are so **
lol
Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB
Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo
I've posted the actual loop itself and also the first function. any help would be greatly appreciated.
Could it be because im using aysnc tasks
Desperately need help trying to figure out why it isnt working now 😦
why wont my bot send emoji?
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
msg = ">:Error:966148323725705246< __**On cooldown**__, please try again in `{:.2f}s`".format(error.retry_after)
await ctx.send(msg)
That's not a default discord emoji
they should've made it ready out of the box, procfile, requirements.txt and all
Preferably with docker, yes
How does it net exist when it does exist....
i tried to make as easy to use as possible, just copy the repos, host and you're set
that isn't the full traceback
Yes it is
hm
@sick birch the emoji is from a server that the bot is in so it should work right?
I don't believe using >< is the right syntax for it
ik
but if i did it right then it would change it on discord to just :Error:
Do you know the error or no?
nope
Maybe try using bot.get_emoji()?
in cog? would it not be self.get_emoji()?
In a cog, it'd be self.bot.get_emoji()
ok
Given that you set self.bot = bot in your cog constructor
ye
wait what goes in the ()'s? name, id, what?
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
f-string not allowed
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
emoji = self.bot.get_emoji(id=966148323725705246)
msg = f"{emoji} __**On cooldown**__, please try again in `{:.2f}s`".format(error.retry_after)
await ctx.send(msg)
Either use all f strings or all .formats() dont mix and match
Hello?
msg = f"{emoji} __**On cooldown**__, please try again in `{round(error.retry_after, 2)}s`"
so lets say i wanted to do all .formats(), how would i do that with emoji?
do you have an SQL file viewer
ok
Not sure, never used formats and there's really no point in using them
should I ditch discord.py and move to another wrapper
If you want to, sure
thats the first time someone has liked the way im doing things lol
It uses positional characters like the ?, $ in SQL
also
Oh, misunderstanding. I meant there's no point in using .format() and you should use f-strings instead
bot now says this for cooldown message:
None On cooldown, please try again in 28.19s
no emoji
ik, i like f strings better
And you're sure the ID is a valid ID of the emoji?
yes
then why are you using .format?
bcs thats how osmeone told me to do cooldown messages
prob because he found the format of decimal online
actually i didnt, but idk about the person who told me
Well I wouldn't listen to that someone
yikes
ok 🙂
but then what do i do, the emoji wont work
Better to find best practices yourself because ones that come from other people may or may not be accurate
ok
How did you find the ID?
Yes
It isn't that bad of code for decimal format.
i have developer mode turned on and right clicked on the moji and clicked copy id
It shows the table exists
show
didn't the owner of discord.py say he's gonna stop working on it tho
Well it's back
Back again
There was a gist a while back on resuming development
Try putting a \ in front of the emoji,
@sick birch
oh, so he's continuing development?
kk
hm idk try asking in #databases
for example: !ducky_blurp
Right
sick, thanks
shows no id
:Error:
thats all it shows
yeah
Try clicking on the emoji from the selector first, then put a backslash before it
still nothing
do u wanna join the server and try it? bcs im not getting anywhere
XD
Can I combine an xp system and an afk system inside of 1 on_message event?
Sure
Well the databases are not letting me
you did something wrong..
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.
Okay I will use that to show my code
@sick birch ...
idk how but i think the id changed somehow? its the same emoji but the id is different now
Any help would be hugely appreciated guys, been stuck for months with this problem 😦
why
Yes
that wasn't a yes or no question
but still no work
Oh
I thought I needed to commit both of them
separately
@boreal ravine I removed it, still same error
try deleting your SQL file
And redoing them?
ima just use default emojis for now
redoing what
Don't I have to remake the sql files?
yes, but aiosqlite will do that for you automatically if it doesn't exist
yes
@boreal ravine Nope
same error?
yes
the last setattr overwrites the old attribute
why're you even using setattr anyways?
create multiple tables inside one file
Oh, is that how I have to do it
I cannot make different files in 1 on_ready statement?
possible, or just ```py
bot.afk_db = ...
bot.level_db = ...
you can
How can I do that then?
you just did in your code..
Okay, then why doesn't 1 of them register?
Hmm
I need to make both connect, can I do that in the setattr line?
How can my bot, count the messages of every server but if the command is used, it tells you how many messages were sent in that specific server? and not global? because currently it counts of every server and sends how many messages were sent in every server
Your bot is verified?
yes
Good Job
thanks
A dream of mine
Yea it was my dream too till i realized they removed the bot developer badge
Damn, why?
You'd need a database.
Some people sold their account with that badge or their bots were in fake servers
thanks
Wouldn't that be pretty slow, counting all messages?
Using .history()
Can someone please help me combine these 2 so they can both register
if so i screenshot
yes i am
is there way to fix this
Alright, open the shell and type kill 1 then everything should work again.
It is not a token 😐
it saying the same thing
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
We do not help with malicious bots
it a test nuke bot i not going use on any severs
Still
Against ToS
okay but if rate things every happen again how do u fix it
Still, first of all its against the discord ToS no matter if you "only" use it in a test server, besides that rule 5 clearly states that it's disallowed requesting help for such stuff^^
nice
Repl is trash
okay get aside from the nuked you still have not answer my question
I won't.
Can anyone please help me with this?
If that code every shown again how do you fix it
I already did..
No, because it does not work
No, it's actually good in some cases
How does it "not work"
If I have it right then why won't levels will not register
I provided you with a solution...
1 of the databases does not register
yes, like I said
the last
setattroverwrites the old attribute
the solution is to just change the name of the attribute
Yeah this doesn't look like something we would help with
i swear no one answering my question
or you could create all of the tables inside one file
You are coding a spam bot. Doesn't matter if it is for testing or not.
I will have like 15 tables when I am done
wait, does the Client class have a db attribute?
nice nuke bot code lol
nuke bots aren't nice..

well
the file would be big, if you wanna create different files for each table go ahead, just make sure you name the "db" something else
Would it still work if I did it that way?
yeah
Jonathan, does it?
Yes
discord.py docs?
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
why would there be a db attr?
Jonathan said where was one
it's a custom attribute he set
there*
!bot-vars
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
oh mb then
it probably was a bot var
Yeah
I combined the databases
worked like a charm
@boreal ravine Thank you so much.
I also have a db var but it's not a bot var
I made my own cause yes
😏
😏

😏
Intensifies
i made a whole db client
anyone here know hot to make a warning command witch includes warn, warnings and unwarn?
Does anyone know how to fix this?
Code
there you go
@maiden fable did you just go offline?
bruh
why even offer to help
U didn't typehint ctx to anything
wdym?
how would i make all pinned messages in a server go to a specific channel
is there something like
async def on_pin
or something
that i could use
no
if you look through this it shows all the api stuff https://discordpy.readthedocs.io/en/latest/api.html#client
What's the type of arg do u want ctx to be?
Also, we ain't liable to help you (:
i want to give people a role called muted
Then why do u have ctx
Remove ctx
thats not the problem its when people say they are gonna help and disappear
its just rude
Bruh, we also have irl stuff to do. No one can be online on discord all the time
i didn't expect that but if people just go off in the middle of helping someone without saying a word it wastes peoples time
there is a difference between expecting common courtesy of not misleading people into thinking that they are getting help and having to stay on all the time
i don't know how to pass it through thats why i asked
^^^
and then what?
and that doesn't work at all
Paste yr code here directly
Not the link
ok
@client.tree.command(name="muted", description="mutes member")
@sec()
async def smute(inter: discord.Interaction, member: discord.Member):
Muted = discord.utils.get(guild.roles, name='Muted')
await member.add_roles(Muted)
nope
property guild```
The guild the interaction was sent from.
yeah that doesn't show it at all
Eh wym
i mean the section you linked doesn't reference the interactions with guilds to roles
Bro, u gotta do discord.utils.get(inter.guild.roles, name="Muted")
Show
@client.tree.command(name="muted", description="mutes member")
@sec()
async def smute(inter: discord.Interaction, member: discord.Member):
Muted = discord.utils.get(inter.guild.roles, name='Muted')
await member.add_roles(Muted)
That means there's no role with the name Muted
I had this code running and I don't really understand the error on this, can someone tell me?
WARNING:disnake.gateway:Shard ID None heartbeat blocked for more than 150 seconds.
Loop thread traceback (most recent call last):
File "E:\Bots\Command\anarchic\source\bot.py", line 8724, in <module>
bot.run(config.TOKEN)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\client.py", line 846, in run
loop.run_forever()
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\asyncio\windows_events.py", line 316, in run_forever
super().run_forever()
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 596, in run_forever
self._run_once()
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1890, in _run_once
handle._run()
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1340, in on_application_command
await self.process_application_commands(interaction)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1332, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 597, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 778, in call_param_func
return await maybe_coroutine(safe_call, function, **kwargs)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\utils.py", line 561, in maybe_coroutine
return await value
File "E:\Bots\Command\anarchic\source\bot.py", line 2909, in sstart
await _start(inter, True)
File "E:\Bots\Command\anarchic\source\bot.py", line 3132, in _start
await assignroles(var[ctx.guild.id]["setupz"], ctx.guild)
File "E:\Bots\Command\anarchic\source\bot.py", line 6205, in assignroles
hisrole = random.choice(var[ctx.id]["mafias"])
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\random.py", line 344, in choice
How the heck do u expect the bot to get the role if it doesn't exist? 😐
You have a blocking function
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
bruh thats not the problem i just told you that
@solar seal tell me... Do u have a role named Muted?
yes
In that very guild?
obviously
Then what's the error u r getting
i am telling you it throws up errors in the code
I mean, share the error then bruh
Argument of type "Role | None" cannot be assigned to parameter "roles" of type "Snowflake" in function "add_roles"
Type "Role | None" cannot be assigned to type "Snowflake"
"id" is not present
Is there a way to replace characters in a string from a regex with blank spaces?
That's just telling u that if Muted is None, it would not work
ah
invisible unicode
!d str.strip ig?
I mean how would you go about replacing it
str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
```py
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
``` The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
This removes the spaces
Does it work with regex?
Wym by that?
it works with any kind of string
So essentially, the bot we use to ban adds the user-username to the audit log reason for some reason
So I'm wanting to replace anything in the reason matching the regex (?i)(.*#\d{4}): with ""
how could i make all pinned messages get sent to a certain channel
all pinned messages in every channel*
I.e. it would replace abcd#1234: with ""
that sounds like something re.sub(...) would do i think
is there a way to remove the error at all?
remove the error from the IDE itself?
Just add an if statement
if Muted is not None:
. . .
fair
that or type ignore (if thats what ur talking about)
Eh, I would advice against type ignores
yo
Cut-down code: ```py
banreason = await guild.fetch_ban(user)
newreason = re.sub('(?i)(.*#\d{4}):', ' ', (str banreason.reason))
[...]
banembed.add_field(name="📄 Reason:", value=f"{newreason}", inline=True)
Error: ```re
Ignoring exception in on_member_ban
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 94, in on_member_ban
newreason = re.sub('(?i)(.*#\d{4}):', ' ', banreason.reason)
NameError: name 're' is not defined
import re when?
(str banreason.reason)


Have that
yea that too
well your error says you dont
Added after it no worky
Hmm
I am way to tired, I pressed ctrl+z too much at some point and got rid of import redawoqLKM{oaw;kdjonbb
Anyone there 
I am
Me

what did i do? i only added one command
U have a command named bot
you cant have a command named a function unless use use an alias im quite sure
Thanks
Ah those are command aliases
wrong person pinged lmao 💀
how to get all members id from a guild ?
thank you

anyone know how to make a clear command for slash commands on discord.py?
what do you want to clear?
just int(str)
that doesn't work
whats wrong?
let me send the trash i have
show code
@client.tree.command(name="clear", description="clears messages")
@sec()
async def sclear(inter: discord.Interaction):
await inter.channel.purge(limit=)
await inter.channel.purge(limit=) just why
wdym?
i would have done that if i knew how
literally i can do everything fine except anything to do with slash commands
async def sclear(inter: discord.Interaction, limit):
limit = int(limit)
...
limit: int, it doesn't really do anything if u expecting it to
its just for the reader to know that it limit should be int
its just saying i have to
who its?
you need to sync the tree to update slash commands
u should, i was just telling that that wont convert it to an int.
what?
i didnt know that, cool
why do i keep getting
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.author.icon_url: Scheme "2cbf391d2820b66f610327bced0af098" is not supported. Scheme must be one of ('http', 'https').
Is there anyway to get the transcripts from a discord channel in this format?
["Person#0000: Hello, this is a message", "AnotherPerson#0000: Hello, this is another message"]```
How to make the bot use slash commands without entering guild id
it will be able to but slash commands requires up to 1 hour before they being registered globally
Wdym
Will it take 1 hour once
Or every time it joins a server
that before they would be available globally it will take up to 1 hour
How to do it
But how does dank memer bot do it without taking 1 hour
use f strings 
it takes UP to 1 hour
that doesn't mean that everytime it takes 1 hour
it can take like 5 minutes or it can take 1 hour
value=f"BLAH BLAH BLAH {client.name}"
Ok
it should be "{} .. {}".format(arg1, arg2), but use fstrings in this case
TEXT FILE - JSON DATA
user_data = '{ "userid":"user1", "cash":"100"}'
user_data = '{ "userid":"user2", "cash":"100"}'
user_data = '{ "userid":"user3", "cash":"100"}'
user_data = '{ "userid":"user4", "cash":"100"}'
user_data = '{ "userid":"user5", "cash":"100"}'
user_data = '{ "userid":"user6", "cash":"100"}'
Code:
`import json
with open("userdata.txt", 'w') as f:
f.write(message.content + '\n')
json_load = (json.loads(json_data))
print(json_load['python'])`
how to make python add 50 cash to userid, user 5? by finding and replacing the value in txt file? sorry im new to this , pls help me thxs :/
json is used to represents javascript object in text files, not as storage method
then how do i make it for a currency system?
for my discord bot*
how to self bot in cog?
A database.
how?
MongoDB, Deta, MySQL, PostgreSQL, Cassandra, MariaDB, SQLite3
by.. using it?
oh
You want to self bot?
yes..
💀
👀
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
its not against tos..
it is
Do you also want me to go through discord ToS
class fun(Cog):
def __init__(self, bot):
self bot = bot
``` syntax error??
What did you mean by self bot here
uh
😆 😆 😆
self.bot
self.bot = bot
when you load json object in python you'll get a dict of the data inside
{
"name":"bob"
"languages":["English", "French"]
}
import json
with open('path_to_file/your.json', 'r') as f:
data = json.load(f)
print(data)
Output: {'name': 'bob', 'languages': ['English', 'French']}
self.bot= bot
thank you guys

:nice:
That is an instance variable
ok
before getting into d.py you need to know python and OOP concepts
That is why you should understand the context first 🤣
He was vague
It was either about instance variables or literal self botting
ok
ok
it's... recommended
async def giveaway(self , ctx:commands.Context, x , channel:disnake.TextChannel, time1 , time2 , winlimit , * , title ):
my givewaway function lol
why do you have so many spaces? 😔
it looks nice
it looks inhumane
..
async def giveaway(self,ctx:commands.Context,x ,channel:disnake.TextChannel,time1,time2,winlimit,*,title):
fine
async def giveaway(self, ctx : commands.Context, x, channel : disnake.Textchannel...):
i will help you out
async def giveaway(
self,
ctx: commands.Context,
x,
channel: disnake.TextChannel,
time1,
time2,
winlimit,
*,
title
):
async def giveaway(self, ctx:commands.Context, x , channel:disnake.TextChannel, time1, time2, winlimit, *, title):
nice
yeah that's more pep8 like
..
after x
uh
async def giveaway(self, ctx:commands.Context, x, channel:disnake.TextChannel, time1, time2, winlimit, *, title):
fine now
How to create music in python without ffmpeg?
space after :
....
async def giveaway(self, ctx:commands.Context, x, channel: disnake.TextChannel, time1, time2, winlimit, *, title):
I assume this isn't about discord bots directly
now dont dare
ctx:
f
async def giveaway(self, ctx :commands.Context, x, channel: disnake.TextChannel, time1, time2, winlimit, *, title):
x is st or stop time 1 is 1 , 2 , 3 and tim2 is hour week sec week mmonth
st?
async def giveaway(self, ctx :commands.Context, x, channel: disnake.TextChannel, time: int, unit: str, winlimit, *, title):```
name it better
stop
but how to use it to change and replace the data?
hm?
if "st" in x.lower():
idc
ok
ctx:
ya i didnt touch that, i just copied and change name of time1 and time2
How to create music in python without ffmpeg?
didnt understand
why black
oh god i just had flashbacks to when i tried to send a countdown message to about 100 servers for a giveaway
and at the end it selected a random winner for every server instead of one for all 
:thumbsup_tone5:
lol i've discovered that the VPN of the client which i'm workin for blocks my website
`import sqlite3 as lite
con = lite.connect('user_data.db')
with con:
cur = con.cursor()
cur.execute("CREATE TABLE user_data(UserID TEXT, Cash INT)")
cur.execute("INSERT INTO user_data VALUES('12031909',10)")
cur.execute("INSERT INTO user_data VALUES('51511111',10)")
cur.execute("INSERT INTO user_data VALUES('8841214',10)")`
if user id 12031909 is in table change the specific user cash by +1. how to do this?
how would i go on from here?
# mute command
@bot.command()
@commands.has_permissions(manage_roles = True)
async def mute(ctx):
i'm trying to make the command give a person a role
update query
how?
just get an IDE which does that for you 😉
first you get the value you want then you do your things and add it again 
try and SELECT WEHRE ID = ?
and fetchone
@placid skiff?
can't tell you how i made custom method for my sql
if it returns none then do your operation
any sample code?
writing?.. 
search online there are plenty
cur.execute("SELECT FROM user_data WHERE id = ?", (id,))
butt = cur.fetchone()
if butt is None:
easiest way is to delete it all
bro you can't sync commands manually

Wdym
i'm trying to make my bot send buttons but it says ImportError: cannot import name 'InteractionType' from 'discord_components
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
@bot.command()
async def button(ctx):
await ctx.send("Press Button",
components = [
Button(style=ButtonStyle.blue,
label="CLICK Me!")
]
)
rest = await bot.wait_for("button_click")
await rest.respond(type=InteractionEventType.ChannelMessagewithSource,
content="Clicked!")```
cur.execute("SELECT FROM user_data WHERE id = 12031909", (id,)) butt = cur.fetchone()
is it like this?
if you're not using ? placeholders you don't need the tuple telling it the number to use for id in your table
client has no method tree btw
i dont understand, let me do some research.
@client.tree.command()```
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
Cuz I need to sync to use slash commands
best place i found to learn
thxs
Client has NO tree method 
What is so hard? 
mood
look at their screenshot lol
BlvckTvrsier.tree
have you ever used vscode? @placid skiff
tldr tree exists on their client
and sync exists as well
Bruh 
an attribute is white if the type checker doesn't know what it is in vscode
they've probably subclassed client and added tree to it
lol i'm not really sure about it, show your client instance @sullen pewter
how to set a cooldown for message.content.lower?
2 second response cooldown for each user of the bot?

CliEnT = commands.BoT lol
ik this question is stupid, but i want to set cooldown*
you understand message.content.lower just turns everything lowercase right
Did you subclass bot?
?
doubt it too you are using commands.Bot
so i'm right, there is no method client.tree in your code 
might be inbuilt way depending on the library you're using
Wdym
someone pls tell me how to set cooldown for that? ik it turns everything lowercase
A variable or a command
the only way there is a client.tree is because you wrote client.tree = something in your code
Wdym by method
omg
No
i'm out 
I have this and it works fine
there's no one way to do that
If I have one server id
I didn't I am using dpy 2.0
then how im i supposed to do a cooldown? plss teach me, sryyy im new
I would heavily suggest that you go through some python tutorials online or something @slate swan or you're going to struggle
before getting to dpy you should know python and OOP concepts
i would love to learn
Hello i reccomeded learning py basics and if your stuck on certain part of topic stack overflow Is your freind if your problem still arises just send problem here


