#discord-bots
1 messages ยท Page 1073 of 1
bruh Xmillion
how should i write it
rpm reload commands.reload right?
by any chance not loaded means its still same?
@loud junco try raising the received exception it might contain useful traceback
Yesterday I had this
glhf
ok
why
i edit and host on replit
why u edit
what does that mean
..
did u load the reload cog
Above
i dont understand it
bot.load_extention
somebody explain the error? ๐ญ
listen
ok
what above
How do I make a discord bot?
u want tutorial?
yes please
thank you
np
back
um
130 + lines main.py
?
u want me to show?
no
then?
uh try changing the folder name
what does this error mean
I dont know how to change sorry
I have token = os.getenv("token")
let me try different way
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "fm" is not found
``` got this error
i have fm command in a cog
loaded the cog, all the other commands in the cog works but not this one
it work now
show ur code
the @commands.command and bot.load_extension
oh
@client.command()
@commands.is_owner()
async def load(ctx, extension):
print ('1')
await client.load_extension(f"cogs.{extension}")
print(f'loaded {extension}')
@client.command()
@commands.is_owner()
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
to load ^
@commands.group()
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def fm(self, ctx):
if ctx.invoked_subcommand == None:
await ctx.send("Please Send A Valid Option. \n `[p]fm on` or `[p]fm off`")
@fm.command()
@commands.has_permissions(ban_members=True)
@commands.guild_only()
async def on(self, ctx):
await commands.load_extension("cogs.fmode")
await ctx.send("Freeloader Mode Enabled")
@fm.command()
@commands.has_permissions(ban_members=True)
@commands.guild_only()
async def off(self, ctx):
await commands.unload_extension("cogs.fmode")
``` command in cog
i got this in my utilitycmds file
and other code in fmode file
=.=
why load like this
no idea
how do i remove the default help command?
um
bot.remove_command('help')
thx
why do u want to do that?
to get my own...
any help?
What would iter(guild.audit_logs(action=action)) return?
is it possible to make my bot reply to the command author with a message only they can see?
yes
how would I go about doing that?
audit_logs() returns an async iterator which doesnt implement the synchronous iterator protocol (__iter__), so calling iter() on it would raise a TypeError
If with dpy, then using interactions
Oh
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
๐
lmao
๐คฆ
didn't observe that
lol
;-;
btw is the lib disnake?
no
help me help this? ;-;
is it the same with reload_extension
what
help me find this @slate swan ;-;
yeah in the latest dpy 2.0 versions
how to check my version
If reason isn't provided while banning will banentry.reason be None?
@loud junco are u using discord.py
๐
use 2.0 !!!
ask replit
huh?
i can do that?
ye ig
ok
Ignoring exception in command fm on:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 362, in on
await client.load_extension("cogs.fmode")
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 992, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.fmode' could not be loaded.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 1614, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionNotFound: Extension 'cogs.fmode' could not be loaded.
``` got this error ^
ye
@client.group()
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def fm(ctx):
if ctx.invoked_subcommand == None:
await ctx.send("Please Send A Valid Option. \n `[p]fm on` or `[p]fm off`")
@fm.command()
@commands.has_permissions(ban_members=True)
@commands.guild_only()
async def on(ctx):
await client.load_extension("cogs.fmode")
await ctx.send("Freeloader Mode Enabled")
@fm.command()
@commands.has_permissions(ban_members=True)
@commands.guild_only()
async def off(ctx):
await client.unload_extension("cogs.fmode")
await ctx.send("Freeloader Mode Disabled!")
code ^
k
import discord
from discord.ext import commands
class fmode(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener('on_member_remove')
async def fm(member):
await member.ban(reason="User Left While Freeloader Mode Was On.")
await member.send(f"`Whoops you left {member.guild.name} while they had freeloader mode enabled, now you've been banned permanently. You can appeal this ban in BA server.")
async def setup(client):
await client.add_cog(fmode(client))
i have a file named fmode
here
oh
so what should i use?
load_extension("fmode")?
now it works
cogs.cogs.fmode works
How do i fix this?
you added some field to embed and it's value parameter is empty
you need to fill it
@bot.event
async def on_message(message):
channel = discord.utils.get(message.guild.channels, name='logs')
embed = discord.Embed(title = "Message sent", description = message.author, color = message.author.color)
embed.add_field(name = "The message is", value = message.content)
embed.add_field(name = "The channel is", value = message.channel)
embed.set_footer(text = "Coded with ๐ by Caleem1212")
await channel.send(embed = embed)
slowprint(f"[38;2;255;255;255mMessage sent by: [38;2;0;0;255m{message.author}\r\n[38;2;255;255;255mContent: [38;2;0;0;255m{message.content}\r\n[38;2;255;255;255mChannel: [38;2;0;0;255m{message.channel}", 0.2)
@kindred kernel what's wrong with this?
i was adding perms to cmds but im confused what perms to add in which cmd can anyone help
message.content = None or ''
try str(message.content) + '.' (this will a dot to original message but at least then it shouldn't give an error)
ok thanks
My bot grew to 100 servers in 8 days, then I got lucky and discord verified it within 20 mins but then discord had a bug where it still didn't have the verified badge or is able to be invited to servers. It's been almost a week now and I haven't heard back from a support email. I've missed really important initial growth for my bot.
Thanks for coming to my TED talk, i will now go cry in a corner.
sad
sed
that worked but it makes the bot send a mesasge which gets logged and it creates a loop of the bot sending a mesasge then logging it
..
what does your bot do
with which commands are u confused?
ok i have many of them so
1st . join a voice channel
how to make kick command?
!d discord.Member.kick
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/latest/api.html#discord.Guild.kick "discord.Guild.kick").
!d discord.Guild.kick
await kick(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`kick_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") permission to do this.
my bot is online but its doing nothing =.=
lol
well you need these two in scopes if it uses slash commands
jesus
expectful
what are the ones you're confused about
omg that's why my js bot's slash commands didnt work
like only perms with kick members can kick members so
@commands.has_permissions("im confused here")
await kick(*, reason=None)
and
await kick(user, *, reason=None)
?
wait why would you need to define the permissions
huh?
ohhh okay
ill give x and u tell me y
help ;-;
i have no idea, i always do that within the function if i need to
uh ok
;-;
discord py?
disnake
any error?
no
uh
its not doing anything
i just sent a resources, your move is to understand that you need to create a command then get guild or member object from something and use that kick methods. If you don't know how to create commands you'd better ask it first
what u added recently
remove it for a sec then try
try @commands.has_permissions(administrator=True)
copy
for every?
ig u didnt understand now too
ok
What are the methods for making tracker inviter system, aside from comparing two different invitation lists
i mean i have commands but everyone can use it so im setting perms for each cmd so im asking which perm should i add on x command
x is a list
so im confused
can someone help me
@bot.event
async def on_message(message):
channel = discord.utils.get(message.guild.channels, name='logs')
embed = discord.Embed(title = "Message sent", description = message.author, color = message.author.color)
embed.add_field(name = "The message is", value = f"{str(message.content)}"or None)
embed.add_field(name = "The channel is", value = message.channel)
embed.set_footer(text = "Coded with ๐ by Caleem1212")
await channel.send(embed = embed)
slowprint(f"[38;2;255;255;255mMessage sent by: [38;2;0;0;255m{message.author}\r\n[38;2;255;255;255mContent: [38;2;0;0;255m{message.content}\r\n[38;2;255;255;255mChannel: [38;2;0;0;255m{message.channel}", 0.2)
what do this code, i dont understand?
logs sent messages
ok
and outputs them into the terminal and sends them in discord as an embded
i dont need it
found the documentation
looks like the permission name will be the discord name but without spaces
can someone help me?
so the permission would be (kick_members=true)

it would only allow people who can kick members to kick members?
๐
what do guild kick?
u
lool what are you asking for sparky
my bot is not doing anything
but u cant understand
?
you keep asking for something that makes it only so that people with kick members permissions can use the command
whats the problem sparky
that's what i just showed you how to do
You want to make a dict like {command: required_perms}?
no ๐
ye!!!!
๐คฃ

!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.
what code
ok
sounds like useless but i can try
If your bot is online it's clearly not the token
i have cmd and im asking what perm should i add
ye
are you printing something in the on_ready function?
Ok and what your command is
if it's not getting to on_ready then your token is wrong
alr i have a list so first
- bot join a voice channel
its printing
If his token is wrong he would get LoginFailure
bruh
...
๐

alright
Well imagine copypasting
i dont know what to do with THIS
- means all args after it are keyword-only
okay so just slash commands not showing up or message commands not working?
It's not an arg itself
await member.kick()
message commands
i dont have slash commands
!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.
๐ bro it's a syntax error remove the *,
@loud junco print literally any message's content in on_message
show an example
its printing it
Just print the content
do u have a while true somewhere
@bot.has_permissions(administrator=True)
async def kick():
await member.kick(reason=None)
no
is this right?
no
try removing the if return statements for a second and see if that fixes
which one
What tutorial did you use to learn how to make a discord bot
https://paste.pythondiscord.com/xohohopaxe
I am making so that when there is spam or many messages in chat the bot sends a random pokemon from the list, but it gives me this error
AttributeError: 'Message' object has no attribute 'send'
or print stuff between them
pwease help
freecodecamp
lucas ig
just add random prints in your code until you find where it's messing up, add one at the start of on_message to make sure it's being triggered
wait let me send teh full one
ok
My fam, on_message takes a message argument
but where do i add
It's not a command it doesn't take context
its not even doing anything
save yourself the eye and brain hurt
so how do i send embed
Shame we can't make threads right here
after async def on_message(message):
add on the next line print("is this working?")
I think it's good that we can't make
await channel.send(embed=yourembed)
okkk
it only run when someone vote for my bot
cool
1 - on_message takes in a discord.Message object as the argument, not context. You cannot do message.send() as that's not a thing. You can do message.channel.send() however.
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
theres nothing called channel
what do you mean it only works when someone votes for your bot? It is used whenever someone sends a message
huh
Well with several persons asking for help in one channel it's hard to manage them all but you do have a point
ooo
can u show code
await message.send
What is @bot.user_command?
Is it like DM slash commands?
how tf it will send a message in message
That's not possible.
Like you click person -> Apps and use a command (desktop only)
๐คฃ
i dont even know
๐
google and stackoverflow
๐ฉ
._.
this channel is chaos today
ye
Thank you so much mate.
ok)
anyone wanna join my replit multiplayer and fix it?
yh just try and familiarize yourself with the docs and python objects and you'll be fine
im frustrated
Replit multiplayer sounds sussy
what's the problem
:/
Why will an alt have nitro haha.
its online but doesnt do anything
mind to help me in replit multiplayer?
gonna need more than that
ok
what is "anything"
I remember how discord gifted me nitro once it was weird
everything
no way
doesnt show error doesnt output doesnt do thing
?
i used @bot.cmmand usually so forgot bout this
well where's the code
Hey @carmine hearth!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
How do I add an image to an embed? I tried doing set_image but it doesnt work.. embed.set_image(myimage)
Oh yea I know who to beg for nitro
can i dm u the replit multiplayer link?
they have on_message which they say they only use when someone votes, so it's a little confusing what they're trying to do @stone beacon
if u dont mind
๐
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Elon doesn't know that prolly
my dude sends his company flying
Has to be a https url. If you want to use a local pic well you can easily send it on discord and just use the discord link to the img
how
no
anyone help me
send your problem here
alright np
ye?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i dm u the link u help me?
Can't you just paste the code using !paste
What's the error?
dont worry ill not leak ur token for sure
and ofc do not show your token..
ffs don't show your token to anyone 
!paste
ยป pathlib
ยป relative-path
ยป windows-path
bruh
!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.
oh
Imagine not storing your token as github runner secret
!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.
lol
!paste
lol
!paste
Imagine writing your token in your main.py file in a local machine
hello
It's right here man
Right here
Imagine creating text file token.txt and writing token straight to there
๐
Wth is even happening in this channel anymore
yoo
thats easy
how did your exam go?
Anyway this looks cool
Haven't begun yet, I gtg at 11
oh gl
I just realized it's pretty similar to that JIt thing in India
all the best ๐
Just not as hard fsfs
I forgot the name
u mean jee..
JIT is eng?
lol jee
ahhh my bad
lmao
its IIT
!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.
Hey! I just got an hoster and when i wanted to start it it said this: See screenshot
In short; It couldnt ping...
How can i fix this?
ah
Seems like a #networks problemo
I don't think this is discord bots related issue sorry, you might want to visit #networks
ok
@carmine hearth
- Don't overwrite builtins
- Subclass help command (although for such a light one you may just parse name kwarg to deco and name the function differently)
- Replit sucks
jesus
i use replit for hosting
@carmine hearth https://realpython.com/how-to-make-a-discord-bot-python/
Point 3
EOL while scanning string literal at line 22
why do so many use replit ๐ฟ
because u dont want to sponsor us vps
Cuz of freecodecamp
That tutorial wouldn't be bad if it didn't have this
discord.Client is not bad if you only need to use events or something
LOL
Man they're using client because they don't have to use bot
i cant find tutorial with bot =
Nothing is wrong with client if you're going event based to be fair
Besides there aren't using Bot and naming it client
Oh hold up at the bottom they use Bot
๐คฃ
What
They all just start putting commands into on_message
Imho it's better to start from teaching what Bot is
Idk how you see client as an abstract class ๐คฃ but yes it would be more beneficial to learn Bot first especially as newbies like to jump on that command train
client = commands.Bot()
๐ฅฒ
does this trigger you 
๐
Indeed
anyone wanna join me and sparky?
No thanks 
in replit multiplayer
Well not abstract but something inner class that shouldn't be publicly available to library users
It's not abstract ofc
It isn't inner class. It's more like Bot is an extension
it'd be pretty interesting if we had an event where we all worked on a single replit instance to make a random bot
its for destroying bots
If you're making a commandless webhook or something you'd simply use a client
Or use bot, but it won't matter
But ofc
Well only for that case
I make API's with aiohttp to use them as webhooks accepters ๐คฏ
@commands.command()
async def trade(self,ctx, arg1, arg2, arg3 = None, arg4 = None, arg5 = None, arg6 = None):
await ctx.channel.purge(limit=1)
tradeE = discord.Embed(title=f"{ctx.author.name} is waiting for a trade!", description=f"{ctx.author.mention} Is trading {arg1} for {arg2} \n {arg3} - {arg4} \n {arg5} - {arg6} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
color = discord.Colour.random())
tradeE.set_footer(text="Click The Button Below If You Want To Trade")
button = Button(label = "Trade", style = discord.ButtonStyle.green, emoji=':Pepe_Business:')
async def button_callback(interaction):
await interaction.response.send_message(f"Hey {ctx.author.mention} **{interaction.user.mention}** has accepted your trade!")
view = View()
view.add_item(button)
await ctx.send(embed=tradeE, view=view())
``` no errors in terminal
embed isnt sent
Holy hell
wait
Wtf are those args
:/
And that thing
await ctx.channel.purge(limit=1)
Must be replaced with
await ctx.message.delete()```
What was your issue again
Yeah, that is a better idea
Nah I can't help with that I am not on PC
Also switch to normal IDE for god's sake
What's your issue
Just install python interpreter and the ide itself
can u help?
What's the issue
me?
Ye
"code editor"
the bot is online but doing nothing
Still the embed isnโt sent
Vscode
Replit is not good
give me money if u want me to quit replit :D
.
You never set the button callback to a button
fyi i read > 30 times already
Did it
button.callback = button_callback
After I sent the interaction for button
Well then it's not a full command
@client.command(aliases=['StartSpam'])
async def Spam(ctx, amount=20):
amount = amount
if amount > 500:
await ctx.send('Cannot Spam more than 500 times at once!')
if not ctx.author.id == (f'625025751413948436'):
await ctx.send('Your not Clicks!')
else:
for x in (n+0.4 for n in range(20)):
await ctx.send(f'Spam')``` it says 'Your not Clicks!' on both my main account (Clicks#8882) and my alt account
Could you use a pasting service
who is harris
also my recommendation is to subclass views to implement buttons
yoooooo im subbed to u fam
Nice lol
lol
how?
make one on how to check the author id and respond correctly
hi there, i'm getting a slight error right now and it's kinda annoying:
when I use the ctx.guild.id variable everything works fine, but as soon as I also use ctx.guild.name in the same event (on_message) I start getting errors saying
AttributeError: 'NoneType' object has no attribute 'name'
any ideas why?
this aint making any sense
Instead of if not ctx.author.id == (f'that id') do if ctx.author.id != that id
U need to teach me / help lol
With welcome system xd
There's nothing difficult if the bot is for single guild
For multiple you would need the database and some commands for setting welcome channel
Ye Iโm doing multiguild
Need help doing the set welcome message / deleting it
I had this command in my main file and it worked fine
Then just add welcome_channel_id column to your guilds table and operate with the actual channel IDs, if no welcome message channel is set you could just put NULL into the field
Idk how Lmao I tried myself but nothing works ever
This command is not full. I don't see button.callback = button_callback anywhere
I said I did add it
Iโll send the code again
Also yeah the callback should have self attribute as well
@commands.command()
async def trade(self,ctx, arg1, arg2, arg3 = None, arg4 = None, arg5 = None, arg6 = None):
await ctx.message.delete()
tradeE = discord.Embed(title=f"{ctx.author.name} is waiting for a trade!", description=f"{ctx.author.mention} Is trading {arg1} for {arg2} \n {arg3} - {arg4} \n {arg5} - {arg6} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
color = discord.Colour.random())
tradeE.set_footer(text="Click The Button Below If You Want To Trade")
button = Button(label = "Trade", style = discord.ButtonStyle.green, emoji=':Pepe_Business:')
async def button_callback(interaction):
await interaction.response.send_message(f"Hey {ctx.author.mention} **{interaction.user.mention}** has accepted your trade!")
button.callback = button_callback
view = View()
view.add_item(button)
await ctx.send(embed=tradeE, view=view())
Why are you setting callback inside the callback lmao
Here's the correct version (the correct one would be to subclass View, see examples folder on the repo)
embed = ...
view = discord.ui.View()
button = discord.ui.Button(...)
async def callback(self: discord.ui.Button, inter: discord.MessageInteraction):
...
button.callback = callback
view.add_item(button)
await ctx.send(embed=embed, view=view)```
what
Exefinix do u think u could help me make finish the welcoming off or nah
Then what should I do
@client.command(aliases=['StartSpam'])
async def Spam(ctx, amount=20):
amount = amount
if amount > 500:
await ctx.send('Cannot Spam more than 500 times at once!')
if ctx.author.id == (f'625025751413948436'):
for x in (n+0.4 for n in range(20)):
await ctx.send(f'Spam')
else:
await ctx.send('Your not Clicks!')``` now its sending both "Your not Clicks!" & its spamming, also how do I make it spam the amount I inputed?
how to check who pressed button ds_components?
Idk that library, but it should have a callback somewhere
Your bot is going to get rate limited + spamming ppl is against tos last I checked
its in a private discord ;-;
Playful or not , they know
me and my friends are doing a challenge
Yea so was mine
๐ what is that for loop
range returns ints not floats
why even add
?
help me in #help-peanut
how do i make a bot send a message when a button has been pressed 2 times?
make a count variable and pass it as parameter to button callback
is there any examples?
- A member joins a voice or stage channel.
- A member leaves a voice or stage channel.
- A member is muted or deafened by their own accord.
- A member is muted or deafened by a guild administrator
Beside the mentioned actions above what other things can trigger on_voice_state_update
hunter's answers do be based
Nvm

Prolly all those events and the vice versa of those, like when the member is unmuted, undeafened, also when the person changes VC(?)
That makes sense. Thanks.
Iโm trying to create a daily command for my economy bot in discord.py and I want it to reset the daily at 00:00 utc everyday how would I do that?
class _(ui.View):
def __init__(self):
self.count = 0
@ui.but...
async def __(self, button, inter):
if self.count >= 2:
return await inter.response.send_message(...)
self.count += 1
i may have messed up the indents
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Need help with this
there is the answer..
and the datetime module
Tasks loop?
oh great, thanks
Bruh click the link to the documentation, it is all written 
Ok ok sorry
loop creates a function which will be executed every amount of time or in a specific moment of the day
Ok Ty
@manic path here's the discord docs for the event- https://discord.com/developers/docs/topics/gateway#voice-state-update
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Oh. Thanks! Really apprecieate it
but i cant await it outside a function
then await it inside an async function
wait... can i do them in on_ready
dont
it'll raise an error anyways, since, the on_ready event is triggered multiple times and randomly while the bot is running, it'll raise the Extensions already Loaded or something error
alright then how
I think that is time to upload my basic bot setup to github 
Best of luck
you have two options, either subclass or run the bot using start
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self):
super().__init_(command_...)
async def setup_hook(self): #this function will be triggered automatically on startup and before any event is dispatched, you DO NOT have to run it explicitly
await self.load_extension(...)
await do_more_things_if_required()
or or
import asyncio
async def main():
async with bot:
await bot.load_extension(...)
await bot.start("token") #use this function instead of "bot.run()"
asyncio.run(main())
The second method does not require sub-classing the Bot class and can be used directly instead of simply doing bot.run(), you can create a main function with all your async functions and await bot.start which works the same as bot.run() but recommended to use if in-case bot.run gets deprecated in the future updates
how to check who pressed button discord_components?
loading cogs?
res = await bot.wait_for(...)
res.user #<- is the "who" who pressed the button
yeah
Can we have slash command names capitalized and stuff
All works now
I've only to upload it xD
u can make an async function to load all ur cogs and run the function in async with bot
It will be handly for me expecially so maybe i will stop rewriting my setup everytime
Hello Asher
hello
I did the same thing ๐
My bot works now all good
glad to hear that ๐
Oh ok but I was actually scared by your message like WHAT WHY CAPS!!!
what?
lmao, I didnt even realize my caps lock was on
oh nvm
BTW are you rick ashley?
Welcome system :/
lmao who is that?
Rick Astley
Wait you don't know rick ashley?
yeah i saw
wtf
singer
yeah i just googled
Astley* with a "t", thanks
Oh nvm
is there a way to call a command from within a function? i have a command that creates a new instance of my 'game', effectively resetting all the variables. i dont know how to call it tho
How can we get auto complete in slash command's itner?
i want to be able to type 'restart' and itll loop back and create a new instance
Like what is the type hint?
yeah u can
how
u can even call a command in another command just do await command_name(*kwargs)
???
alr
normally commands in discord just take parameters from users so u just gottad add your own in the code
can anyone help me with pytube?
I believe not
yes you can call functions within functions
That one there was a violation
can u clarify
Personally I would not have it
I need help developing a set welcome message command
@stone beacon how did yr exam go
quick question
how do I make my bot reply if it gets mentioned?
like, mentioned only
User: @ bot
Bot: why you mentioned me
It's starting in 2h 35mins
whats the exam about?
Best of luck!!!
my code is a peace if shit?
face it and ace it uwu
Chemistry
๐คฃ why did you say this
tyty
Ofc
its peaceful
lmao
hmm
good luck haha
you should enable your intents
can someone help me lol
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@carmine hearth
hi
https://github.com/Tvrsier/BaseBot
If someone needs a basic bot setup, serve yourself 
Base bot setup for discord.py and relative forks. Contribute to Tvrsier/BaseBot development by creating an account on GitHub.
f||uck|| this shit i'm out
damn
i need a welcome message xd
how do i make it disable all the buttons in that view when i interact with one button? i tried it this way but it doesnt work```py
button1 = [x for x in self.children if x.custom_id == "decline_trade"][0]
button1.disabled = True```
This hurts, having this class test(Cog): instead of uppercase Test
Literally why its not registering this simple command?
class ExtensionCommands:
@ client.slash_command(name='load', description='Loads an extension, only for the owner.')
async def load_cmd(inter: disnake.AppCommandInter, extension: str):
if inter.author.id == 980730313011507220:
try:
client.load_extension(f'Extensions/{extension.lower()}')
await inter.response.send_message('Successfully loaded extension!')
return
except:
await inter.response.send_message('Cannot load extension. The extension does not exist or its already loaded.', ephemeral=True)
return
else:
await inter.response.send_message('Only the bot\'s owner can load or unload extensions.', ephemeral=True)
well children returns all the items in the view
Man this is old like ages who knows why i didn't put the upper case there
shall i add the other custom_id aswell?
Wait... dont say we can't use bot's slash commands in browser?
Just iterate over it, type check if the item is a Button with isinstance() and disable it
Can we?
what do this command?
Now i made it uppercase
how does this thing work again lmao I do not use this bot
whart
!d bool
class bool([x])```
Return a Boolean value, i.e. one of `True` or `False`. *x* is converted using the standard [truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). If *x* is false or omitted, this returns `False`; otherwise, it returns `True`. The [`bool`](https://docs.python.org/3/library/functions.html#bool "bool") class is a subclass of [`int`](https://docs.python.org/3/library/functions.html#int "int") (see [Numeric Types โ int, float, complex](https://docs.python.org/3/library/stdtypes.html#typesnumeric)). It cannot be subclassed further. Its only instances are `False` and `True` (see [Boolean Values](https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values)).
Changed in version 3.7: *x* is now a positional-only parameter.
Achievement unlocked: inner peace
I am on browser btw
what do this code?
more like its invalid
ok
would this work?
button1 = [x for x in self.children if x.custom_id == "decline_trade"][0]
button1 = [x for x in self.children if x.custom_id == "accept_trade"][0]```
i dont understand this
nope:)
yes it will
it will disable all the buttons?
no?
it will error if no custom_id matches
and you index the list
!d IndexError
exception IndexError```
Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised.)
im trying to disable both buttons using their custom_id when i react with either button
How can I send a custom error into the channel when someone is not filling out arguments on a command?
wtf why isn't anyone helping me
!d discord.ext.commands.MissingRequiredArgument
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
I am sure my code just have a small problem
class ExtensionCommands:
@ client.slash_command(name='load', description='Loads an extension, only for the owner.')
async def load_cmd(inter: disnake.AppCommandInter, extension: str):
if inter.author.id == 980730313011507220:
try:
client.load_extension(f'Extensions/{extension.lower()}')
await inter.response.send_message('Successfully loaded extension!')
return
except:
await inter.response.send_message('Cannot load extension. The extension does not exist or its already loaded.', ephemeral=True)
return
else:
await inter.response.send_message('Only the bot\'s owner can load or unload extensions.', ephemeral=True)
Help me plsss
Its not loading the slash command
It takes time for those commands to sync
Now how do I use that?
I don't really understand, do I put it into the command class or out of it
do you have a example
doesn't matter, just pass the guild_ids kwarg in the decorator and it'll come up way faster
you're talking about error handling
yep
which is what I ALREADY linked you yesterday....
#discord-bots message
wait what
I cant remember asking that lo
oh yeah that was at 4am while I was on 5 red bulls, remember
I passed test guilds in the InterectionBot.
from matplotlib import pyplot as plt
import numpy as np
nov = int(input("enter number of values"))
initial = 1
cars = []
while initial<=nov:
print("enter the value to append")
apen = input()
cars.append(apen)
initial = int(initial+1)
nop = int(input("enter number of values for pie chart"))
initials = 1
data = []
while initials<=nop:
print("enter the value of pie chart to append")
apens = int(input())
data.append(apens)
initials = int(initials+1)
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
plt.savefig("chart.png")
Can anyone help me to covert it to discord command
Which takes input from user
!d discord.Client.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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Oh my god its finnnnnnnnnnnally registered
what do this code?
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
group = app_commands.Group(name="hyb", description="-")
@app_commands.command(name="test1")
async def command(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello!", ephemeral=True)
@group.command(name="sub")
async def test(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello!", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
print('hybrid')
is this correct?
yeah seems fine
yeah the ids in a list
@bot.command()
async def help(ctx):
await ctx.send("ะะฐะฟะธัะธัะต o!ping ะธ ะฑะพั ะพัะฒะตัะธั pong. ะะฐะฟะธัะธัะต o!botping ะธ ะฑะพั ะฟัะธััั ัะฒะพะน ะฟะธะฝะณ ะฒ ัะธััะฐั
(ั ะฝะต ะทะฝะฐั ะทะฐัะตะผ ััะพ ะฝะพ ััะพ ัะตััะพะฒะฐั ััะฝะบัะธั).")
is there any other way instead of me addind every server ids in a list ?
dont do this and this is not required def pingg():
return int(bot.latency*1000)
also dont forget to add intents
subclass the help command
Does anybody know why this appears every time I start my Bot?
DistributionWarning: discord is installed which is incompatible with nextcord. Please remove this library
by using `pip3 uninstall discord`
warn(message, DistributionWarning, stacklevel=0)
discord and nextcord are incompatible together, so it is suggested to uninstall discord.py
even when I do it still pops up, so is there like any traces of the module maybe?
you can check by doing pip freeze in your terminal
no?
I mean, I have all of 'em installed and it works out fine
- discord.py
- disnake
- nextcord
- hikari
it literally say that in a error by nextcord
no comments
Yup, they did it recently, like with the January release
it's something related only to nextcord
weird
they added a bit of racisms 
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("what")
I have added this to my code but other commands wouldnt work
yep its still there even tho I uninstalled
either change the decorator instead of client.event to client.listen() or add a await client.process_commands(message) at the end of your on_message
everybody has two sides
Next time you're posting code make sure to have it look like this
``py
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("what")
!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.
change .event to .listen()
Yeah, we're binary 
got you
just what I expected from the type of people here
also, client.user.mentioned_in = bad
its still there so what now?
I'm offended now 
whats the point of lying so uhh anyways
uhm... try it again? uninstall it manually?
dont uninstall it manually
ok but if i wirte "hello {and tagging him}" he will still responed. how can i change it
you probably have multiple versions of python installed
I don't lie
yes, it will still respond
tried that somewhen else and It messed up some healthcheck thingy
was talking about me, but sure
so?
i want it to responed only if hes tagged with no other words How can i do it
you can check if the bot's mention is the message.content
if bot.user.mention == message.content
what even is the error....
Sad 
@wet crystal
@slate swan
Honestly Freyln it could be everything
you could using a venv or smth
broooo
we can't know it 
I couldn't know that
pip3 uninstall <library>
pip3 freeze
and yes, venvs are really handy uou should be using them
!venv
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
tbh thats one of the dumbest cases of how to upvote your library lol
Once you will start work you will understand how useful venvs are 
well, they are quite useful, better use conda though
ew
Companies doesn't like this

....?
though pipenv works better
i don't think everyone would be comfortable with conda, while venvs is something any general python user would use
@ban.error
async def ban_error(error, ctx):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("cant ban the air...")
if isinstance(error, commands.UserNotFound):
await ctx.send("user not found")
this doesnt work
idk why tho
it seems all good, but first of all change the second if into an elif
yea but still wouldve worked
how do I use @command.error with multiple arguments?
then add an else and write this:
else:
print(f"Ignoring exception in command: {ctx.command}", file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
Then look if there is some error in the console
You will need to import sys and trackeback
error handler takes only error and context
does else:
raise error not work?
So how do can I handle errors for multiple args?
Uhm usually we do this so we can trace which command raised the error
still doenst work
in that case is useless because is an handler for a single command but in on_error event is more usefull
wdym?
then the decorator or the function are not being resolved
oh i know that just asking since in his case we are just trying to see if there is some error which was not defined in the if statements
lets say the first arg was found and is valid but the second is missing, how can I handle that?
MissingArgument
!d discord.ext.commands.MissingRequiredArgument
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
The arguments that are missing are stored in this class, which is your error
something similar ur intellisensor or linter comes to play here
but that will assign also if the first one is missing so I cant really go individual on the response
Hey'
it is passed automatically when the error is raised
yes
i need help making welcome messages lol
in your error handler you can do error.param and get that parameter
@shrewd apex
?
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome TEXT FROM wm where guild_id = ?", (ctx.guild.id, ctx.channel.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id))
await db.commit()
await ctx.send(f"Welcome message has been set!")
return
if data is not None:
await cursor.execute("SELECT welcome TEXT FROM wm WHERE guild_id = ?", (ctx.guild.id,))
data3 = await cursor.fetchone()
result = data3[0]
await ctx.send("There is no welcome message currently set.", delete_after = 10)
return``` i just coded this , do u think it will work
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id))
dont u need to insert 3 values?
oh ye
data3 = await cursor.fetchone()
result = data3[0]
why fetch again u already have fetched it
shall i delete it
if not data is more pythonic and u can just do return await ctx.send()
idk what would be the 3rd value
this line is not required since prev if statement prevents this situation already
so what do i remove again
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome TEXT FROM wm where guild_id = ?", (ctx.guild.id, ctx.channel.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id))
await db.commit()
await ctx.send(f"Welcome message has been set!")
return
if data is not None:
await cursor.execute("SELECT welcome TEXT FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await ctx.send("There is no welcome message currently set.", delete_after = 10)
return
``` current code
idk either i guess their input welcome message or welcome message image link
i just put ctx.welcome
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome TEXT FROM wm where guild_id = ?", ctx.guild.id)
data = await cursor.fetchone()
if not data:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", ctx.guild.id, ctx.channel.id, 'xyz')
await db.commit()
return await ctx.send(f"Welcome message has been set!")
msg = await cursor.execute("SELECT welcome TEXT FROM wm WHERE guild_id = ?", ctx.guild.id)
mesg = await cursor.fetchone()
if not mesg: return await ctx.send("There is no welcome message currently set.", delete_after = 10)
return await ctx.send(f"welcome message is {mesg}")
that should be all idk abt the database part tho i dont use aiosqlite
id = ctx.guild.id would make my day
mesg and msg ??
guuuuuuuuuuuuys
checks if the new msg or the current message is empty or not
i have indent errors thats why im curious
is this good?
i want to die:(
y?
nope
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
better?
yeah
K
@commands.Cog.listener()
async def on_member_join(self, member):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (member.guild.id,))
data = await cursor.fetchone()
if data is None:
return
else:
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (member.guild.id,))
channel_id = await cursor.fetchone()
channel = channel_id[0]
final = self.client.get_channel(channel)
await final.send("Welcomes activated!")
else:
return```btw anything here i gotta change
or am i good here .
Is it possible to add a Dismiss this message button like Clyde has?
make ur command ephemeral
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: welcome``` next error
thats a db problem
hmm ok
u havent created the table properly or using the wrong column name
await cursor.execute("CREATE TABLE IF NOT EXISTS wm(guild_id INTEGER, channel_id INTEGER, welcome TEXT, leave TEXT)")```
idk
await cursor.execute("CREATE TABLE IF NOT EXISTS wm(guild_id INTEGER, channel_id INTEGER, welcome TEXT, leave TEXT)")``` any ideas
# instead of this
UKTIME = await sessions.get("https://worldtimeapi.org/api/timezone/Europe/London").json()
# change it to this
resp = await sessions.get("https://worldtimeapi.org/api/timezone/Europe/London")
UKTIME = await resp.json()
# or even better
async with sessions.get("https://worldtimeapi.org/api/timezone/Europe/London") as resp:
UKTIME = await resp.json()
check if the table was created
nah it wasnt created
Yeah you need to change it to what I showed
Because both .json() and get() are coroutines but u are only awaiting one of them
yeah so u arent creating the table do that on ready and make sure ur connected with the db when doing so
Well I can show coe
code
nah i need to go to sleep soon and my heads not working very well rn
I was testing my dropdown menu and got this error
by looking at it i deduced that it is connected to this callback class but i don't know the issue
Oh well thanks for all help maybe we can try again tommorrow
here is the callback class
async def callback(self, interaction: disnake.MessageInteraction):
x = self.values[0]
x = x - 1
user_id = id_many[i]
user : discord.user
for ban_entry in banned_users:
user = ban_entry.user
if user_id == user.id:
return
await ctx.guild.unban(user)
I am using disnake
from where does ctx come in in an interaction wont it give not defined error?
I forgot to put it but still it is about the values part from what i have read from this error
yes
I fixed ctx part and still got same error
user_id = id_many[i] 'i' is not defined
it is definded in earlier part of command
here is whole command
https://paste.pythondiscord.com/ovituqibor
@shrewd apex do u know any typescript support servers ?
Like related to this sort of
whats the issue...?
How can I make a Interaction on a command which deletes the message?
huh?
I wanna make a horse race discord command. How do i give each of the 6 horses a position, which ofc cant have duplicates?
!random.sample
!d random.sample
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
!e
from random import sample
c = [1, 2, 3, 4, 5, 6, 8, 7, 10, 11, 9, 0]
print(sample(c, k=6))```
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[6, 7, 10, 8, 9, 5]
yeah, it says unique
interesting
!e
from random import sample
c = [1, 2, 3, 4, 5, 6, 8, 7, 10, 11, 9, 0]
print(sample(c, k=6))โ
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[0, 7, 8, 6, 5, 3]
Just curious lol
curious about?
where do you guys reccomend that i store my bots custom status that changes randomly?
change the presence in a for loop
a list
button can use all members... how to fix? I want the button to be used only by people with the role roleforum or rolecur
if interaction.user == ctx.author
if the callback is in a command or just pass the user as a parameter
guys
import discord
from discord.ext import commands, tasks
import asyncio
from config import token
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True
client = commands.Bot(command_prefix = '+', intents=intents)
@client.event
async def on_ready():
print("HEHE IM READY")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="You're on a cooldown!", color=discord.Color.blue())
cd = round(error.retry_after)
hours = str(cd // 3600)
minutes = str(cd % 60)
embed.add_field(
name="\u200b",
value=
f"you cant use dailyspin again\n Wait for `{hours} hours {minutes} minutes`"
)
await ctx.send(embed=embed)
else:
raise error
async def main():
async with client:
await client.load_extension('cogs.rewards')
await client.start(token)
print(client.db)
asyncio.run(main())``` anything wrong here ? i have a cog also but the command doesnt respond
whats the cogs code
import discord
from discord.ext import commands
import random
class rewards(commands.Cog):
def __init__(self, client):
self.client = client
print("hello")
@commands.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def dailyspin(ctx):
responses = ['100 million coins',
'10 packs of choice',
'50 million coins',
'nothing',
'1 billion coins',
'5 packs',
'5 modded packs',
'15 packs',
'1 coin',
'55 coins',
'12 million coins']
response = random.choice(responses)
embed=discord.Embed(title="Daily Spins!", color=0xff0000)
embed.add_field(name='You Won: ', value=f'{response}', inline=False)
embed.add_field(name='How to claim?: ', value=f'Create a ticket', inline=True)
await ctx.send(embed=embed)
async def setup(client):
await client.add_cog(rewards(client))```
indent the command
raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)')
TypeError: Command signature requires at least 1 parameter(s)``` @flint isle what about this
import discord
from discord.ext import commands
import random
class rewards(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def dailyspin(ctx):
responses = ['100 million coins',
'10 packs of choice',
'50 million coins',
'nothing',
'1 billion coins',
'5 packs',
'5 modded packs',
'15 packs',
'1 coin',
'55 coins',
'12 million coins']
response = random.choice(responses)
embed=discord.Embed(title="Daily Spins!", color=0xff0000)
embed.add_field(name='You Won: ', value=f'{response}', inline=False)
embed.add_field(name='How to claim?: ', value=f'Create a ticket', inline=True)
await ctx.send(embed=embed)
async def setup(client):
await client.add_cog(rewards(client))``` i think so
since its in a cog
ok'
it still doesnt work the command
... 1 sec
Hey, so I made a new cog file called "chatbot.py", here's the code :
import discord
from discord.ext import commands
def setup(bot):
bot.add_cog(ChatboxIA(bot))
class ChatboxIA(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def chatbot(self,ctx):
await ctx.send("test")
I made a similar base structure for my other codes. I've a command that load up commands from cogs by loading + the name of the cog. Example :
v.load mod load the mod.py file commands. So I tried to load this new cog, but for some reasons everything I tried return me this : Extension 'chatbox' could not be loaded.
Do you guys know why this file cannot be loaded ?
@warped mirage you need self, ctx
move the setup function to the bottom
i added
errors?
nope
async def dailyspin(self, ctx):
yes i have that
when i added self it worked fine for me
import discord
from discord.ext import commands
import random
class rewards(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def dailyspin(self, ctx):
responses = ['100 million coins',
'10 packs of choice',
'50 million coins',
'nothing',
'1 billion coins',
'5 packs',
'5 modded packs',
'15 packs',
'1 coin',
'55 coins',
'12 million coins']
response = random.choice(responses)
embed=discord.Embed(title="Daily Spins!", color=0xff0000)
embed.add_field(name='You Won: ', value=f'{response}', inline=False)
embed.add_field(name='How to claim?: ', value=f'Create a ticket', inline=True)
await ctx.send(embed=embed)
async def setup(client):
await client.add_cog(rewards(client))``` hmm is this correct?
@warped mirage do you have an error handler?
@commands.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
async def dailyspin(self, ctx):
responses = ['100 million coins',
'10 packs of choice',
'50 million coins',
'nothing',
'1 billion coins',
'5 packs',
'5 modded packs',
'15 packs',
'1 coin',
'55 coins',
'12 million coins']
response = random.choice(responses)
embed = discord.Embed(title="Daily Spins!", color=0xff0000)
embed.add_field(name='You Won: ', value=f'{response}', inline=False)
embed.add_field(name='How to claim?: ', value=f'Create a ticket', inline=True)
await ctx.send(embed=embed)
``` that worked for me
import discord
from discord.ext import commands, tasks
import asyncio
from config import token
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True
client = commands.Bot(command_prefix = '+', intents=intents)
@client.event
async def on_ready():
print("HEHE IM READY")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="You're on a cooldown!", color=discord.Color.blue())
cd = round(error.retry_after)
hours = str(cd // 3600)
minutes = str(cd % 60)
embed.add_field(
name="\u200b",
value=
f"you cant use dailyspin again\n Wait for `{hours} hours {minutes} minutes`"
)
await ctx.send(embed=embed)
else:
raise error
async def main():
async with client:
await client.load_extension('cogs.rewards')
await client.start(token)
print(client.db)
asyncio.run(main())``` is this correct?
it must be something
Still don't work
Or I did it wrong ?
import discord
from discord.ext import commands
class ChatboxIA(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def chatbot(self,ctx):
await ctx.send("test")
def setup(bot):
bot.add_cog(ChatboxIA(bot))
import discord
from discord.ext import commands, tasks
import asyncio
from config import token
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True
client = commands.Bot(command_prefix = '+', intents=intents)
@client.event
async def on_ready():
print("HEHE IM READY")
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="You're on a cooldown!", color=discord.Color.blue())
cd = round(error.retry_after)
hours = str(cd // 3600)
minutes = str(cd % 60)
embed.add_field(
name="\u200b",
value=
f"you cant use dailyspin again\n Wait for `{hours} hours {minutes} minutes`"
)
await ctx.send(embed=embed)
else:
raise error
async def main():
async with client:
await client.load_extension('cogs.rewards')
await client.start(token)
print(client.db)
asyncio.run(main())``` @flint isle is this correct
did you copy and paste the command i sent for you
ye
@commands.Cog.listener()
async def on_ready(self):
print('Cog Loaded')
insert that same indention as the command and then re run your code and look for cog loaded in the terminal
cog has loaded

