#discord-bots
1 messages Β· Page 791 of 1
Lemme see
;-;
u didn't define self
its now doing nothing
its starting up
oh wait it did
it takes time to get the data from discord, parse it and stuff
yes
Mind showing it?
@slate swan
idk if u meant this but this what i understood
no, an on_message event
Also
do *, item so that u will get a single string instead of list
something like this
@client.event
async def on_message(message):
...
I am not looking for a client.event, but a client.listen() with await bot.process_commands in it haha
Now im getting this discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: bot
i dont
Mind showing the whole error?
Since that is the reason the commands are executed twice
Don't ask us everything,
you won't learn anything like that
Yea Stop it
Traceback (most recent call last):
File "C:\Users\garyk\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\garyk\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\garyk\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: bot
Wdym ?
nvm was meant as a joke
Been trying to get this command done for a WHOLE day
show latest code
We are programmers , we remove bugs for days
π
Welcome to the cult
also can u tell how to use commands from different files? i used to do that in js but i forgot because i havent done it in a long time
cogs ?
wuts dat
or other way around which i forgor π
class that can be reloaded, unloaded, loaded and is group of commands and listeners
!d discord.ext.commands.Bot.add_command ?
add_command(command)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientException "discord.ClientException")
ah ye that
how am i supposed to download the hlper module
What is that
pip crashed
so i got a template online
it does?
And this isnt the appropriate channel to fix pip
Either claim a help channel or ask in #python-discussion
People in general: Why tf do people come here for help, there are help channels for a reason π€£
so now im supposed to fix pip when it was working absolutely fine 2seconds
They arent even discussing anything useful half of the time lol
Hmm
Let's give them some work then :DDD
just uninstalled
Cool
xD
wow, my bot's bot.users
i want like
if commands by user != commands of bot :
await ctx.send ('not a valid command')
else:
()```
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
How would i add a kick feature on this?
https://paste.pythondiscord.com/hividixiza.py
await message.author.kick(reason)
Pep8 wants to discuss with you about your pfp.
Anything else?
I need a new pfp
yes, you do.
so it cant be done using self?
no
wait i can use the channel object right?
how do i fix this
Traceback (most recent call last):
File "C:\Users\garyk\AppData\Roaming\Python\Python37\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\garyk\Desktop\delink-bot-main\init.py", line 59, in on_message
await deletemsg(message)
File "C:\Users\garyk\Desktop\delink-bot-main\utils\functions.py", line 55, in deletemsg
await message.author.kick(reason)
TypeError: kick() takes 1 positional argument but 2 were given
reason="Kicked cz why not"
My irl pic Nah I'mma pass
cat pfp
why is a blackjack command so hard to make
No thanks
smh
Peter Parker pfp
No thanks
guys guys, does the on_slash_command_error event follow the same syntax as on_command_error?
rip everybody
why are u ripping me
sorry bad joke
@commands.Cog.listener()
async def on_guild_remove(self,guild):
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
prefixes.pop[str(guild.id)]
with open("prefixes.json", "w") as f:
json.dump(prefixes,f)```
looks like a Lucas tutorial
nah
Ignoring exception in on_guild_remove
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 "/home/runner/beluga/cogs/prefix.py", line 65, in on_guild_remove
prefixes.pop[str(guild.id)]
TypeError: 'builtin_function_or_method' object is not subscriptable```
wanna see my prefix command?
what error?
I was making an function which received an instance of commands.Bot(...) so I type hinted it with bot: discord.ext.commands.bot.Bot which got me the error AttributeError: module 'discord' has no attribute 'ext', what am I doing wrong here?
Well, at first it would be discord.ext.commands.Bot
And I would recommend to use a different library as discord.py is no longer being maintained.
what error in it ?
so, can I create a command that, when executed, will restart the bot? 
they are good tbh
hmm
@commands.command(aliases = ['changeprefix','chprefix'])
async def prefix(self,ctx,*,prefix=None):
if ctx.author.guild_permissions.manage_channels == True:
if not prefix:
with open("prefixes.json","r") as f:
prefixes = json.load(f)
prefix = prefixes[str(ctx.guild.id)]
em = discord.Embed(title='Current prefix',description = f'My current prefix = `{prefix}` ',colour = discord.Color.gold())
await ctx.send(embed=em)
else:
with open("prefixes.json","r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open("prefixes.json","w") as f:
json.dump(prefixes,f ,indent=4)
emb = discord.Embed(description = f"**prefix changed to `{prefix}`**",colour = discord.Color.gold() )
await ctx.send(embed=emb)
else:
with open("prefixes.json","r") as f:
prefixes = json.load(f)
prefix = prefixes[str(ctx.guild.id)]
em = discord.Embed(title='Current prefix',description = f'My current prefix = `{prefix}` ',colour = discord.Color.gold())
await ctx.send(embed=em)
```
my prefix command

call it
what library
disnake uwu
rtd idk
Yes
Is it invalid to use decorators like this?
class meta(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command
@self.bot.cache.command("cmd_test")
def test():
return
I am getting the error self is not defined (on the line of second decorator)
so how can I can make an decorator from the bot argument that __init__ takes?
without the use of globals?
thanks youuu
Only that you don't have some of the exceptions that Context has
And have the extra exceptions an interaction raises
oh yeah, I checked the docs for those
You need to call .command
Also where's the params for it
And it's supposed to be a coro
oh yea oops
Also you can't access class attributes in a decorator like that
Now it looks like this :
class meta(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@self.bot.cache.command("cmd_test")
async def test(self, ctx):
return
edit : err
Oh, so how should I proceed then?
async def test(self, ctx):
...
discord api wrappers are all about asynchronous programming π«
And remote that self.bot.cache decorator
Remove*
I kind of needed that, it was an custom decorator
what's the alternative?
π€
def wrap_command(your_params_here):
def inner(ctx):
ctx.bot.cache.command(your_params_here)
return inner
No
Oh, thank you very much!
My project code is so sketched right now that I use an alt to ask questions and make PRs π₯΄
how do i make my bot mention a role?
<@&id> or if you have the role object, use the discord.Role.mention property
kk thx
@slate swan ?
cof cof
Calm down
how to react to a new arrive in the server
whats a new arrive
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
@slate swan ^
item_name = item_name.lower()
name = None
for item in Egg_Shop:
name = item["name"].lower()
if name == item_name:
name = name
price = item["price"]
break
if name == None:
return [False, 1]
cost = price * amount
users = await get_bank_data()
bal = await update_bank(user)
if bal[0] < cost:
return [False, 2]
try:
index = 0
t = None
for thing in users[str(user.id)]["petbank"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["petbank"][index]["amount"] = new_amt
t = 1
break
index += 1
if t == None:
obj = {"item": item_name, "amount": amount}
users[str(user.id)]["petbank"].append(obj)
except:
obj = {"item": item_name, "amount": amount}
users[str(user.id)]["petbank"] = [obj]
with open("mainbank.json", "w") as f:
json.dump(users, f)
await update_bank(user, cost * -1, "Coins")
return [True, "Worked"]```
These are codes for buy command .... when i run them i dont get errors but still the command dont work ... what can i do?
don't watch YT videos about these types of libraries, that's the first hint
I've seen this code so many times before
hm..
?
What
what you mean by ^
see the above
how do I expect the user to give a float number
You can type hint it
but that doesn't make it only accept floats
That's true, if they inputted 2 it'd turn into 2.0
it can still be anything, the type hint just says it shoudl be float
Not anything but an int/float
if message.content.startswith('$greet'):
channel = message.channel
await channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send(f'Hello {msg.author}!')``` and I want a float
got this from a website
uhh where is the float supposed to come in
Make a check which checks if message.content is numeric
Do not use that tutorial @slate swan, use this one https://vcokltfre.dev/
thank you

does if type(response) == float: work
use isinstance
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
good afternoon
Good morning
good evening
good night
How do you make a slowmode command?
followed it and it didn't work
rewrote the entire code
Hello. I have this code, but i want to make it like when row is 0, to give different output.```python
mycursor.execute("SELECT gen FROM customers WHERE name = %s", (user.name,))
row = mycursor.fetchone()
print(f"selected gen for {user.name}: {row[0]}")
new_gen = int(row[0]) - 1
print(f"gen for update: {new_gen}")
upd_stmt = "UPDATE customers SET gen = %s WHERE name = %s"
mycursor.execute(upd_stmt, (new_gen, user.name))
mydb.commit()
lines.remove(random_item_from_list)
with open('rockstars.txt','w') as f:
f.writelines(lines)
emb=nextcord.Embed(title="Ainta Gen", description=f"Your account is: {random_item_from_list}\n**Gens left:** {new_gen}", color=color, timestamp=datetime.now())
await user.send(embed=emb)
Define 'didn't work'. Errors?
no response
π I'm very bad at discord.py
The code is valid, so it should work. If you are running it locally, then it might have a very long response time
messages before !hello were with a different code
Are you running the bot off of your PC?
yes
The ping is likely the issue. It takes up to two minutes to respond when I run it off of my own
Is this your first time using Python?
discord.py, yes
I'm so bad at it π
No, the language itself
actually not sure how to answer that as I'm still in high school π
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
You need to learn the language - Python
discord.py is a library that uses Python
have you learned Python
He doesn't know the difference between Python and discord.py, so no
yeah
https://tenor.com/view/saul-better-call-saul-saul-goodman-saul-sweep-titans-gif-21970301 when someone tells me I'm bad at python (it's the truth):
You can ignore us, but you cannot make a discord bot if you do not even understand Python
ah no I'd rather be the type of person to follow good advice, thank you
Good luck
But don't waste anyone's time with a more complex library because you don't want to bother learning the basics
lol
python is the easiest language
I don't get why people don't bother to learn it before using d.py
!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.
discord.py requires understanding of decorators and asynchronous programming
Because they want to make something cool and making a simple quiz game using input() is NoT wOrTh tHeIR tImE
yes?
As for asynchronous bot programming, that's what they'd rather be doing
ok π
def get_prefix(client,message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]```
shows key error in last line
the guild id isn't in the json
that's it?
btw really it isn't lol
show full error
Show dict structure
thats how keyerrors are caused
you said it was earlier but ok
guys guys, even though message intents would be disabled, It can still detect if a message was sent, right?
yes
but content, embeds, attachments, components will be empty
hello so i'm basically trying to make the bot posts these answers for these questions everything the these questions get asked within few seconds
kinda forgot how to do that
U can still use the intent as long as u don't plan to verify yr bot highly doubted
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
uhm, I see I see you're right
How would i make a kick command with cogs
same as you do for a normal one, but with self as the parameter for the function
What is the best way to have a command sorter?? without cogs?
wdym by sorter? categories?
How to find out how many times a person has used a command?
database
okay, thanks
cogs have been getting all my code messed up
wdym messed up, it should be helping you for a proper management of the commands
When I tried making a broadcast command to dm the owners in the servers its in it never worked I spent a whole day trying
It should be making your life easier
nope not really
If you cannot transfer your code into cogs you most likely haven't learned fundamentals yet
It's just simple classes
π
Not following pep8 I see 
@slate swan lol?
What python version is better?
I would recommend 3.9 or 3.10
kk
@slate swan maybe u have global error handlers makin debug harder for u i have a load cog shit that i can add/remove cogs if i wanna see btr i only run the cog i am working with
How do i translate discord buttons to cogs?
translate with lexicon.py
Do you think you can maybe help me with mine from scratch????......
Cogs are just a class
So it's just like working in a class
class Confirm(nextcord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@nextcord.ui.button(label='Confirm', style=nextcord.ButtonStyle.green)
async def confirm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@nextcord.ui.button(label='Cancel', style=nextcord.ButtonStyle.grey)
async def cancel(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
``` how do I access this in my cogs?
do I self.confirm = Confirm() ?
it is a class not just xP
Mostly both..... only if you have time
@final iron
Try it
i did
And?
bot.add_cog(eco(bot))
File "c:\Users\philip\Desktop\coding\projects\projects\discord\jr_\economy.py", line 39, in init
self.sub = Confirm()
File "c:\Users\philip\Desktop\coding\projects\projects\discord\jr_\economy.py", line 17, in init
super().init()
File "C:\Users\philip\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 166, in init
loop = asyncio.get_running_loop()
RuntimeError: no running event loop
@final iron
Where u doing that?
on the same file
Like, in the cog file or what
yeah
How would i make it so my bot can play music?
Against ToS
wait what?
Youtube
And what u doing in the main bot file?
!ytdl (it's a module used for music bots)
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
oh ok thx
import nextcord
from nextcord.ext import commands
from economy import eco
intents = nextcord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!",case_insensitive=True,intents=intents)
@bot.event
async def on_ready():
print("The bot is online.")
bot.add_cog(eco(bot))
``` @maiden fable
Show
cogs will automatically load when you start the bot
U still gotta add load_extension else the bot won't know if u r using cogs
File "c:\Users\philip\Desktop\coding\projects\projects\discord\jr_\bot.py", line 13, in <module>
bot.load_extension(eco(bot))
File "c:\Users\philip\Desktop\coding\projects\projects\discord\jr_\economy.py", line 39, in __init__
self.sub = Confirm()
File "c:\Users\philip\Desktop\coding\projects\projects\discord\jr_\economy.py", line 17, in __init__
super().__init__()
File "C:\Users\philip\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 166, in __init__
loop = asyncio.get_running_loop()
RuntimeError: no running event loop
well, in the first place that thing above doesn't even look like a cog
You simple join a vcchannel and do like voice = yourconnection_to_vc.play(andsource)
how to find content of replied message when user replies to someone?
message.reference
please ping me
@slate swanthis is basicly all u need for play music/sound in vc,
hi, this: https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots- says that no selfbots are allowed but ONLY bot api & OAuth2, is possible to make a "selfbot/userbot" using OAuth2 to not gen banned?
self.voice = await ctx.author.voice.channel.connect(reconnect=True, timeout=5500)
self.voice.play(FFmpegPCMAudio(url), after=lambda e: print('Player error: %s' % e) if e else None)
because probably you don't use them right
selfbots are not allowed, that's all you need to know
but if i use OAuth2 ? what i can do using OAuth2???
and what is allowed to do with OAuth2??
not everything
u should't keep asking tho about selfbotting
yeah ^
WHAT?
what what
just move on make a bot or find another server
which part of it did it mention "self-bots"
theyre not like bots??
well he asking about whats diffrent n whats allowed selfbot vs bot
@crisp tapirdo u know what a bot is?
thats sus because the more we tell him the more he'll find out about self bots
ah then sorry
look at the last sentence
yeahh
that...
if they can do both same ofc,
"to not get banned"
so you wanna use OAuth to make a self bot?
if u use OAth in ur developer page @ discord, u still have bot
but u dont use token, u use Oauth to identify urself
yes?
its not selfbotting
selfbotting is pretend be a client
on telegram userbots are allowed
but you do automated stuff
this is discord
if you dont spam
ik
anyways lets stop the convo bout self bots
why cant u just do a bot like 99% else what disturbs u so much having a [bot] tag?
okay sorry
it cant join servers, i want to sell fake members to become rich lol
i could understand if u would like to make a discord CLI client for fun but thats pretty much only reason
lmao what
and that is not selfbotting cause nothing is automated
tf?
@crisp tapirok i think ama report u
can i ping moderators for this
its fine i reported to modmail
Depends on how he is self botting though
@cloud dawnhe wants to sell fake accounts and get rich...
either way, tos
and this
No not specifically, recommend reading the tos
@crisp tapir hello, we won't help with self-botting as it violates Discord's ToS
okay
i think its funny when peoples has agendas like that but cant code n needs help xD why not gitgod or giveup
Dashboards for example are self-bots, per-guild configs.
what is dashboards?
A website that can interact with the bot.
hm why not use webhooks then?
Those are really limited
what?
How to respond to the author of the message in on_message?
how's that self-botting?
I need help guys
ctx.author.send for dm
That isn't?
Since usually you would use oauth to login with your account. To look into your own guild.
in on_message not ctx
message.author
well message.author
message.author.send
i was little too fast ^^
my discord project is not running pls help
How to chat with him?
ok ποΈ noticed
What
sometimes i cant tell if noobs or trolls,
Breh
i want a proper syntax for it like -
if command used by a user != command of my bot:
await ctx.send('hi')```
U shouldn't really judge anyone like that, yk
How to do the same only in on_message?
i didnt judge, i said i could't judge π
!d discord.ext.commands.CommandNotFound
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Oh wait my bad
Rip I'm sleepy
Misread can't as can, sorry!
aliases
check message.content.startswith()
how can u check amount of members in a guild?
With or without bots?
With
total members? are you talking about that?
yes
guild.member_count iirc
@slate swannothing wrong with 666 tho
I don't really think this is a Mod case? Idrk, I guess that's for mods to find out
@slate swanis it a crime being antichristian?
Hello. Could you contact @novel apex please.
iirc it's considered as bad in India or smth
Next time best to report to modmail instead of creating a witch hunt.
Hunt π
guild.member_count
in that sense i feel u, but overall 666 yes is devils number but everyone has their rights of religion
Let's keep further discussion of this out of this channel to stay on-topic please.
π
that is correct
U both should just take it to OT or DMs idk
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
So, discord bots ey?
@slate swan lets debate religions
Why not
How do I make a kick command?
Let's spam Discord's API Computers
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
What aspect of it are you having trouble with?
Well I haven't made a fully kick command..
thanks, that updates when a member joins, right?
hello guys, what happends with python dc api??
https://discordstatus.com looks fine to me.
Welcome to Discord's home for real-time and historical data on system performance.
would i make a discord bot with replit
How do i make is so when i ban someone it DMS them the reason?
Before banning use member.send()
https://vcokltfre.dev/ code is code. This should help you get started.
is there a way to detect when the bot is kicked from a server?
!d discord.on_guild_remove
discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
This happens through, but not limited to, these circumstances...
Keep in mind that you can't send anything to that guild anymore.
yeah thanks for the tip!
hi i just made a bot and i tried to upload it to repl.it and the cogs don't work (on my pc it works) and no error shows up
can i do something about it
??
just send a dm user.send("ur banned!") but make sure send msg before banning
how can u do something like user has been invited by user2
thats lil complex, i would suggest use a already made lib for that
and its still aint 100%
what's the lib?
google discord invite tracker python
a whole database is still just a tiny databse π€·π»ββοΈ
pls respond
Anybody know like good base code for a discord antinuke
this isnt much to work with.
Really need it to stop bans channel creation
what do you mean by discord antinuke?
Did you add a .replit file?
Bots like wick bleed haunt
no
You could use it to make your bot start when you run the replit
@commands.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx,member : discord.Member,*,reason= "I do not need a reason"):
await ctx.send(member.name + " has been banned from the server, because"+reason)
await member.send(reason=reason)
await member.ban(reason=reason)
``` when i try to ban someone i keep getting this error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Admin' object has no attribute 'send' can anyone tell me whats wrong
inside a cog its self, ctx, ...
Recommend coding it yourself, not that hard if you've done other commands.
i used keep alive method with flask
also reason isn't a kwarg of .send
Put this inside of a .replit file.
run = "command to start your bot"```
ok
For example, one of my bots uses this.
run = "python bot.py"```
@bot.command()
@commands.is_owner()
async def rename(ctx, *, message):
channel = ctx.textchannel()
await channel.edit(name=message)
await ctx.message.delete()
this correct?
or should it be ctx.TextChannel()?
ctx.channel not ctx.textchannel()
appreciate it
yeah ctx.channel
however, to get all text channels
it's ctx.guild.text_channels
bruh i m just stupid i had the bot running on my pc and the replit
Lol
can u do something like this
bot = commands.Bot(remove_command='help')
yeah
Hey guys, how do I send a text fille via python code to a discord webhook? Just a simple webhook message with the text fille on it.
also dont mind my status im just testing it on my own lol
await webhook.send(file=text_file) where webhook is an instance of discord.Webhook and text_file is an instance of discord.File object - or you can do discord.File(byte_like_object) where byte_like_object is a byte-like-object/fp
no theres no such kwarg yall have to set the help_command kwarg as None
Thank you I will try
How would i make a tik tak toe command
first make the game outside of discord to understand how it works, then implement it in a bot
This doesn't work
Guess replit is not the best cloud hosting
No but itβs free π€£ππΌ
If I own my bot how can I make it so I canrun them without admin perms in the server?
Replit thing try local host and then put in a private github then use heroku it is free
Heroku doesn't work for me
If local host works
Did youmake a requirement.txt qnd a procfile?
Yes I followed the instructions on Jacob Allen how to make discord bot
are txt databases decent?
Yes
Json is better but sql is best
well, it's for a school project and we need to use txt for it
oh this is the wrong channel. my apologies
No it is just for a hobby
BTW I am 12 and I really understand the code
ok?
Yes I know, but our teacher stated that we must use a txt database
so i'm just asking around it
then dont do the project
lol
hes teaching you horrible things because txt files arent supposed to store data
How to make the bot not constantly write that a person has 10,000 xp and a new role?
Yeah, i know we used sql before, but were using txt cause we need to apparently, he agreed on it himself
i would just do the project in sql or not do it lol
bad practice isnt something good lol
agreed
Instead of letting the member. Name just make it an f string and write like this (f"{member. name} has been banned from the server, because {reason} " )
pep 8 is screaming
and your missing self
and .send doesnt have a reason kwarg only ban does
how can u get the account age? in days
!d discord.User.created_at || you would use strftime on user.created_at
property created_at: datetime```
Returns the userβs creation time in UTC.
This is when the userβs Discord account was created.
created_at = member.created_at.strftime("%d")
alr, gotcha thanks
hi so i have 2 different bots a beta bot and a regular bot i want them in the same folder but idk what to do because i don't want the cog files colliding
make 2 different cog folders
Will it mess up in my bot or do I do one cog and one cogs
no just add different paths
Explain
hey man i tried something else but its not working
I dont understand how to apply yours
also the text filles I am trying to send will always have different names
why dont you just use discod.Webhook?
how do you get a guild id by using a role?
!d discord.Role.guild
The guild the role belongs to.
The guildβs ID.
okay, how does get_role work then? ive tried
bruh = await bot.get_role(role_ID)
print(bruh.name)```
but i get `'Bot' object has no attribute 'get_role'`, do i need to fetch the guild first?
hell is happening
!paste -- please use this instead of a picture
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.
isnt it guild
I need a way to fetch the guild by using a role
why?
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.

Easier for us to read
If it is the command prompt, right-click the title bar and select "Mark", then highlight the stuff and press Enter to copy it
`
C:\Users\Ramsay>pip install discord.py
Collecting discord.py
Downloading discord.py-1.7.3-py3-none-any.whl (786 kB)
|βββββββββββββββββββββββββββ | 655 kB 45 kB/s eta 0:00:03ERROR: Exception:
Traceback (most recent call last):
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_vendor\urllib3\response.py", line 438, in _error_catcher
yield
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_vendor\urllib3\response.py", line 519, in read
data = self._fp.read(amt) if not fp_closed else b""
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\site-packages\pip_vendor\cachecontrol\filewrapper.py", line 62, in read
data = self.__fp.read(amt)
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 465, in read
s = self.fp.read(amt)
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into
return self.read(nbytes, buffer)
File "C:\Users\Ramsay\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read
return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
`
whatever you say ma'm
!code -- see this as you used a single backtick ... (ignore adding the py part since it is not actual Python code)
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
discord.py is just a mirror
seems like a pip issue
!pypi discord.py
Ah ... so it's the old one?
^^^
Is discord.py the obsolete, outdated one?
jesus how come i forgot import discord means i have to install discord not discordpy, sorry
Master isn't published to any pypi. You need to directly download it off github
isnt discord the mirror?
You know this better than me, I assume.
I'm running off of memory
Β―\_(γ)_/Β―
yea
but yes master isn't published to the pypi
also that wasn't a python code but thanks
they just meant that you should use codeblocks, read what they wrote in brackets
it is
its an outdated mirror
just use a fork tbh π₯΄
@tasks.loop(seconds=600)
async def role_color():
colorz = ["red", "green", "lime", "yellow", "purple", "orange", "blue"]
guild = client.get_guild(756504534897000528)
for role in guild.roles:
try:
for color in colorz:
await role.edit(color=discord.Colour.color())
print(role)
except:
pass
cause youre my cat brother
sister* pls dont gey my genders mixed up
did okimii get brozoned again?
ποΈ ποΈ
Does anyone have idea, how to create a invitation tracker on high traffic servers?
Im trying to have my bot mention a person and a channel, but It keeps showing up as this instead of actually mentioning
ohh ok, thanks!
and channel.mention on a TextChannel object
follow down all invites, once someone joins a server, check which invite has a join more than before
so database
That requires me to use guild.invites() a lot right?
I think so
But it gets rate limited
wdym
Had experience when it started returning None after few hours of running
I thought it got executed so many times that it stopped giving me results
help guys :(
bot = commands.Bot(
command_prefix=get_prefix,
intents=disnake.Intents.all(),
case_insensitive=True,
is_owner=493344822900424714,
)```
```py
@tasks.loop(seconds=60)
async def change_pr():
await bot.change_presence(
activity=disnake.Activity(
type=disnake.ActivityType.playing,
name=f"With {len(bot.users)} members in {len(bot.guilds)} servers",
status=disnake.Status.online,
)
)```
```yaml
Unhandled exception in internal background task 'change_pr'.
Traceback (most recent call last):
File "/config/.local/lib/python3.8/site-packages/disnake/ext/tasks/__init__.py", line 167, in _loop
await self.coro(*args, **kwargs)
File "/config/workspace/main.py", line 45, in change_pr
await bot.change_presence(
File "/config/.local/lib/python3.8/site-packages/disnake/client.py", line 1428, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
AttributeError: 'NoneType' object has no attribute 'change_presence'```
where are you starting this task?
make sure to do it after the bot has started running
at the end of the file
yeah you should use wait_until_ready
is there a way for me to make let my bot make changes to the code when run?
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientβs internal cache is all ready.
another alternative is passing the activity while initialising the bot
thank you!
ex: i have number = 1 every time i use command addnumber it changes to number = 2
if you dont need to change it
you could change code in cogs and then reload the cog
I was starting it before my run function lmfao
what is cogs
or add things to json file
exts that have commands and listeners
i dont get it
@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=discord.Activity(type=(next(activity)), name=(next(status))))
I use this, You can get the idea from it
please don't
It's better...
ur gonna get rate limited fast.
I never do...
You can change the seconds to 30
still sounds bad
I NEVER DO THO!
I swear I don't
the person is still confused what next is, bet
status = cycle(['SamTheNoob#4854', 'The Hub'])
activity = cycle([discord.ActivityType.listening, discord.ActivityType.watching])
:)
and where does the cycle comes from? you dont show how you import it from itertools
from itertools import cycle
here
and here we have, Making a discord Bot with python : Part <> ( Custom Status)
yez!
And making the bot pretending to watch the hub
its from lucas, if im not wrong
Well, I started watching his videos to learn python and making bots
But no...
and ill assume you start the task in on_ready too?
yes!
hm
It was my idea
I'm a weirdo
How would i make it so i can have all my commands in different files? like 1 file per command
use cogs
and make a cog per command
but why would you do that?
So then i could work on one command at a time without messing anything else up
dont worry, I know that much and it was just a stupid mistake (me starting loop before starting bot)
no im procrastinating π
@commands.command()
async def Ping(self, ctx):
await ctx.send("pong")
would be if your trying to get it to respond to a text
lmao i was talking about caeden
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
ohhh yeah he is
and what this is used for @client.event
a event decorator
what is the difference between @client.event and @commands.command()
@slate swan
one is a command thats in a cog and the other one is an event
cog?
its an ext that has commands and listeners
ext? @slate swan
is there an event for when someone deletes their account?
this can help you with all the questions
https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
THKS BRUH
yw
!codeblocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
you put # instead of @ first line 
I copied it wrong here but itβs got @ on the code
Help pls
well you didn't pass any id in the get_channel at the top either
Yes I did, I just missed that out here. ππΌ
why
Hang on, let me edit it.
embed = discord.Embed(
title = f'@{username}',
url = f'https://www.instagram.com/{username}',
color = discord.Color.purple()
)
Does anyone know how to randomise the color of an embed?
do you have an error anyways
randint
!d discord.Colour.random
No documentation found for the requested symbol.
lmao
well, it exists
you can use discordheximals or just use the built in
!d discord.Colour.random
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
its ust not documented
wait wtf
random.randint(0x000000, 0xFFFFFF)
or the Color class is just a Subclass of Colour we can say
you dont need to do that lmao, just use discord.Color.random()
No errors, just wonβt accept Submit & send to the log channel
not american π€
disnake/colour.py line 326
Color = Colour```
my life was a lie
@cold sonnet help pls
its just an alias or an instance of the class
im american
ok
lol
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
lol
it's not?
it's not just a word
is it possible to get ctx like this when using slash commands? (i cant test it myself rn cuz my slash commands wont register for whatever reason)
@bot.slash_command(guild_ids=[GUILD_ID])
async def takegold_slash(ctx,interaction: Interaction, arg1: int = SlashOption(required=True), arg2: int = SlashOption(required=True)):
arg1 = arg1.replace("<","")
arg1 = arg1.replace(">","")
arg1 = arg1.replace("@","")
arg1 = arg1.replace("!","")
if await PlayerSignUpChecker(arg1) == "no":
await SignUpPlayer(arg1)
await TakePlayerGold(ctx,arg1,arg2, prefix, owner_id)
*using nextcord
!d disnake.Interaction.author
The user or member that sent the interaction.
so i can just do Interaction.author.id?
yes
How do I make a warn command?
Well you need to log your warns in a database
You should also add a system to remove the warns
Making a warn system is quite simple
hes asking like how
first you need to learn sql than aiosqlite and then you make a db file with the sql browser and make a table and then youre good
Can someone find me where I am calling an int? literally can't find it
Here's file that the error occured :
import discord
import typing
from discord.ext import commands
from tools.enum_tools import CommandType, EmojiRubric
class enlarge(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def cmd_enlarge(self, ctx, *emotes: typing.Union[discord.PartialEmoji, str]):
successful_additions = 0
for index, i in enumerate(emotes):
if not isinstance(i, discord.PartialEmoji):
embed = discord.Embed(
title="That is not an custom emoji",
description=f"You need to give me an custom discord emoji!\nYou passed in : {i}",
)
await ctx.send(embed=embed)
continue
embed = discord.Embed(title=f"Enlarged view of {i.name}")
embed.set_image(url=i.url)
embed.set_footer(
text=f"{index + 1} of {len(emotes)} to enlarge {'' if not (index + 1) == len(emotes) else '(over)'}"
)
successful_additions += 1
await ctx.send(embed=embed)
await self.bot.cache.command(ctx, CommandType.enlarge)
await self.bot.cache.emoji_rubric(
ctx, EmojiRubric.enlargement, successful_additions
)
def setup(bot):
bot.add_cog(enlarge(bot))
Here's the entire traceback :
Adding add.py from cogs...
Adding enlarge.py from cogs...
Adding list.py from cogs...
Adding meta.py from cogs...
Adding rename.py from cogs...
Successfully connected to the database
Cache is ready.
Successfully logged in as StackOverflow#8213
im called, type_of_command = <CommandType.enlarge: 'cmd_enlarge'>, type_of_command.value = 'cmd_enlarge'
Ignoring exception in command cmd_enlarge:
Traceback (most recent call last):
File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 173, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Achxy\Desktop\emoji-alchemist\cogs\enlarge.py", line 35, in cmd_enlarge
await self.bot.cache.emoji_rubric(
TypeError: 'int' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 882, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 910, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 182, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not callable
await self.bot.cache.emoji_rubric(
TypeError: 'int' object is not callable
That's exactly what I thought at first too! but emoji_rubric is an function located somewhere and not an int.
async def emoji_rubric(
self,
ctx: discord.ext.commands.context.Context,
type_of_rubric: EmojiRubric,
value_to_increment,
):
"""
Accepts 2 positional arguments, command context and type of rubric respectively
returns None
Internally references increment_usage from database_tools
"""
print(
f"im called, {type_of_rubric = }, {type_of_rubric.value = }"
) # for debugging, remove afterwards, FIXME:
await increment_usage(
self.pool,
ctx,
type_of_rubric.value,
value_to_increment,
in_the_table="emoji_rubric",
)

mhmm
im not sure then
I have checked every line of code and did not find a single occurrence of calling an int

.....
Welp my bot will take 2 more week LOL
make it 3

make it quick learning everything
Kind of wish there was a way i could maybe have someone nice do it for me....
sql is very gud tho
We don't give people code here
keep wishing
Sql is very easy
lol
sad
how do I use cooldown with slash commands?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("I am ready.Let s do it!")
@bot.command()
async def coucou(ctx):
await ctx.send("Coucou")
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print("I am ready.Let s do it!")
@bot.command()
async def coucou(ctx):
await ctx.send("Coucou")
the bot sends me two Coucou messages
i dont know wh
restart
y
did you run the code twice?
because you have 2 instances running
restart and retry
r
you already have the solution, start scrolling
so it pings specific role
if a word is in the webhook
I typed in english, right?
you did but i don't have the solution
you do, in the other server where you asked the SAME question
that's what happens when you crosspost
doesnt do anything
i have another issue look at the user-interfaces asap
hi okimii
help me how i make command invade russia with my nato role
jk π @velvet tinsel hi
i forgot give ukraine role, fixed
russia will never invade ukraine
idc what the west say
How to give experience to a person when he is in a voice channel?
first, you invite him to minecraft server
they say they dont care n coming for putin
hi
bye
by time
And how to determine how long he spent in the voice channel? And then how to make a condition that if a person sat there for 3 hours, then give out 50 xp
time em since joined vc n new timer wen mute - that? i dunno
@rare saddle u seem to get what u want theoratically just do it practically
okay, thanks
bro
what
ye time of seconds for 3h
he said 120*3 first, then 36*3
wtf
now you can't delete that
correct
pings moderators to remove it
move on
movin on
movin on
π
Hey, does anyone know about an open source alternative to statbot?
Not really what this channel is for
And your name is not pep8 compliant, use snake case
No
the channel is named discord bots but okay π
I guess I will ask in offtopic or a help channel
"For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries."
Don't see where it says asking for alternatives to discord bots
Let me rephrase. Is anyone aware of an alternative open source project to statbot? I would like to contribute to such project and its development but I can't find any
Nope
Aight, cool, thanks x)
Any tutorial out there, which teaches/gives tips how to organize files & optimize the bot?
Good resource to understand discord.py more?
https://discordpy.readthedocs.io/en/stable/ probably the best one
Ig something like this could help https://discordpy.readthedocs.io/en/stable/
Wrong one
Idk probably the best resource, I like them a lot
Itβ s almost only place I go to for dpy related stuff
I see
wordy?
you play the piano?
Yes
what grade
But not like that
o
man of culture
U play?
Ur fav genre?
Lmao
I walk in for a lesson and she's like "I signed you up for a concert btw" and I'm like "...you what?"
LMFAOOO
idk
Imagine
I got like 3 rn :sadge:
What do u play most
informal, duet and then big formal
I play off of a grade 4 book
So like classical?
mhm
Idk if I know a classical piece
I'm also doing don giovanni (if that's how you spell it) for the duet
I'm paired with a grade 8 (who's my friend)
I'm a low level grade 4 π¦
Idk how Itβ s spelled
I'm doing the grade 5 dis year tho
by mozart, he does lots of random shit
Idk how grades work but gl
I dont know much bout classical
it's so good
liebestraum no.3 is amazingggg
and another song, idk how to spell it tho
Ill mby listen to it
Did u ever play blues
Also we are having a convo bout music in a discord bots channel
Mods wont appreciate it π
Sure
LMFAOOO
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
nice
whats the best lib for disc bots rn?
