#discord-bots
1 messages · Page 265 of 1
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | l
@topaz gust :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print hi
003 | ^^^^^^^^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
@topaz gust :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(Hi)
004 | ^^
005 | NameError: name 'Hi' is not defined
#bot-commands
!e print "Hi"
@topaz gust :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print "Hi"
003 | ^^^^^^^^^^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
@topaz gust please experiment with the bot in #bot-commands
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
is there a way to sync command tree not on_ready
yes you can
how
Just call .sync somewhere else
person im working for said "dont do it on rebbot"
Like in command or in setup hook
Can be
idk he said something like "please dont tell me you sync on reboot"
which is what i normally do
so idk what else he wants me to do
Tks u
in general you should avoid making unnecessary API calls and afaik the main concern with syncing on startup is hitting the rate limit
(not the 200 maximum commands per day since existing commands dont count towards that, but the dynamic rate limit which appears to be 2/30s at the moment)
plus if you use dpy's extension system for hot-reloading, having a command to re-sync after changing your slash commands is probably a bit more convenient than entirely restarting your bot
if you happen to be using the jishaku cog, that comes with a sync command too
from nextcord.ext import commands
import nextcord
import asyncio
class CreateTicket(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Create Ticket", style=nextcord.ui.ButtonStyle.blurple, custom_id="create_ticket:blurple")
async def create_ticket(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
await interaction.response.send_message("Ticket being created. . .", empheral=True)
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreateTicket())
self.persistent_views_added = True
print("Persistent views added")
print("Bot is ready | Logged in as {self.user}")
bot = Bot(command_prefix=',', intents=nextcord.Intents.all())
@bot.command()
@commands.has_permissions(manage_roles=True)
async def setup_tickets(ctx: commands.Context):
embed = nextcord.Embed(title="Create a ticket!", description="Click the 'Create Ticket' button to below to create a ticket. Staff will be with you soon.")
await ctx.send(embed=embed, view=CreateTicket())
bot.run('')```
Anyone help?
!d nextcord.ButtonStyle
class nextcord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
anyone know how to make a bot follow announcements and send them on your server?
I changed to style=nextcord.ui.ButtonStyle.primary and it doesnt work
You can manually do that
no I want it to follow a websites announcements. Like if I want youtube announcements
Oh
Api
It's not part of the ui subpackage... Check the docs link I sent
im new to coding so idk how to do that
I realized I removed ui and got this
So you want ur bot to send like youtube posts to a certain channel??
yes... but not youtube. video games
Yeah do what it says
Having both libraries can cause conflicts
I already did though
nevermind I uninstalled py instead of py-cord
which i need to uninstall both just got mixed up
you uninstalled python itself 😨
I didnt
It works now I will be here if anything comes up
do you know how to make a bot send video game posts to my server?
Mayhaps
idk what that is
Perchance, possibly 🥸
But that's why the help channels exist, so you don't have to rely on one specific person to help you 🦆 so ask away
whats mayhaps
maybe + perhaps lol
Tell you what
this
That's way too vague of a question
you know how some servers have a bot send youtube announcements on their server?
yes
What announcements
video game
To automatically announce when a YouTube channel uploads? You'll need some sort of YouTube api wrapper or to write one yourself then
try looking for one on Google and start with their documentation then, I've never done this before so I wouldn't be able to recommend anything specific
@bot.event
async def on_member_update(before, after):
if after.bot:
return
if before.activities == after.activities:
return
# Define required_activity
userHasActivity = False
for activity in after.activities:
if isinstance(activity, discord.CustomActivity) and str(activity) == '/bloodthirsty':
userHasActivity = True
role_id = 1126319070682292284
role = discord.utils.get(after.guild.roles, id=role_id)
if userHasActivity:
await after.add_roles(role)
else:
await after.remove_roles(role)
print("person repping")``` if someone has /bloodthirsty bot gives user role
is there a error
no, the bot isnt giving the person the role and it has max perms
check terminal
should show a error
2023-07-06 01:25:32 INFO discord.client logging in using static token
* Serving Flask app ''
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:8080
* Running on http://172.31.196.3:8080
Press CTRL+C to quit
172.31.196.1 - - [06/Jul/2023 01:25:32] "OPTIONS * HTTP/1.1" 404 -
172.31.196.1 - - [06/Jul/2023 01:25:32] "GET / HTTP/1.1" 200 -
172.31.196.1 - - [06/Jul/2023 01:25:33] "GET / HTTP/1.1" 200 -
2023-07-06 01:25:33 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 5a4f3dbda0d69f19f5ae22f2d1f4387f).
Everything's all ready to go~```
thats what i get
it says everything is working fine
with no error I wouldn't want to guess why the bot is not giving the role maybe someone else would though
do you know anyone that could help me?
I do, but I will not ping
you can create a python help channel #1035199133436354600
Can you show us your intents?
import discord
from discord.ext import commands
from keep_alive import keep_alive
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=',' ,intents=intents)
client = discord.Client
client = discord.Client(intents=discord.Intents.default())
intents = discord.Intents.default()
intents.message_content = True```
what do i have to remove
okay i removed the client
What's your code look like now?
import discord
from discord.ext import commands
from keep_alive import keep_alive
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=',' ,intents=intents)
intents = discord.Intents.default()
intents.message_content = True```
import discord
from discord.ext import commands
from keep_alive import keep_alive
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=',' ,intents=intents)
intents = discord.Intents.default()
intents.message_content = True
@bot.event
async def on_ready():
print("Everything's all ready to go~")
@bot.event
async def on_member_update(before, after):
if after.bot:
return
if before.activities == after.activities:
return
# Define required_activity
userHasActivity = False
for activity in after.activities:
if isinstance(activity, discord.CustomActivity) and str(activity) == '/bloodthirsty':
userHasActivity = True
role_id = 1126319070682292284
role = discord.utils.get(after.guild.roles, id=role_id)
if userHasActivity:
await after.add_roles(role)
else:
await after.remove_roles(role)
print("person repping")````
what attribute/function is used to change the nickname of the user?
its supposed to give a user a role if they have /bloodthirsty in their status
!d discord.Member.edit iirc
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
There's a nick kwarg
ty
Check if the event is actually being triggered
how would i do that?
Just a print statement in the function that's not inside any conditionals or control flow
put some print statements throughout to see if each line executed as intended
does this change if im using replit?
maybe, maybe not. replit is just kinda bad and unreliable
It shouldnt
i understand that but my os is wierd and wont install pip on vscode
You should probably be debugging that instead
maybe worth its own help post then, I've not heard anything good about replit
Anything good about replit
🥴
Does the bot add the role now?
im making reaction button role on / command and everything I did theirs no error. But when it runs the command doesnt show up
class SelfRoles(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="fortnite", style=discord.ButtonStyle.blurple)
async def blue_color(self, interaction: discord.Interaction, Button: discord.ui.Button):
blue_role = discord.utils.get(interaction.guild.roles, name=fortnite)
@commands.command(name="reactionroles")
async def self_role(interaction: discord.Interaction):
await interaction.response.send_message(content="Choose your favorite games", vie=SelfRoles())
await interaction.user.ad_roles(1126332842591400027)```
Your button isn't in the view class
spelling error
and what catlover said
await interaction.user.ad_roles(1126332842591400027)
should be
await interaction.user.add_roles(1126332842591400027)
still didnt work
That's not helpful
^ @ornate sapphire
It didn't work doesn't explain your problem
the bot runs successfully
but when it comes to doing the /reactionrole
tthe slash command doesn come up
?
is their a way I can turn this into an on message
instead of slash command cuz those dont work for me
Yes using views
I don't know about you, but commands.command isn't for creating slash commands
It's for prefix commands
then how do I do slash command
been trying for so long
.-.
not making fun of you xD
so do you want your button to a slash command or a normal command
for me command
then command
yes
class SelfRoles(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="fortnite", style=discord.ButtonStyle.blurple)
async def blurple_color(self, interaction: discord.Interaction, Button: discord.ui.Button):
blurple_role = discord.utils.get(interaction.guild.roles, name=fortnite)
@commands.command(name="reactionroles")
async def self_role(interaction: discord.Interaction):
await interaction.response.send_message(content="Choose your favorite games", view=SelfRoles())
await interaction.user.add_roles(1126332842591400027)```
everything runs fine
but I cant do the command
yes
also cogs might not be loaded
Your button is still outside of the view
IDK WHA THAT MEANS
import discord
import os
import random
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_ready():
activity = discord.Game(name=f"Call of Duty Black Ops III", type=2)
await client.change_presence(status=discord.Status.online,
activity=activity)
class SelfRoles(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="fortnite", style=discord.ButtonStyle.blurple)
async def blurple_color(self, interaction: discord.Interaction, Button: discord.ui.Button):
blurple_role = discord.utils.get(interaction.guild.roles, name=fortnite)
@commands.command(name="reactionroles")
async def self_role(interaction: discord.Interaction):
await interaction.response.send_message(content="Choose your favorite games", view=SelfRoles())
await interaction.user.add_roles(1126332842591400027)
client.run(why)```
Have you learned about indents and how it works in Python yet?
yes
Your blurple_color is indented improperly, so it's outside of the SelfRoles class
discord.py isn't picking it up because of that
Buttons need to be inside the view class (SelfRoles in your case) for discord.py to pick it up
Also you're not in a cog so @commands.command(...) isn't going to work
so how do I fix all that
indent
By indenting the button function so it's within the class
Yeah and wouldn't @commands.command() be @bot.command() since this is not a cog
Yup
@commands.command(name="reactionroles")
async def self_role(interaction: discord.Interaction):
await interaction.response.send_message(content="Choose your favorite games",
view=SelfRoles())```
is this the right indent?
oh wait wrong one
.
@discord.ui.button(label="fortnite", style=discord.ButtonStyle.blurple)
async def blurple_color(self, interaction: discord.Interaction, Button: discord.ui.Button):
blurple_role = discord.utils.get(interaction.guild.roles, name=fortnite)```
thiiiiiis is definititely right
right?
Hard to tell without context
The indentation of the function only matters within the context of the class
Ok where are you giving the role to the users?
As far as i can see you are only getting the role
indent your button function
It doesn't seem like you changed anything?
by pressing tab
the async def?
Your button function (blurple_color) is still unindented, and, therefore, not inside the view class (SelfRoles)
no @discord.ui.button
The whole function, including the decorator
@ornate sapphire https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py check out this example and see how they did it
do same for @client.command
No, don't do that
??
Indentation on line 38 is inconsistent as well
fixed it
Can you paste your whole code now?
Oh an button might not work as you want it to
What's the fortnite variable? You didn't define it anywhere
Then make it a string
its yellow
i thought it would have to be indented as well I guess not, my bad 😅
.
no that's definetely an error color (red/orange)
You're referencing a variable that does not exist
Make it a string zzz
Okay, but your callback doesn't actually do anything
It just finds the role called "fortnite" and then gets garbage collected immediately after
You are only getting the role but not giving it
That will give the role on command use not button press
sorry I meant the await at the bottom
😁
We talking about that
oh
Instead move it inside the button
Green runs on button press and blue runs on command
And instead of role id put blurple_role there
Sort of but add_roles doesn't accept a plain ID
It accepts a discord.Role object (which you already have)
ofc it doesnt
yay
But you still aren't using it
?
Remove the id inside add_role and use the blurple_role variable
You're basically saying, "find a role named "fortnite", then ignore that role object. Instead, add this other role with ID instead"
Yup
yay
Now try running your bot
everything ran
but how do I run the command in my server
!reactionroles?
no command called "reactionroles"
Can u send an ss of the help command output
Can u tell what is on line 36
oh
Not interaction
I did ctx.response.send_message() and it said ctx was undefined
Make it something like this
async def ping(ctx):
await ctx.send('Your_message_here',view=....)
This is an example modify your code accordingly
Remove the interaction
await ctx.response.send_message() should be await ctx.send
oh
You don't need those that's what throwing the error
You checked my example?
you need to add ctx
Then u should know why
Yeah
now can I run it?
should work
IT WORKED
accept when I clicked the button it said interaction faled
I think thats why
do I change this to
blurple_role = discord.utils.get(role_id)```
???
You can try
See if it gives an error
The blurple_role variable was None
?????
What's confusing about it
The bot didn't find any role called fortnite in the guild u used the command
do capitals matter?
Yes?
Yes
Why wouldn't it
so...
wheres the name?
So u switched it to id?
you told me too
I never did
so I switch it back to name?
Yeah
so interaction.user.add_roles(name="Fortnite")
Use the exact name of the role you have in the guild
do I need to say name= or no?
Not here in discord.utils.get
Just make it like it was befor
then can I run it again?
Yeah if you have the role name correct
interaction still failed...
That didn't explain why
The error? And your code?
Then try defering the interaction
That wouldn't help
OH WAIT
Show your code then
it did give me the code
Wait u are the server owner?
just when I click it it says interaciton failed... but it gave me the role
Yeah need to defer it then
how
Then why get the role?
Because they called the add_roles?
Yeah and defer will stop that interaction failed?
it worked... all I need to do is fix the response when you click it
Then can send an ephemeral message?
@ornate sapphire try sending an ephemeral message after the add role
Check and see if that works
wahts ephemeral?
It's an arg if set to true then only the user will see the message
false=everyone sees
. . .
whereeeeee
Read the error
Check error
See it again
nop
No, it's reacionroles
ohhhhhhhhh
People really can't recall what they sent
ya it worked now
epic
Because you kept overriding previous buttons in the view
how do I NOT override it
you're using the same code for each button
The function name to be precise
Simply don't
All these buttons have the same function names, so they override eachother
oh lol
Learn Python first
change the functions
if functions are the same it will only load the first
working on itttttttttttt
The last one not first
last i mean
!e
class A:
def a(self):
print(0)
def a(self):
print(1)
A().a()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
You didn't respond to the interaction
Yeah just try sending an ephemeral response after someone clicks the button
you dont describe stuff at all
whats ephermeral
It's an arg if set to true then only the user will see the message
false=everyone sees
it was?
yes nobody described ephermal earlier
how do I do this then? and is it hard?
ephermeral=true
but where do I put it in my code
await interaction.response.send_message('your_message', ephemeral=True)```
Inside the button under the add_role line
Yeah
But you can make the message look good if u told what role you gave in the message
ooooooo
Tho the interaction failed should be solved now
it did
it was beautiful
I luv you guys sooooooo much
Nah am straight XD

would it be {mention.role}
What is mention supposed to be
Nope role.mention where role is a variable
soooooo this
await interaction.response.send_message('Success! {meantion.role} has been added to your account', ephemeral=True)```
mentioning the role wdym
dont follow what I said I was asking a question
oh
That didn't answer the question
tell me
mentioning the role the button gave
I told u already
What object is mention supposed to be
.
They're waiting for the spoon
you did?
Long ago
now that you're saying this I see why you are asking
What is it then
role
discord.Role object doesn't have an attribute called role
.-. i was talking about mentioning a role once the button is pressed
Already know
ohh

still dont know?
Just a question why are u bothering with the role.mention?
When none will get pinged
Instead you can put the role name in your message directly
lol I dont care about it
thought it was easy but dont care
Im fine with what I got
you guys helped me enough
also wouldn't recommend copying code from someone who's using cogs
if you aren't using cogs
I told it again if u noticed
lmao im so dumb
Idk what cogs is
But when I asked you way earlier you said you were using cogs
idk what that is so if I did I wasnt paying attention
.-. that's ok
sorry XD
So everything works?
ya
I switched the code from repl.it to a bot hosting website
and now its not working
well you have to do many different things then just pasting in your code for bot hosting websites
you can read the website error log
I already fixed all the errors
the indenting n stuff
no errors, but when I do the !reactionrole command
talking about the hosting errors
nothing happens
website errors
oh no cuz the oher commands work
cant help when you dont show anything and your not explaning really anything
what hosting webstire you using
Daki
see a youtube video by offical youtube for the site if there is one it may help
Is the on_ready event firing when you start the bot?
ya theirs a few videos
but its how to host it
And one more thing u changed the command name to addrole then how would it work with reactionroles
ya ik I did !addrole
lol not THAT dumb
And I don't see your on_ready event firing
There is no message here saying we have logged in
any errors
no
It just means the bot isn't ready tho it should not take long for it to get ready
also that too
ive been using the website for a while now and it never says we have logged in
after days
Yeah then it might be a hoster problem try switching to someplace else
nothing else is free
Try discloud it has a free tier
theirs like a crap ton of steps
So follow them
AWS has a free tier
Old machines also work
I have a raspberry pi hosting all my discord bot projects
robin could you help me in my help channel
Code: https://paste.pythondiscord.com/evutadasah
Errors: everyone can see tickets
Add User error
Remove User error
Hello, I'd like to create a bot that connects to a voice chat room with a command for speech-to-text and text-to-speech, where speeches will be posted in a text chat room. Which libraries do you recommend to use in Python?
Code: https://paste.pythondiscord.com/biqixumovo
Error: 👇
Your message variable from the list comprehension is unused
yea i figured it out
messages.contest typo
async def help(ctx: commands.Context):
embed = nextcord.Embed(title="Currect Commands", description="setup_ticket (sets up tickets) \n setup_role (Allows a role to see all tickets)")```
**Why doesn't this work I got no error**
What doesn't work exactly
no response from bot, no error received
I see no ctx.send in that code
oh ... i forgot to put that part e
The Code:
The Error: Traceback (most recent call last):
File "/Users/mac/Desktop/GrowBet/main.py", line 59, in <module>
@bot.is_owner()
^^^^^^^^^^^^^^
TypeError: BotBase.is_owner() missing 1 required positional argument: 'user'
Bot.is_owner is not a decorator

no
It's not a decorator
what is the decorator
try checking the docs for checks
checking rn but i couldnt find
Use the search bsr
u sure u searched is_owner?
Search for is_owner
any1?
I dont get why this is an error
commands.is_owner is the decorator
i dont know the fix to it can you enlighten me
What's the error?
your bot is undefined
@commands.is_owner()
Well you need to define the bot variable before you use it
ANYONE GONNA HELP OR NO
and u will need to await this line too
i had my bot = Bot line under my cmds
🤦♂️
await bot.load_extension?
yeas
??????????
it's event
is this inside a function?
i said if possible
you might need to put the for loop inside a setup_hook
wdym im not to fimilar with cogs
and i suggest using setup_hook for connecting to the db
ok ig chatgpt is more helpful than this channel
I see no problems
Instead of doing async setup in on_ready, or using a task which may lead to events being called before that task runs, you can overwrite Client/Bot.setup_hook.
For example:-
class MyBot(commands.Bot):
async def setup_hook(self):
print("Bot is starting")
await self.load_extension("my.extension")```
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook
so you want me to add that into my on_ready?
im confused
Why not
no don't use on_ready for events that u wan't to happen only once on startup
since on_ready can fire many times
if not self.persistent_views_added:
self.add_view(CreateTicket(self))
self.add_view(TicketSettings())
self.persistent_views_added = True
print("Persistent views added")
self.db = await aiosqlite.connect("tickets.db")
async with self.db.cursor() as cursor:
await cursor.execute(f"CREATE TABLE IF NOT EXISTS roles (role INTERGER, guild INTERGER)")
print("Database ready")
print(f"{self.user} is ready!")
print(f"Bot is ready | Logged in as {self.user}") ```
This?
update the persistent view in a wait_until_ready event
no only load extensions and db in setup_hook
yeah u did right
u need to connect to db and load extensions in setup_hook
as for updating your persistent view do that in wait_until_ready
but idk how to add all of that into my code
like
async def setup_hook(self):
#connect to the db and your for loop to load extensions here
async def on_ready(self):
await wait_until_ready()
# Your code for updating the view
self.db = await aiosqlite.connect("tickets.db")
async with self.db.cursor() as cursor:
await cursor.execute(f"CREATE TABLE IF NOT EXISTS roles (role INTERGER, guild INTERGER)")
print("Database ready")
async def on_ready(self):
await wait_until_ready()
if not self.persistent_views_added:
self.add_view(CreateTicket(self))
self.add_view(TicketSettings())
self.persistent_views_added = True
print("Persistent views added")
print(f"{self.user} is ready!")
print(f"Bot is ready | Logged in as {self.user}")
move the for loop in setup hook too
wait wait
wait u using nextcord
yup
let me check its docs for a bit
oh I should have told you, sorry
there is wait_until_ready method
i cant find it
mb its await self.wait_until_ready() since its inside a class
it seems there as an issue with your cogstickets file
uhh
import nextcord
class Tickets(commands.Cogs):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.reply("Pong!")
def setup(bot):
bot.add_cog(Tickets(bot))```
I dont see any errors here
there we have it
in latest versions u need to async every function
async def setup(bot):
await bot.add_cog(Tickets(bot))```
like this
thats strange
use disnake much better
What?
anyone use disnake library?
this?
yeah in for loop
alr
anyone know how to make modmail thing
oh ;-;
simple
Hello, I'd like to create a bot that connects to a voice chat room with a command for speech-to-text and text-to-speech, where speeches will be posted in a text chat room. Which libraries do you recommend to use in Python?
async def load(ctx, extension):
bot.load_extension(f"{extension}")
await ctx.send("Loaded cog!")```
pls help me
asking the wrong guy havent made one of those in a year or so just go back into coding
i dont know what you want me to remove thats the only word cogs i see
in this picture there is a bot.load_extension(f"cogs{fn[:-3]}") in your for loop remove the word cogs from in it
idk how u assuming that i'm saying remove from load command when i have been clearly saying for loop
Why
thats checking for a file called cogstickets when there is only tickets there
uhm
why not just tickets?
yeah works too
ok
but you will need to import that first
Then tell it to
i will look on docs
If your extension filename (fn) is from the cogs folder, you need to tell it to load them from there, like cogs.{fn}
It works just like Python import statements
if I knew how to do that
and already thought i had that in main.py
Had what
if fn.endswith(".py"):
bot.load_extension(f"{fn[:-3]}")```
And? You're telling it to load the extensions (that is from the cogs directory) from the current directory, not the cogs directory
thats not loading the cogs folder?
No
why not?
Because you're telling it to
..??
What don't you understand
i understand what you're saying but dont know how to fix
Just think it as this
bot.load_extension("ext") # <-- it will try to load an 'ext' extension from the current directory
bot.load_extension("extensions.ext") # <-- it will try to load an 'ext' extension from the 'extensions' directory (or folder)
so bot.load_extension(f"{fn[:-3]}") is not loading the cogs? or what
If you have them in the current directory, then probably
ill try and fix later i have no idea how to fix this
Just change it to bot.load_extension(f"cogs.{fn[:-3]}")?
I already explained how it works
And I'm running out of patience 🫠
bro i did that and get all of this
Read the error
You should be subclassing commands.Cog, not commands.Cogs, which doesn't even exist
bro
so change cogs to cog?
i cant even await setup because async like what
import nextcord
class Tickets(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.reply("Pong!")
async def setup(bot):
await bot.add_cog(Tickets(bot))```
nextcord's loading extensions and cogs stuff aren't async, like discord.py's
that nobody guy told me to async that
So, just remove async stuff (async def setup to def setup, await bot.add_cog to bot.add_cog)
They probably weren't aware that you're using nextcord
they were aware
import nextcord
class Tickets(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.reply("Pong!")
def setup(bot):
bot.add_cog(Tickets(bot))```
I did this i ran bot went online but nothing came out of terminal
and the cog works just nothing came out of terminal
Right, nextcord don't have setup_hook stuff
so should I move everything back to on_ready
Yeah
did that nothing came out of terminal
await self.wait_until_ready()
if not self.persistent_views_added:
self.add_view(CreateTicket(self))
self.add_view(TicketSettings())
self.persistent_views_added = True
self.db = await aiosqlite.connect("tickets.db")
async with self.db.cursor() as cursor:
await cursor.execute(f"CREATE TABLE IF NOT EXISTS roles (role INTERGER, guild INTERGER)")
print("Database ready")
print("Persistent views added")
print(f"{self.user} is ready!")
print(f"Bot is ready | Logged in as {self.user}") ```
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.
Your on_ready function isn't in your bot subclass
Nor does it is decorated as an event
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.persistent_views_added:
self.add_view(CreateTicket(self))
self.add_view(TicketSettings())
self.persistent_views_added = True
self.db = await aiosqlite.connect("tickets.db")
async with self.db.cursor() as cursor:
await cursor.execute(f"CREATE TABLE IF NOT EXISTS roles (role INTERGER, guild INTERGER)")
print("Database ready")
print("Persistent views added")
print(f"{self.user} is ready!")
print(f"Bot is ready | Logged in as {self.user}") ```
No, move it down an indent, so it is considered to be in the class
i fixed it
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(CreateTicket(self))
self.add_view(TicketSettings())
self.persistent_views_added = True
self.db = await aiosqlite.connect("tickets.db")
async with self.db.cursor() as cursor:
await cursor.execute(f"CREATE TABLE IF NOT EXISTS roles (role INTERGER, guild INTERGER)")
print("Database ready")
print("Persistent views added")
print(f"Bot is ready | Logged in as {self.user}") ```
Now I moved my buttons and commands to that cog and got this
Got what
the bot is yellow, why?
It's not defined?
how do i define it in a cog?
Those aren't in any cogs
Since they're not defined in one
First, make a cog for them or move them to one
bro that is in a cog
Where?
i mean im not gonna go to bed just im sick of fixing errors
The problem is most likely that you dont have self in commands inside cog
But didnt read full conversation
Or are they in Cog class i dont see them indented
tried adding self and it gets errored
Do you have it in class
Cause looks like its not
Idk what you mean by 'it'
You need to move the commands to the Tickets class
??
You created a Cog and didnt put any commands in it
You put them in global scope
This is why basic Python is important
class Tickets(commands.Cog):
...
@commands.command()
async def comm(self, ctx):
...```
im gonna try and make it all work
What's the correct "send" method for channels?
channel = bot.fetch_channel(ID)
channel. #method here
Nvm, it was giving wrong methods since I didn't await the coroutine
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns the channel’s name.
is it a good idea to use different databases for stuff? say postgres for currency and all that more of interactive stuff like afk and all and idk mongo for moderation to store all the servers and their configs? or should i just use postgres for everything
no totally not a good idea
use one database for everything
thats why you can create tables to store multiple data
or collection in mongo
more software more problems
I have a command that im using to bump servers that has my bot in them. If a user runs ?bump it sends a description of their server to a channel in my support server. The command ran fine until i tried to add a cooldown to the command. I keep getting the following error /home/container/bot.py:63: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
def __init__(self, bot):
self.bump_cooldown = {}
#Bump command
@bot.command()
async def bump(self, ctx):
user = ctx.author
if user.id in self.bump_cooldown and self.bump_cooldown[user.id] > 0:
embed = discord.Embed(title="Bump Sserver", description="You can only bump your server once every 2 hours.", color=discord.Color.red())
await discord.message.send(embed=embed)```
. ```else:
self.bump_cooldown[user.id] = 7200
chickbot_channel_id = 1126199929908494377
chickbot_server_id = 884813207888347228
chickbot_server = bot.get_guild(chickbot_server_id)
# Fetch the server information
guild = ctx.guild
server_name = guild.name
server_description = guild.description
server_members = len(guild.members)
server_invite = await guild.text_channels[0].create_invite()
channel_count = len(guild.text_channels) + len(guild.voice_channels)
# Fetch the target channel in the other server
target_channel = bot.get_channel(chickbot_channel_id)
# Send the server information and invite link to the target channel
await target_channel.send(f"Server Bumped :Bump:")
embed = discord.Embed(title="Bumped Server Information", color=discord.Color.gold())
embed.add_field(name="Server Name", value=f"{server_name}", inline=False)
embed.add_field(name="Description", value=f"{server_description}", inline=False)
embed.add_field(name="Member Count", value=f"{server_members}", inline=True)
embed.add_field(name="Channel Count", value=f"{channel_count}", inline=True)
embed.add_field(name="Invite Link", value=f"{server_invite}", inline=False)
embed.set_footer(text=f"Successfully bumped by {ctx.author.name}")
await target_channel.send(embed=embed)
await discord.message.send(f"Server Bumped Successfully by {ctx.author.mention} :Bump:")
bot.add_cog(Bump(bot))```
last line is wrong
how do i fix it?
I respect you using the docs
i know the discord.message.send needs to be ctx.send if thats what you mean
add_cog is an async function => a coroutine
hence the coroutine 'BotBase.add_cog' was never awaited
so how do i fix it? async await bot.add_cog(Bump(bot))?
examples/basic_voice.py line 147
await bot.add_cog(Music(bot))```
click the link
this whole bit of code? but replace the cog with my cog?
async with bot:
await bot.add_cog(Music(bot))
await bot.start('token')```
correct
you still have to run the main function though
best use case of cogs is using separate files for them though
to keep it all organized
cogs
- OtherCog
- Music
main.py
will this not stop my other bot running code from working?
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"))
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
bot.run('token')```
or can i put the presence code inside of main?
commands.Bot has a kwarg with activity
so you don't need to change presence in the on_ready event, it's a common mistake
if you just set the activity in the bot's constructor, it'll set the presence when online
this code works though, so how can i change it to work with main()
or how do i change it with the constructor
eating soup with a spoon works too
bot = commands.Bot(<whatever_you_had_here>, activity = discord.Activity(...) )
see what I mean?
so will this work?
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers") intents=intents)
it will
gotcha
name?
name of the activity
command_prefix = '?'
bot = commands.Bot(command_prefix=command_prefix, activity=discord.Activity(type=discord.ActivityType.listening, name=f"{command_prefix}help ‣ {len(bot.guilds)} servers") intents=intents)```
this makes more sense right? mind the {command_prefix} before help
i tried that, it just sets the status to prefixhelp ‣ 10 servers
doesn't put the symbol
you didn't try it correctly in your case then
because I defined command_prefix above the bot
also, make sure your message_intents are enabled, or the bot won't respond to commands (as it won't be able to read the message content)
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
right, because i have it set using the bot = commands.Bot(command_prefix='?')
and then the prefix command that changes the prefix uses bot.command_prefix = new_prefix
right...
and message intents is enabled already, my other commands work
👍
maybe {self.command_prefix}help would work, at least, if the command_prefix is set first before the activity
in that case, you wont need to create a separate variable first
so.......
async with bot:
command_prefix = '?'
bot = commands.Bot(command_prefix=command_prefix, activity=discord.Activity(type=discord.ActivityType.listening, name=f"{command_prefix}help ‣ {len(bot.guilds)} servers") intents=intents)
await bot.add_cog(Bump(bot))
await bot.start('token')```
so....
async with bot:
command_prefix = '?'
bot = commands.Bot(command_prefix=command_prefix, activity=discord.Activity(type=discord.ActivityType.listening, name=f"{command_prefix}help ‣ {len(bot.guilds)} servers") intents=intents)
await bot.add_cog(Bump(bot))
await bot.start('token')````
nope
why would you use async with bot¿
why not use setup hook
but
also a valid option, but I don't see him extending his class any time soon
okay then
im so confused lol, the bot ran perfectly before i tried adding a cooldown 😂
and what is the issue now?
he's not adding his cog correctly
showed you exactly how to do that, but I guess somehow that's not clear 🤔
bot.add_cog(Bump(bot)) wont run
just add that function on the bottom, run that function with asyncio like in the link, and you're all set
i get the error /home/container/bot.py:63: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
.add_cog was never awaited
@potent spear is saying that i need to add the function at the bottom of this link https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py#L147
examples/basic_voice.py line 147
await bot.add_cog(Music(bot))```
It is just as clear as it could possibly be
do you see any difference between this:
bot.add_cog(Bump(bot))
and thisawait bot.add_cog(Music(bot))
and the function is more complex than just await bot.add_cog(Bump(bot))
not talking about the class name
what do you mean by that
lemme copy it quickly
they said i needed to add this whole thing
async with bot:
await bot.add_cog(Music(bot))
await bot.start('token')
asyncio.run(main())```
Why
but my token and bot define code are already functioning outside of that
It can be any async function
well in this case you actually need it since you cant do await outside async function
because you need to be able to run this in an async function...
so all i have to do is put await infront of my add_cog function?
right ok
or put it in setup_hook
bot = ...
async def setup_hook():
# do stuff
bot.setup_hook = setup_hook
bot.run(...)
right, lemme right out the code like that and you tell me if it'll work or not
async def setup_hook():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"))
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
await bot.add_cog(Bump(bot))
bot.setup_hook = setup_hook
bot.run(token)```
@slate swan will this work?
intents are already defined btw
should be but why change presence in setup_hook if you can start the bot with activity already
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
pass activity here
i will get to that when i get to it, because it works rn
okay then how would i add it the code
?
embed.timestamp = datetime.datetime.utcnow()```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'Timestamp'
What has changed in Discord PY time?
as it tells you Embed constructor does not take Timestamp argument
its passed by attribute
!d discord.Embed.timestamp
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
@bot.check
async def allChecks(ctx):
if await bot.isBlacklisted(ctx.author.id): raise blacklistError()
if bot.checkMaintenance():
if ctx.command.parent == "dev" and ctx.command.name == "maintenance": return True
raise maintenanceError()
return True
``` why doesnt this check for the command parent and name (this is py-cord not d.py)
@potent spear you know you said i could define the activity for the presence of the bot through the commands.bot function?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
it doesnt work.
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers") intents=intents)
Really 
probably some other stuff, like for example you have bot defined twice or whatever
you're not showing us the actual issue
!e
a = str(a)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | a = str(a)
004 | ^
005 | NameError: name 'a' is not defined
erm no....
from discord.ext import commands, tasks
from datetime import datetime, timedelta
import json
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers") intents=intents)
async def setup_hook():
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
await bot.add_cog(Bump(bot))
bot.setup_hook = setup_hook
never have i ever seen it takes timestamp

!d nextcord.Embed
class nextcord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then `None` is returned.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") for you...
so it's not showing you the activity, correct?
the setup hook doesn't work like that my friend
check how setup_hook works through the examples
you have to extend your bot class in order to be able to use that
you told me above that i could do it this way.... XD
i was missing a comma, i solved that, but no its telling me bot isnt defined
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"), intents=intents)
you dont have , before intents
better view of the code
from discord.ext import commands, tasks
from datetime import datetime, timedelta
import json
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"), intents=intents)
async def setup_hook():
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
await bot.add_cog(Bump(bot))
bot.setup_hook = setup_hook```
just fxed that now
what line?
you cant use bot when you are defining it
right, before this whole situation, that line of code worked. there was no definition before it or after it
now that ive added the setup_hook it no longer works
no you can just override setup_hook like it is now
mhm, not clean though
bot.setup_hook = lambda : print(f"Bot is ready. Connected to {len(bot.guilds)} servers."); await bot.add_cog(Bump(bot))
right. you guys obviously know how to do it. Please do me a favour and adjust this so that it works. i will read through it and understand what i did wrong after
from discord.ext import commands, tasks
from datetime import datetime, timedelta
import json
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"), intents=intents)
async def setup_hook():
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
await bot.add_cog(Bump(bot))
bot.setup_hook = setup_hook```
lambda is awaitable? 
🤫
intents = discord.Intents.all()
class MyBot(commands.Bot):
async def setup_hook(self):
print(f"Bot is ready. Connected to {len(self.guilds)} servers.")
await bot.load_extension("Bump")
bot = MyBot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(self.guilds)} servers"), intents=intents)
bot.run("poop")
hold up
you're never loading the extension
bruh
in your bump cog, you should add
async def setup(bot):
await bot.add_cog(Bump(bot))```
like this?
async def setup(bot):
await bot.add_cog(Bump(bot))
def __init__(self, bot):
self.bump_cooldown = {}```
no
setup function is supposed to be in global scope
!d discord.ext.commands.Bot.load_extension
ok bot thanks
for hte docs
await bot.add_cog(Bump(bot))
class Bump(commands.Cog):
def __init__(self, bot):
self.bump_cooldown = {}```
!d discord.ext.commands.Bot.load_extension
?
Great
someone else type it
!e
?
great
under the class preferably
but yeah, you're all said if done what was asked
it broke things 
its telling me im using an inconsistent amount of indents.....!?
async def setup_hook(self):
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
bot = MyBot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"), intents=intents)```
!d
error: bot is not defined
async def setup_hook(self):
print(f"Bot is ready. Connected to {len(bot.guilds)} servers.")
bot = MyBot(command_prefix='?', activity=discord.Activity(type=discord.ActivityType.listening, name=f"?help ‣ {len(bot.guilds)} servers"), intents=intents)
bot.run("token")```
so self.run(token)
no

it's in the print
thats why i didnt suggest creating a subclass
the error appeared for bot.run not the bot presence
maybe the subclassing guide is done so far
let me check ill link you if it does
A hands-on guide to Discord.py
cause you never create instance of you subclass
as shown here
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
userAvatar = member.avatar_url
AttributeError: 'Member' object has no attribute 'avatar_url'
????
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
check what attributes it has
@ commands.has_role(XXXXX)
async def png(ctx, *, member: discord.Member = None): # set the member object to None
channel = ctx.channel
await channel.purge(limit=1)
if not member: # if member is no mentioned
member = ctx.message.author # set member as the author
userAvatar = member.avatar_url
await ctx.send(userAvatar)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
userAvatar = member.avatar_url
AttributeError: 'Member' object has no attribute 'avatar_url'
the issue here is you're either looking for old tutorials, or you're copy pasting outdated code
because you can't have this problem if you looked at the docs
already answered above
userAvatar = member.avatar_url >>> userAvatar = member.avatar.url
...................
Discord changed (_)
i know
i wanted you to go read the docs so you can solve such problems by yourself next time and you will save time
Oh you mean that I should use this instead?
start_time = time.perf_counter()
end_time = time.perf_counter()```
how do we send a gif in a embed
The same way u send an image
Thanks
def match_search_places(place, coins = 0, item = "Nothing"):
match place:
case '...':
if random.random() < 0.5:
if random.random() > 0.5:
return f"..."
else:
return f"..."
else:
return f"..."
case 'Canal':
if random.random() < 0.5:
if random.random() > 0.5:``` is there a more efficient way of doing this deciding if u get an item or a coin, or just dont get anything
How do I created a select options? with tree commands?
Sorry?
Not sure I'm following
is this python? Not familiar with match/case
yeah thats python
I was lookin for a way to make a preset selection for one of the slash command arguments
I'm used to pycord so I'm not sure how to do it in d.py
why not just stick to pycord then