#discord-bots
1 messages Β· Page 189 of 1
how
!venv
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 PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
python3 -m venv env
nothing happned
does it happen to be resolved if you restart vscode?
I mean it returned with nothing yet
let me try restarting
bot = commands.Bot(command_prefix='!')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
what exactly do I have to do here
^
Bro πππ
oh you've defined three different Bots in the same code...
U have 3 bot instance
NameError: name 'client' is not defined
client is not defined
do you know how python works?
have removed bot
Um not being rude, if the answer is no, please consider learning it
.. and how Python works
Show the current code now
Good job
Now try running the code
This wont give error except keep_alive
Huh?
TypeError: intents parameter must be Intent not <class 'type'>
hello
Show the current code please
the recent one I had sent
Why u added client instance
You already have defined bot instance
Just drop ur ques
I used client instance and not bot instance. So I removed the bot instance
typeerror: 'bool' object is not interble
@shrewd fjord
@shrewd fjord
how do i fix this
line 22, in <module>
bot = commands.Bot(command_prefix=prefix, self_bot=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
Well then add the client instance to the same place of bot instance
!intents
Using intents in discord.py
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.
@naive briar is there any rules for self bots?
yeah why is there a self_bot=True argument there?
its in the same place
grid = [['π£' for j in range(5) in range(5)]]
typeerror: 'bool' object is not interble
@shrewd fjord
how to fix this
Bro it isn't the full code
u need the full thing?
There is no such bool objects i see on ur code
@bot.slash_command()
@commands.has_role("Urzan")
async def ownermines(ctx, round_id:str):
if checker2(round_id) == False:
await ctx.send("This Round ID is Fake")
elif checker2(round_id) ==True:
encoded_round_id = base64.b64encode(round_id.encode())
hashed_round_id = hashlib.sha256(encoded_round_id).hexdigest()
binary_hashed_round_id = bin(int(hashed_round_id, 16))[2:]
grid = [['π£' for j in range(5) in range(5)]]
safe_spots = [0, 10, 20]
for spot in safe_spots:
row = spot // 5
col = spot % 5
if spot % 2 == 0:
safe_spot = int(binary_hashed_round_id[spot:spot + 5], 2) % 4
else:
safe_spot = binary_hashed_round_id[spot:spot + 5].count('1') % 5
grid[row][col + safe_spot] = 'β'
grid_string = "\n".join([" ".join(row) for row in grid])
embed = discord.Embed(color=0x8bdbff)
embed.add_field(name="π Owner Prediction",
value=f"{grid_string}")
await ctx.send(embed=embed)
self_bot can be use in 1.7.3 version of dpy

@shrewd fjord
here
its a self bot
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Ignoring exception in command ownermines:
Traceback (most recent call last):
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 310, in ownermines
grid = [['π£' for j in range(5) in range(5)]]
TypeError: 'bool' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/Urzan/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'bool' object is not iterable
@shrewd fjord
nah im asking the author why they have it, iirc ive seen at least one person write a selfbot parameter without understanding what its used for
So, self bots are allowed in this server's rules?
no
Demn
grid=[π£ for j in range(5)]
Its also very much against Discord's ToS, and they will obliterate your account
in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
this is what I got after running
replace it with this?
@shrewd fjord
@shrewd fjord
Yes
Remove that line completely
its not there in the code
Bro don't copy paste
do :bomb:
k
Show full err
that was the full error
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
line 1348, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
Oh wait
line 1348 doesnt exist
?
It isn't the full error then
it is
This is how a error looks like
Traceback (most recent call last):
File line 287, in <module>
@client.command()
^^^^^^^^^^^^^^^^
File, line 1513, in decorator
self.add_command(result)
File bot.py", line 245, in add_command
super().add_command(command)
File, line 1348, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
send code
!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.
Code is above it
Good now go to line 287 and give a screenshot
Huh?
nothing looks wrong with that
do this
bot=commands.Bot(......., help_command=None)
bot=commands.Bot(command_prefix='$', help_command=None)
This?
sorry
just use the client
client=commands.Bot(command_prefix="$", intents=intents, help_command=None)
aight, its up an running now
btw why not use .all()
U can use if u want lol
it should just be from liste_bjr import response_description_bjr on line 7 in cog_cmd.py
yes but i understand it...
what?
why i have this error?
Whatβs the problem?
Is there a way we can run a code for a discord bot froever
even when we close the window
for free
i told you
replace line 7 with from liste_bjr import response_description_bjr
okay π
thanks
oof
why not tho
but I just want to run it for a few servers that my bot is in
is there not other way
without paying
now i have this error in my main.py file...
or running it
If you're a student, you could get the Github Student Developer pack for free which will give you access to a few VPS services for free
and AWS, GCP and Oracle have free tiers
although many have expressed data and privacy concerns for all of these
what
PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot> & C:/Users/Mathieu/AppData/Local/Programs/Python/Python311/python.exe "e:/SSD externe/Python/Code/Projets/DevBot/DiscordBot/main.py" Traceback (most recent call last): File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 4, in <module> from cogcmd.cog_cmd import liste_commandes File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module> from liste_bjr import reponse_description_bjr ModuleNotFoundError: No module named 'liste_bjr' PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot>
can you give some more information on that
anyone?
is this module in the same package as wherever you're importing it?
yes in subfolder
not sure what you mean by a subfolder, but you're probably looking for relative imports
look my arborescence
from .liste_bjr import ...
in main file?
no, you said you were importing it in one of the package's modules
yes and @slate swan suggest this code
https://discordapp.com/channels/267624335836053506/343944376055103488/1070016272202469416
!eval
While True:
{
print ("gg bot")
}
so you need a . before the module name ^
@vagrant raft :x: Your 3.10 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | While True:
003 | ^^^^
004 | SyntaxError: invalid syntax
and now i have a same error in my main file, before this, the reero is in cogcmd file
what's the error?
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 3, in <module>
from cogcmd import cog_cmd, cog_info, monde, automsg
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot>
ModuleNotFoundError: No module named 'liste_bjr'
!eval
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
@vagrant raft :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 2
002 | > a, b = 0, 1
003 | ^
004 | IndentationError: expected an indented block after function definition on line 1
of course, in main.py how will you access it like that
!eval
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
@vagrant raft :x: Your 3.10 eval job has completed with return code 1.
001 | File "<string>", line 3
002 | while a < n:
003 | IndentationError: unexpected indent
it's a module of the package; ```py
from cogcmd.listebjr import ...
hi, can you please use #bot-commands
i try it, thanks
dont work!
error?
is not defined
what is not defined
your code
send the traceback man
I think it's not very clear I'll start from the beginning
in my main.py file i have this code:
import discord
from discord.ext import commands
from cogcmd import cog_cmd, cog_info, monde, automsg
import os
from dotenv import load_dotenv
and in my cog_cmd.py file i have this code:
import discord
from discord.ext import commands
import random
import os
from dotenv import load_dotenv
import dataclasses
from liste_bsr import reponse_description_bsr
from gage import liste_gage
import asyncio
if i start the bot i have this error in main.py
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 3, in <module>
from cogcmd import cog_cmd, cog_info, monde, automsg
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
PS E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot>
that error is actually in cog_cmd.py
see where it's actually being raised
no in main.py
Looking at the traceback, it says that in File cog_cmd.py it is raising the error
!traceback learning how to read and understand a traceback is very helpful in ironing out errors and bugs
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
So what is liste_bjr........?
its a module inside the cogcmd package
file tree here for reference
He is trying local imports?
liste_bjr is a .py file in cogcmd folder
change line from liste_bsr import reponse_description_bsr to from codcmd.liste_bsr import reponse_description_bsr
If that doesn't work, then idk what else would
Me and Python imports are not the best friends
it dont work
Import "codcmd.liste_bsr" could not be resolved
That is being shown in the IDE
Try running it directly without debugging via the command prompt
its cogcmd.liste_bsr
Okay yea that then just change it
Sorry I misread it
What is the error?
i have 2 error in 2 files
Paste the error pls
in cog_cmd.py
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
from cogcmd.liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'cogcmd'
okay so in the main.py, add this line of code at the top:
import os
print(os.getcwd())
i allready imported os
then just add the print
What the
That is not possible
Paste the whole output of the script here
wait
Add that code above all the imports too bro
import discord
from discord.ext import commands
from cogcmd import cog_cmd, cog_info, monde, automsg
import os
print(os.getcwd())
from dotenv import load_dotenv
Above the discord imports too
move the os import to the top
and the print statement in the second line
E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 5, in <module>
from cogcmd import cog_cmd, cog_info, monde, automsg
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 9, in <module>
from gage import liste_gage
ModuleNotFoundError: No module named 'gage'
no print here...
E:\SSD externe\Python\Code\Projets\DevBot\DiscordBot
There u go
That is what was printed
Hey the error changed!
now change the gage import also to cogcmd.gage
in cog_cmd.py
ok, now i have
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
from cogcmd.liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'cogcmd'
uh
WTF, but cogcmd is the folder, no?
what is that?
whats gage?
try adding a period before cogcmd so it is .cogcmd
π weird naming
just a file name inside cogcmd
it does not make sense
prolly because they are French and the naming is French?
the . tells Python that it is a local folder
i say it for the error in traceback
I have another way but it is a hacky one and I don't want you to use that since I don't think anyone really likes that lol
Ah hm yea u r right
one directory relative but for beginners i always say use full path in imports
You are most welcome to help with local imports
I suck at those
the dot carcter not work
circular import as well
This is the file tree
and error is in?
cog_cmd
is from .liste_bjr not working?
i can see an init.py in cogs folder so from .list_bjr import whatever should work
!e
a = ["1", "b", "c"]
for i in range (len(a)):
if a[i] == 'b':
a[i] == 'k'
print(a)
@supple ridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1', 'b', 'c']
huuh weird
and whats that?
yeah but you rename your package and suddenly you're fucked
although find+replace does exist nowadays π
i mean pycharm auto refactors that for me so
are you using pro?
yeah
and?
is it good
yeah op
or should i not bother
so what am I supposed to do?
people may say it takes ram but i feel its indexing is totally worth it
what was the error in main.py?
if i write this, i dont have error in cog_cmd.py
import discord
from discord.ext import commands
import random
import os
from dotenv import load_dotenv
import dataclasses
from liste_bjr import reponse_description_bjr
from liste_bsr import reponse_description_bsr
from gage import liste_gage
import asyncio
bro a[i] = k not == k
!e
a = ["1", "b", "c"]
for i in range (len(a)):
if a[i] == 'b':
a[i] = 'k'
print(a)
@supple ridge :white_check_mark: Your 3.11 eval job has completed with return code 0.
['1', 'k', 'c']
also #bot-commands
i j noticed rn LMfao
yea sorry couldn't find it my bad
this is main.py?
and if i run the code in main.py i have a traceback:
Traceback (most recent call last):
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\main.py", line 5, in <module>
from cogcmd import cog_cmd, cog_info, monde, automsg
File "e:\SSD externe\Python\Code\Projets\DevBot\DiscordBot\cogcmd\cog_cmd.py", line 7, in <module>
from liste_bjr import reponse_description_bjr
ModuleNotFoundError: No module named 'liste_bjr'
why are u even importing stuff from cogs every where
lmfao
no in cog_cmd.py
ur error literally says in line 5 u are importing modules from cogcmd folder
also its from .liste_bjr or cogcmd.liste_bjr
yes
in python u either import relative to current directory but u need an init.py or u use full paths to import relative to main directory
also importing in a loop ie importing files like a in b and b in a cause circular loop error
u might want to rearrange your imports
try not to import cog to cog or main.py to cog vice versa
make utility files and import wherever needed
@shrewd apex this is carrying what I thought of doing. these files contain lists of character strings, nothing else, no code
why are they in cog folder then?
because this is where all my bot commands are
in the root path i have 2 images folders, .env, main file
all my code is in this folder
with separate files according to the types of commands I have to do, to arrange and classify the code, I think it's easier with cogs
I just want to throw my code in the trash...
Can someone help me now please
@static holly whatβs ur issue
what are you trying to do?
get the proxy's ip
I want the bot to connect to the site to be able to retrieve its IP address and if it is in Mexico it means that the proxy works
the code works without the proxy
its my main IP
I reset the bot it is now functional. now I must succeed in having no more errors, in fact what I am trying to do is store a list of character strings in a file and call it in a command
i have this list of caracters
I would like to put this list in a file from my code but in the same directory so that the code is cleaner
I had created a "listgage.py" file and called it in my cog, but I had errors
I had 3 lists for 3 different orders in 3 different files
tu as essayΓ© sans proxy voir?
I wrote the code, it only works on the "client" on the "bot" error, what should I do?
oui
et Γ§a donne quoi?
la connexion est autorisΓ© ou non?
oui
me no english
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
mb
je vois écrit "le système distant a refusé la connexion réseau"
yes
idk why
probleme with proxy?
either the script either the site
but its weird
because i activated the proxy on my pc so im not in france but logged as the proxy locaiton 'chicago'
and it shows the proxy ip so it means the connection is allowed
but no when i try to log to the site thru the script i did
hmmmm
ask them if they don't have a problem with their api at first, then you will have the last solution
Can someone help? I am waiting since 29.01.2023
#discord-bots message
alrdy done
Converting to "int" failed for parameter "pep_number".
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
Here β«
@static holly
@white citrus do you have an error?
yes, the role is not added...?
have you tried to print as the command goes, see if you see anything strange?@white citrus
No after i added the role, admin_role is not longer None
it doesnt seem obvious if you're actually changing anything about status_embed
It has if statements
Whatβs the problemo?
that doesnt change the fact that you only generated the embed once
as far as i can tell from that code, you compute the correct emojis once, and then just re-use it throughout your prompts without updating it to match the new status each time
And how can i Match the new Status each time?
create a new embed with fresh data...?
This is the embed
This is one line
f"> Administrator Role {c.MajaCrossMark if admin_role is None else f'{c.MajaCheckMark} {nl} > {get_admin_role}'}\n\n"```
If i set the admin_role the else should triggeer at message.edit
if i say, "You have 1 cake", and i give you another cake but say "You have 1 cake" again, do you see the problem? i didnt change my response, even though i really did give you another cake
you're not changing your status_embed after each question, so you're not changing the initial response
So how can i change it?
run the same code at the top after every question to make a new, up-to-date response
@white citrus whatβs ur problem
How
yknow all of this code, literally run it again, i dont know how to explain it any simpler, you have to create a new embed or update your existing one after every choice the user makes
it doesnt magically repeat itself to keep up with the choices the user makes, you need to manually update it so you have a new status to edit your message with
Yeah, and how can i update my existing one after every choise
That's the big mysterious question I'm asking myself
!e doing the same analogy again: ```py
n_cakes = 2 # this would be your "status embed"
Here's sending a message with the status embed
print("You have", n_cakes, "cakes")
For each setup step the user has to do:
for _ in range(4):
# Get their answer
print("Would you like a cake? [yes]")
# Update your embed to reflect the choice that the user made
n_cakes += 1
# Edit your original message with the new status embed
print("You have", n_cakes, "cakes")```
@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | You have 2 cakes
002 | Would you like a cake? [yes]
003 | You have 3 cakes
004 | Would you like a cake? [yes]
005 | You have 4 cakes
006 | Would you like a cake? [yes]
007 | You have 5 cakes
008 | Would you like a cake? [yes]
009 | You have 6 cakes
I'll take the first one and edit it
if admin_role is None:
SetupAdminView = SetupAdminRoleSelect(inter)
reply = nextcord.Embed(title="Setup β’ Activate Administrator Role", description=f"{c.MajaSettings} Please select a role.", colour=c.blurple)
await org.edit(embeds=[status_embed, reply], view=SetupAdminView, attachments=[])
SetupAdminView.message = org
await SetupAdminView.wait()
await org.edit(embed=status_embed, attachments=[])
await asyncio.sleep(2)
else:
await org.edit(embeds=[status_embed, embed_wait], attachments=[])
await asyncio.sleep(2)```
make your embed generation into a function, and then call it after each selection to replace the current status embed
So i quess
i am unable to send buttons through webhooks
beb=os.getenv("web")
webhook = SyncWebhook.from_url(beb)
button1 = Button(label="β OKAY", style=discord.ButtonStyle.link, url='https://google.com/')
view=View()
View.add_item(button1)
webhook.send(embed=embed,view=view)```
yet another example: ```py
async def get_status_embed():
async with aiosqlite.connect(...) as db:
query = "SELECT admin_role, moderator_role, supporter_role, ... FROM setup WHERE guild_id = ?"
c = await db.execute(query, guild_id)
row = await c.fetchone()
return discord.Embed(description=
f"Admin Role: {...}\n"
f"Moderator Role: {...}\n"
...
)
status_embed = await get_status_embed()
message = await ctx.send(embed=embed)
if admin_role is None:
... # ask user to provide admin role, update the database, then:
status_embed = await get_status_embed()
await message.edit(embed=status_embed)
Repeat above for every prompt```
i dont know if you're allowed to send message components for regular webhooks
omg you totally can thats cool
the discord docs says it'll only work for webhooks owned by the bot
oh and apparently SyncWebhook doesnt support the view= parameter
ok
what should i do then
in context to the traceback you just deleted, discord.py only officially supports handling interactions through the gateway websocket
as such, you need to have a Client/Bot instance running on a separate thread in order to send webhook messages with views, and to receive interactions when people click on them
(see also Client.fetch_webhook(), and if you're making persistent message components Client.add_view() too)
can i use requests module and deliver a button payload
?
as in manually send a message with components on it? i guess sure, but my described approach can still work for discord.py
ok
The embed still doesnt update
https://paste.nextcord.dev/?id=1675200045938331 HERE IS THE CODE
Hey, sorry fore the non code related question but does anyone know what these are?
The dark colour boxes containing all the information. Are they just embeds? They look different from your standard embeds imo.
is there a on_command_error equivalent for slash commands?
cant find anything in docs
looks like markdown
Doesnβt mark down always look like this though?
Hmm. Iβll look into this further, thanks
Turns out they are just embeds after all⦠just without the colour lol
They're embeds with the same color as the discord dark mode background
!d discord.Colour.dark_theme
classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discordβs dark theme.
New in version 1.5.
If you change your client to light theme you'll be able to see it
Ye, I figured out that they were embeds. I didnβt know about the theme so thatβs definitely useful. Thanks!
couldnβt you just use colour = 0x303135?
Sure
But personally I prefer using the discord.Colour object as it makes it more explicit what you're doing
I will generally also create a utility method:
@staticmethod
def _build_dark_theme_embed(*args, **kwargs) -> discord.Embed:
if "color" in args:
raise ValueError("_build_dark_theme_embed does not take a `color` parameter")
return discord.Embed(*args, **kwargs)
Though this is not strictly necessary
alright thanks
@sick birch ?
what are examples of some big open-source bots
i want to get inspiration for how to implement mine

β€οΈ awww I do the same
!contribute
Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!
Projects to Contribute to
β’ Sir Lancebot - our fun, beginner-friendly bot
β’ Python - our utility & moderation bot
β’ Site - resources, guides, and more
Where to start
- Read our contribution guide
- Chat with us in #dev-contrib if you're ready to jump in or have any questions
- Open an issue or ask to be assigned to an issue to work on
Ours not not really "popular" per se, but still follow good practices and design principles
Especially @unkempt canyon
Be warned, though, the codebase is quite complex
Ask your question
ok hold on
Embed doesn't have any positional args 
TIL @unkempt canyon isn't made with dpy
It is though
oh, pydis_core is a whole other library that wraps dpy lmao
pydis bot is made with dpy
if you're using discord.py 2.0 the setup, add_cog, and load_extension methods need to be invoked asynchronously
https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
preciate it
i still dont see you creating a new embed after each prompt, i.e. this part of my example
tf is that server icon π
is anyone familiar with the scrapetube library?
I can't seem to get this youtube scraper module working
I've literally tried everything lol
def video_links():
# channel = "UChozbOPP6uOJ2UkiTZy-sgQ"
# try:
# scrape = scrapetube.get_channel(channel_id='channel')
# videos = scrape.videos
# return random.choice(list(videos))
# except Exception as e:
# print(f"An error occurred: {e}")
# videos = scrapetube.get_channel("UChozbOPP6uOJ2UkiTZy-sgQ")
# for video in videos:
# print(video['videoId'])
# return random.choice(video)
# channel_id = "UChozbOPP6uOJ2UkiTZy-sgQ"
# videos = scrapetube.get_channel(channel_id).videos
# return random.choice(list(videos))
# print(video_links())
channel_id = "UChozbOPP6uOJ2UkiTZy-sgQ"
videos = list(scrapetube.get_channel(channel_id).videos)
return random.choice(videos)
# for video in videos:
# print(video['videoID'])
main.py where I call it
if message.content.startswith('$video'):
video = video_links()
await message.channel.send(video)
I made a bunch of comments because none of that shit works and I am trying to figure it out and I might need to go back and use some of those code blocks.
setup_hook
got it
smart π
thx zefo bro
Ok π
you're probably running the bot twice
or have process_commands in a listener
any alternative i can use for await in a def function to use asyncio.sleep?
Why don't just make it async
asyncio.loop.run_until_complete
!d asyncio.loop.run_until_complete
loop.run_until_complete(future)```
Run until the *future* (an instance of [`Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future "asyncio.Future")) has completed.
If the argument is a [coroutine object](https://docs.python.org/3/library/asyncio-task.html#coroutine) it is implicitly scheduled to run as a [`asyncio.Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task").
Return the Futureβs result or raise its exception.
or you can use the not async time.sleep, but that will block other parts of your code
yea
Why though..? Instead of just making the function async
Traceback (most recent call last):
File "/Users/x/PycharmProjects/dispy-lin/main.py", line 40, in register_commands
await bot.rest.set_application_commands(
File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 3761, in set_application_commands
response = await self._request(route, json=[command.build(self._entity_factory) for command in commands])
File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 712, in _request
await aio.first_completed(request_task, self._close_event.wait())
File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/internal/aio.py", line 138, in first_completed
await next(iterator)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py", line 571, in _wait_for_one
return f.result() # May raise f.exception().
File "/Users/x/PycharmProjects/dispy-lin/venv/lib/python3.10/site-packages/hikari/impl/rest.py", line 852, in _perform_request
raise await net.generate_error_response(response)
hikari.errors.ForbiddenError: Forbidden 403: (50001) 'Missing Access' for https://discord.com/api/v10/applications/1070247718506741800/guilds/934896901256515714/commands
I enabled the scopes bot and applications.command with these Intents Intents.GUILD_INTEGRATIONS | Intents.GUILD_MESSAGE_TYPING | Intents.GUILD_PRESENCES | Intents.GUILD_VOICE_STATES
Inside the Privileged Gateway Intents I only got presence enabled. Bot also has admin perms inside the test guild.
you sure that youre trying to edit your own bot's commands?
cause it seems like you don't have access to the particular applications' commands
I'm trying to add application command to a guild.
But it's giving me hard time.
I could share the code?
!pip hikari-crescent
!pip hikari-tanjun
this method should work fine btw
I know about lightbulb but I straight off copied this from their git so idk why it's not working.
recheck the application.commands scope
remember that you need to kick and reinvite the bot if it was already in your server
Well I did it from the start, I will try to use lightbulb.
Will take some time since I want to handle it properly lol
Do you have any examples or docs for extending the bot? Like separate into extensions.
Plugin in lightbulb and crescent
Component in tanjun
they are used for organisation of your code
hey it works in input, but when i try it using discord bot it sadly doesnt work am i doing smth wrong?
@client.command()
async def name(ctx, arg1, arg2):
arg1 = arg1.capitalize()
try:
with open('names.txt', 'r') as f:
name = f.read()
name.replace(arg1, arg2)
with open('names.txt', 'w') as f:
f.write(name)
await ctx.send('File is succesfully updated.')
except:
await ctx.send('Error occured.')ββ
is there a on_command_error equivalent for slash commands?
Depends on library
But yes there are
class WelcomeGoodByeEditButtos(discord.ui.View):
def __init__(self, styles_list:list):
self.styles_list = styles_list
super().__init__(timeout=None)
def test(self):
print(self.styles_list)
Extension 'dashboard.mainDashboard' raised an error: TypeError: test() missing 1 required positional argument: 'self'
Please send the full traceback
You're probably calling the method on the class instead of an instance of it
How can Steam's website have 3 fields to its embed? apparently they are not adding any meta-data for such things.
@discord.ui.button(label='Welcome Text Type',style=test(), custom_id='WelcomeGoodByeEditButtos3', row=1)
TypeError: test() missing 1 required positional argument: 'self'
im calling it here
@discord.ui.button(label='Welcome Text Type',style=test(), custom_id='WelcomeGoodByeEditButtos3', row=1)
style = self.test()
And you don't have access to an instance there, so that won't work
im trying to use a style from list
styles_list is a list with discord styles
Yes, but the methods are created when the class is created, not when an instance is created
So you'll need to create the button in the _init_ or another place where you can actually access the list
Via the instance or otherwise
other way
becuase i have and other buttons
with not need to use a styles from list
Do you know how to make a command?
yeah
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
You can call this method to change the status / activity
Dude I've given you the answer. You need to use self.test() rather than test().
Could you help me code that?
Wut
Make the command first then use change_presence() inside of it.
hey catgal sup
He can't use self because that is undefined where he's calling it
Sounds be right
I haven't seen his other part where he uses that function but he can pass it as an argument in that case.
An option is to set the style in the init instead of the decorator, which would require minimal work
Or use ui.Button and add it with View.add_item
Where is he using test()?
Also wait, style = test()?! style doesn't take a function as an argument, or does it?
oh my bad, yeah that's correct
It should rather be return self.styles_list rather than print(self.styles_list) because in this case it returns None apparently
I'm a bit new to python would it look a little like this?
@bot.command()
async def changestatus()
i'm not sure what else to put
That's a start. Now we need to call change_presence() inside that function.
In between () or on a new line?
New line. In between () goes the arguments you pass to that function. On a new line is where you can call a function.
Thanks, So this?
@bot.command()
async def changestatus():
await change_presence()
Put a : after function declaration
Yes
And you need to call the change_presence from a bot instance
Also move it up an indent to make it inside the function
Like this: await change_presence():
No, after the function declaration
def func(): # <---
...
Now would be a great time to read up on functions in python
true
@bot.command()
async def changestatus():
await change_presence()
So like that?
Yeah
correct
Thanks, ill look into that shortly
And commands take a "ctx" parameter
So is that it or do i have to add more stuff to make the command work?
you have to add stuff
what will your presence change to? you need to tell it what text to change into right,
How can i get all subcommands in nextcord?
!d discord.ext.commands.Bot.walk_commands
for ... in walk_commands()```
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
yes
i want to run a command so like !changestatus hello π
and it would change
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientβs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
^^^ kinda ez as well as there is a example right there
this is what i got so far
@bot.command()
async def changestatus():
await change_presence()
Idk what else to do
hello is an argument, so you have to pass it in your command then use it in change_presence()
https://www.w3schools.com/python/gloss_python_function_arguments.asp#:~:text=Information can be passed into,separate them with a comma.
Maybe ask on #python-discussion ?
Wait, i want to be able to change my status to what ever?
can i not do that
so say like watching 5 tickets
Just pass an argument then
Yea lol
you pass "watching 5 tickets" as an argument
how would i do that
import discord
from discord import app_commands
import traceback
TEST_GUILD = discord.Object(0)
class MyClient(discord.Client):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def setup_hook(self) -> None:
# Sync the application command with Discord.
await self.tree.sync(guild=TEST_GUILD)
class Feedback(discord.ui.Modal, title='Feedback'):
name = discord.ui.TextInput(
label='Name',
placeholder='Your name here...',
)
feedback = discord.ui.TextInput(
label='What do you think of this new feature?',
style=discord.TextStyle.long,
placeholder='Type your feedback here...',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
traceback.print_tb(error.__traceback__)
client = MyClient()
@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
await interaction.response.send_modal(Feedback())
client.run('token')
Dear please tell me. I took the code from the discord py git hub. does not start. didn't change anything.
you're passing an invalid token
go to your application's developer portal, and click "Regenerate" in the Bot section to get a new one
It didn't help... The fact is that the bot starts up if you do it according to the instructions, but this particular section of the code is not...
client.run('token') <-- this 'token' has to be replaced with your actual bot token
did you do that?
yes
and where did you get the bot token from?
This is what I put in client.run('token')
you put token between ' ' ?
code please
import discord
from discord import app_commands
import traceback
TEST_GUILD = discord.Object(0)
class MyClient(discord.Client):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def setup_hook(self) -> None:
# Sync the application command with Discord.
await self.tree.sync(guild=TEST_GUILD)
class Feedback(discord.ui.Modal, title='Feedback'):
name = discord.ui.TextInput(
label='Name',
placeholder='Your name here...',
)
feedback = discord.ui.TextInput(
label='What do you think of this new feature?',
style=discord.TextStyle.long,
placeholder='Type your feedback here...',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
traceback.print_tb(error.__traceback__)
client = MyClient()
@client.tree.command(guild=TEST_GUILD, description="Submit feedback")
async def feedback(interaction: discord.Interaction):
await interaction.response.send_modal(Feedback())
client.run('token')
this is the code from the git hub discord py just copied and did not change anything
Ok and what do you want us to do about that
π
You don't have the permission to register slash commands to that guild π€·
That's just the minimum effort of reading the error
how do i use bot.load_extension("")? i am using replit and when i put the file name in this error appears Traceback (most recent call last):
File "main.py", line 17, in <module>
bot.load_extension("random_commands.py")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.8/importlib/util.py", line 98, in find_spec
raise ModuleNotFoundError(
ModuleNotFoundError: path attribute not found on 'random_commands' while trying to find 'random_commands.py'
i have no idea how to find the path for replit files and have done some research and anything that worked for other people isnt working for me D:
The same way you import other python file
From this folder/file.py to folder.file
Or if in the same directory, from file.py to just file
Hi, I don't have any error code but either response from my bot when I do the command !feet
import discord
from discord.ext import commands
import aiohttp
from bs4 import BeautifulSoup
import re
import asyncio
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'
}
proxies = {
"https": "http://user: password@ip:port",
}
async def main():
async with aiohttp.ClientSession() as session:
url = "https://ipinfo.io/json/"
async with session.get(url, proxy=proxies['https']) as resp:
data = await resp.json()
print (data['country'])
print(data['ip'])
print(data['region'])
asyncio.run(main())
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@client.event
async def on_ready():
print('bot is online')
@client.command()
async def feet(ctx, name):
name = name.replace(' ', '_')
url = f"https://www.wikifeet.com/{name}"
await ctx.send(f"URL : {url}")
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
soup = BeautifulSoup(await response.text(), "html.parser")
images = soup.find_all("img")
if images:
for image in images[:3]:
url = "https:" + image["src"]
if "image" in r.content_type:
await ctx.send(url)
async with session.get(url) as r:
if r.status == 200:
await ctx.send(file=discord.File(await r.read(), filename='image.jpg'))
else:
await ctx.send("Aucune image trouvΓ©e.")
else:
await ctx.send("Une erreur est survenue.")
client.run('token')
Hi, i don't have any error from the code but no answer too
Does anyone knows why?
oo!! this worked, thank you very much for your help :D
@bot.command()
async def changestatus(ctx, new_presence: str):
await change_presence(status = discord.CustomActivity(name = new_presence))```
This should work.
`new_presence: str`: is the argument we pass to the function.
`change_presence()`: takes `status` parameter to decide the status of the bot.
`status`: takes a `BaseActivity` object as an argument, in this case we'll create one with `discord.CustomActivity()` then pass it to `change_presence()`.
https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.change_presence
https://discordpy.readthedocs.io/en/latest/api.html#discord.BaseActivity
You still need ctx to be the first argument
You should add print() after every if and else to see where the code blocks at.
Oh yeah, true.
good idea
it block at await CTX.send("URL :", url)
it doesn't print the url
print(url)
@slate swan just above it.
use a f string
infact there was no error just my proxy take too much time lol
Your TEST_GUILD constant has an invalid ID
There's no guild with ID 0
You need to use an actual guild's ID to sync your commands there
Oh thanks! I'll be more careful next timeπ₯³
where do i host my bot?
so it's working?
no
still have an error somewhere
hello , my bot always shows members status as offline , but his one as online .. any solution ?
Enable member intents
*presence intents
How can i get all application subcommands in nextcord?
And change user.create_dm to user.send
enabled
it's already user.send
you're trying to send a message to the bot's own dms
and you need presence intents, not member intents
(if you just want the status+activities)
or both if you want all the data
all subcommands for every application command?
i want it to send a message to a specific member if he's online
your error says ClientUser has no attribute create_dm which means you're trying to dm the bot.
Yeah all subcommands from every application command
do you know how to get all application commands?
Yeah
i'll show you
ok, so you can use the children attribute: https://docs.nextcord.dev/en/stable/api.html#nextcord.SlashApplicationCommand.children
what is this supposed to show
?Β΅
how is member defined
for member in guild.members
which includes the bot
hence your error
and mass dm is going to get you ratelimited
i enabled presences intent and it works
it's not going to get rid of the
ClientUser has no attribute create_dm
!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.
here's the code i use
and this is the bot's answer
Remove the last else so you can see whatβs making it error
Oh yea
also whats with the feet π
File "main.py", line 9, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content how can i fix this?
show code
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='z!', intents=intents)
this is the part that is saying that it has the problem
Thereβs no message_content to intents I guess?
prolly message ig no idea i forgot
lemme check docs
message_content does exist
u sure u have the correct library?
idk
!pypi discord.py
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
β’ The message was sent by the client
β’ The message was sent in direct messages
β’ The message mentions the client
This applies to the following events...
so i have to pip install discord.py v2.1.0 ?
just discord.py
ππ
do i need to import cog to use cogs?
like what could be the problem, last time i used wavelink.Player to make a class of my own to pass in channel.connect() as we can only pass classes made with abc disnake.VoiceProtocol this time its showing the error TypeError: Type must meet VoiceProtocol abstract base class.
its been long since i logged into my bot prolly something with updates ?
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
for example i have a file called test.json
with the following content:
{
"696969": "abc"
}
now the 696969 is the guild id and abc is the string i want it to send. What i wanna do is whenever a command is ran and if the guild id is in test.json it gets abc or whatever and sends it.
U get the dict
can you elaborate a bit?
store it as like ```py
whatever_dict = {
"696969": "abc"
#in ur callback
data = whatever_dict[interation.guild.id]
}```
with open('test.json') as f:
config = json.load(f)
yea im not getting the data part
oh
i think its json.loads
oh it converts to a dict yea
Do not use on message events to create commands.
You are defining the bot twice
It's not
Just spend some hours to learn the basics!
Do not select any language because you can find anything ready in Google π
It should be bot.change_presence
Okay so I have some work done and currently going over the example but when I try to run this -> https://paste.pythondiscord.com/oyixunujin it doesn't work and says that the user isn't in the server using ctx.bot.cache.get_member(ctx.guild_id, user) to get the member but I don't think it's in cache, any way to fetch it?
theres guild.fetch_member
look into bot.rest.fetch_member
wait nvm, you're using hikari
or it should be fetch_guild_member, either of these
Thanks :3 still getting used to the docs website.
everything related to the rest is available in the RESTClient(impl) class
it;s in the hikari.impl.rest dir
Thanks! Worked.
Hikari is fast π
and cool :p
Discord.py usually takes so long to start lol
that's because dpy performs a large amount of cache operations before loading the actual bot
hikari is cache independent
everyone liked that
i like the banner and logging
I was kind of lost like aren't there any fetch operations
But it makes sense to put it neatly at the rest api
Like it so far, right now I got extensions etc set up so time for docker compose and put it in an image.
Although the docs from lightbulb are kind of weird I was looking at this and used it for testing purposes -> https://novanai.readthedocs.io/en/latest/lightbulb/part_3.html but they don't have it setup if your user isn't cached and it uses get_member but calls it user after that.

you can just use ```py
member = get_member(...) or await bot.rest.fetch_member(...)
if not member:
member = await ctx.bot.rest.fetch_member(ctx.guild_id, user)
if not member:
await ctx.respond("That user is not in this server.")
return
``` quickly used this but I'm most likely going to make a function for it.
fetch_member will raise an error if member is not there
try:
member = await ctx.bot.rest.fetch_member(ctx.guild_id, user)
except hikari.HTTPError:
respond("Not in server")
I have to setup an error handler too... yes.
I'm using slash commands but I guess people are weird enough to try.
I also hoped to typehint Member but it didn't like that lol
the @option decorator does it all
@lightbulb.option("arg_name", ..., type=hikari.User)
@lightbulb.command("foo", "description", pass_options=True)
# pass_options = True will pass the option in function signature
@lightbulb.implements(...)
async def foo_callback(ctx, arg_name):
...
``` you can access the provided value using `arg_name` or `ctx.options.arg_name`
Could Member be typehinted? Does it look up on cache or does it fetch as well?
just use hikari.Member type
and yeah typehint can be used, but it wont help with anything related to data conversion
Hi i am new to discord bot
i tried watching a video online and tried to make a bot using the code(basic) in the video
Hmm thanks for the info I will try some things out to make it easier.
when i run the code the bot is online but the issue is the bot does not respond to the user message
Just a sec i will share the code
import discord
import os
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hi'):
await message.channel.send('hello')
my_secret = os.environ['token']
client.run(my_secret)````
at first i was getting some error with Intents and tried searching it up online and someone suggested to make it default
if message.content == "$hi", if I read you right
!intents you need message_content intents
Using intents in discord.py
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.
please i need help in #1070390791903658024
Thanks for the help , took some time for me to process
import discord
import os
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == "hi":
await message.channel.send('hello')
my_secret = os.environ['token']
client.run(my_secret)```
works now π
How can i get the mention of a nextcord.SlashApplicationCommand.subcommand
Like </test:1>
!d discord.Member.status
property status```
The memberβs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
I created a script in python that retrieves images from a website and sends them to the discord server where the command was executed. However I have a problem. The script doesn't filter the images so it requests 3 images (because I have a limit of 3 images) in .svg and .gif only I would like the bot to request only images ending in .jpg.
I tried to filter with py if url.endswith(".jpg"):```` and at the top I defined URL like this: py
url = "https:" + image["src"]``` but it doesn't work. It always requests .gif and .svg images.
Here's my script : https://paste.pythondiscord.com/gipefofadi
hi, I setup a cog in version 1.7.3 and now i'm migrating to v2 but i can't get it to take the cog https://paste.pythondiscord.com/ilupamekal
I just started and heres my code:
import discord
bot = discord.Client()
@bot.event
async def on_ready():
print("BOT IS ONLINE")
bot.run("my token")
!paste or use ` three times
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 is wrong with it?
'''import discord
bot = discord.Client()
@bot.event
async def on_ready():
print("BOT IS ONLINE")
bot.run("my token")'''
it says in the terminal
it's the button above tab on a keyboard
bot = discord.Client()
@bot.event
async def on_ready():
print("BOT IS ONLINE")
bot.run("my token")'```
File "c:\Users\leoja\Documents\bot\Event Basics.py", line 3, in <module>
bot = discord.Client()
^^^^^^^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'```
!d discord.Client.intents
property intents```
The intents configured for this connection.
New in version 1.5.
that is what your missing
where do i put it
example intents = discord.Intents.default() bot = commands.Bot(command_prefix="!",intents=intents)
like this?
bot = commands.Bot(command_prefix="!",intents=intents)
intents = discord.Intents.default()
@bot.event
async def on_ready():
print("BOT IS ONLINE")
bot.run("*my token*")```
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)```
File "c:\Users\leoja\Documents\bot\Event Basics.py", line 4, in <module>
bot = commands.Bot(command_prefix="!", intents=intents)
^^^^^^^^
NameError: name 'commands' is not defined```
ah let me get an import
from discord.ext import commands
How do you go about accepting files from users?
I want to do some operations on the accepted file (say a txt file which i want to take data out of)
I searched around but I only see examples about the bot sending files
how would i possibly implement a text to speech command in my bot?
Won't that return custom status
or are they the same thing
what does that mean?
i ran the code, and i wanna edit it
ctrl c
how does the bot send a message after a user prompts something?
have you learned discord.py yet?
no, only python
I would learn discord.py
Using discord cogs, my terminal is blank? my on_ready() event isn't triggering?
my bot is running but none of my events or commands are triggering
is the on_ready inside a cog?
Can we see where you're loading cogs?
import asyncio
import discord
from discord.ext import commands
import os
import json
f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)
class MyBot(commands.Bot):
async def setup_hook(self):
pass
async def main():
async with bot:
for filename in os.listdir('./cogs'):
if filename.endswith('py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
await bot.start(TOKEN)
asyncio.run(main())
this is main.py @sick birch
ok nvm it worked
idk how that been 1 year since I have this prob and now it work
wtf
Ah, you have multiple command.Bots
All of your cog loading logic should be moved into setup hook
async def setup_hook(self):
for filename in os.listdir('./cogs'):
...
and what should be in my main()?
bc I did that before and it never worked
maybe i messed up the loading
You don't need a main
This is how I usually set up my bots (highly simplified):
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
# setup stuff here
bot = MyBot(command_prefix=".", intents=intents, ...) # notice how this is MyBot and not commands.Bot
bot.run()
thanks
my bot ran after doing this but now none of my commands are "found"
!pastebin your commands
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.
its in a cog called kick.py
class Kick(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.reason = None
@commands.command(aliases=['k', 'boot', 'remove'])
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member = None, *args, reason=None):
author = ctx.author.mention
if not member:
if len(args) == 0:
await ctx.send(f":no_entry_sign: {author} mention a valid member or provide a user ID")
try:
user_id = int(args[0])
member = ctx.guild.get_member(user_id)
except ValueError:
await ctx.send(f":no_entry_sign: {author} provide a valid user ID")
if not member:
await ctx.send(f":no_entry_sign: {author} The provided user ID does not belong to a member in this server")
reason = ' '.join(args[1:]) or reason
await member.kick(reason=reason)
await ctx.send(f":thumbsup: Successfully kicked **{member}**")
else:
self.reason = reason
await member.kick(reason=reason)
await ctx.send(f":thumbsup: Successfully kicked **{member}**")
async def setup(bot):
await bot.add_cog(Kick(bot))
@sick birch
Hm
Can you do a print statement inside your setup hook?
you want me to print bot.add_cog(Kick(bot))?
Nah just print like hello world or something inside the setup_hook
async def setup_hook(self):
print("Setup hook was called")
it didn't print anything
2023-02-01 20:27:54 INFO discord.client logging in using static token
2023-02-01 20:27:55 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: XXXXXXXXXXXXXXXXXX).
2023-02-01 20:28:02 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
@sick birch
And your main.py code?
nothing
No, I'm asking can if I can see your main.py code
import discord
from discord.ext import commands
import os
import json
f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]
intents = discord.Intents.all()
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
print("main.py setup hook was called")
bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)
bot.run(TOKEN)
You still have 2 different bot instances, that's why
oh my god
See the comment here
same error tho
import discord
from discord.ext import commands
import os
import json
f = open("config.json")
data = json.load(f)
TOKEN = data["TOKEN"]
intents = discord.Intents.all()
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
bot = MyBot(command_prefix=".", intents=intents, help_command=None)
bot.run(TOKEN)
Do you have a traceback?
2023-02-01 20:35:55 INFO discord.client logging in using static token
2023-02-01 20:35:56 INFO discord.gateway Shard ID None has connected to Gateway (Session ID:).
2023-02-01 20:36:05 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
Also add back in the print statement like you had before
alri
2023-02-01 20:38:20 INFO discord.client logging in using static token
main.py setup hook was called
2023-02-01 20:38:21 INFO discord.gateway Shard ID None has connected to Gateway (Session ID:).
2023-02-01 20:38:31 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "kick" is not found
Looks like you're probably on an older version of discord.py then
What editor are you using?
I'm not familiar with Pycharm so you'll have to research how to update packages
okay tyy
what version is it?
You need to be on at least v2.0.0
mine is 2.1.0
Try printing discord.__version__ right underneath your bot = MyBot(...)
Oh i just realized your setup hook was called
main.py setup hook was called
2.1.0
not my kick.py one tho
Inside your Kick class, try this:
class Kick(commands.Cog):
def __init__(...):
print("Kick cog is being loaded...")
...
interesting, it doesnt print
Try one in the setup of kick.py
async def setup(bot):
print("Setup was called")
await bot.add_cog(Kick(bot))
doesnt print
Well that's not good
Can we see your file structure?
for my kick cog?
Is your kick.py in cogs folder?
wait wait i think i figured it out
alright
moderation is in the cogs folder
im trying to organise it
i don;t want utils mixed with moderation yk?
yeah I see that
how do I load it so that its organised?
all files in cogs is lowkey annoying
Just put your cogs file in cogs folder
aight
That's all
Your setuphook load everything that end with py in cogs folder
Unless you want to recursively walk to directory tree and load cogs I'd just put everything you have in the cogs folder
Hello I wanted to know? how do I do? to print what choice an user took when using a slash command
@app_commands.choices(store=[
discord.app_commands.Choice(name="A", value=x),
discord.app_commands.Choice(name="B", value=y),
discord.app_commands.Choice(name="C", value=z)
])
Here how do I know what choice the user took
How would I make an if statement wether the use took option A,B,C ?
i think the variable store
is there a way to set maximum length of text for an app comand parameter?
also does the description show up on app command groups?
Sorry for late response, in dpy it should be on_application_command_error or smth like that
Idk dpy events
Uh oh nvm it's even more weird
!d discord.app_commands.CommandTree.on_error
await on_error(interaction, error, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
Can my bot see who joined a voice channel?
yes
Does my bot have to join the same voice channel for this?
Or can we like, listen for a join event without being in any voice channels?
you can listen for it without being in the channel
Join event being when a user joins a voice channel
Oh okay. Thank you
Okay
how do i make a slash command for the default help command?
As long as you have member intents you don't even need to listen to an event
!d discord.VoiceChannel.members
property members```
Returns all members that are currently inside this voice channel.
is this for discord.py?
how do i make a slash command for the default help command?
yeah it is
excuse me but does anyone knows how to apple for message intent and the steps to get it after getting a bot verified
What do you use message content intents for?
import discord at the top of your code.
@client.command(name='invite')
async def invite(ctx, invite_code):
proxy = {
'https': 'https://24.230.33.96:3128'
}
url = f'https://discord.com/api/invite/{invite_code}'
response = requests.get(url, proxies=proxy)
if response.status_code == 200:
data = response.json()
if data['type'] == 0:
print (f"This Invite Is Valid | Status Code: {response.status_code}")
return await ctx.send("This Invite Is VALID")
else:
print (f"This Invite Is INVALID | Status Code: {response.status_code}")
return await ctx.send("This Invite Is INVALID")
I am trying to check if a discord invite is a valid invite or not, works up until my server IP gets rate limited. Wondering if theres a way to send requests through a proxy to prevent being rate limited?
why use requests here
just use discord.py builtin method
!d discord.Client.fetch_invite
await fetch_invite(url, *, with_counts=True, with_expiration=True, scheduled_event_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets an [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite "discord.Invite") from a discord.gg URL or ID.
Note
If the invite is for a guild you have not joined, the guild and channel attributes of the returned [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite "discord.Invite") will be [`PartialInviteGuild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialInviteGuild "discord.PartialInviteGuild") and [`PartialInviteChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialInviteChannel "discord.PartialInviteChannel") respectively.
@meager chasm it appears to be working nicely, would you happen to know if this method has a rate limit?
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Everything has rate limits. Don' know invites, but if you did want to use a GET request you can look in the headers it returns
he library will attempt to throttle you to avoid getting rate limited based on those
it appears the fetch_invite method doesnt have a rate limit, thanks @meager chasm and @fast musk
Apparently my 't' is going out haha
Anything that has to make API call have rate limit
Can I scrape images using data = response.json?
I'm not sure I think json doesn't store images
You should be using aiohttp over requests. aiohttp comes with discord.py and it's asynchronous. requests doesn't come with discord.py and it's synchronous
Just read the response bytes
|| requests is a stdlib package and actually it's used in a place in d.py and forks || he should use aiohttp because in an asynchronous context a synchronous call such as requests.get will block the event loop
but I can't send the image after found it?
Just read the response bytes
Then wrap that bytes to BytesIO and use that on discord.File then send it
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
KeyError: 'ticket'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\jishaku\features\management.py", line 61, in jsk_load
await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ticket.master' raised an error: KeyError: 'ticket'```
anyone know why cog isnt loading?
What is ticket in cogs
its a folder
thats all
that shouldnt effect anything
You meant that?
if mimetypes.guess_extension(response.headers["Content-Type"]) in [".jpg"]:
async with session.get(url, proxy=proxies['https'], headers=headers) as r:
if r.status == 200:
file = discord.File(BytesIO(await r.read()), filename='image.jpg')
await ctx.send(file=file)
figured it out
@client.command()
async def feet(ctx, name):
name = name.replace(' ', '_')
url = f"https://www.wikifeet.com/{name}"
await ctx.send(f"URL : {url}")
async with aiohttp.ClientSession() as session:
async with session.get(url, proxy=proxies['https'], headers=headers) as response:
if response.status == 200:
print(response.status)
soup = BeautifulSoup(await response.text(), "html.parser")
images = soup.find_all("img")
if not images:
await ctx.send("There's no images")
else:
print("There's images")
for image in images[:3]:
url = "https:" + image["src"]
print(url)
if mimetypes.guess_extension(response.headers["Content-Type"]) in [".jpg"]:
async with session.get(url, proxy=proxies['https'], headers=headers) as r:
if r.status == 200:
file = discord.File(BytesIO(await r.read()), filename='image.jpg')
await ctx.send(file=file)
else:
await ctx.send(f"Status code : {r.status}")
else:
continue
if mimetypes.guess_extension(response.headers["Content-Type"]) in [".jpg"]:
This line doesn't work. It doesn't filter the extension file
