#discord-bots
1 messages · Page 254 of 1
fr
Though it isn't
i forgot a whole abt python
If the class is named Button
mind helping me
me dumb as hell
yea
You may want to create a variable button that is an instance of Button
So button = Button(...), just like that
if you dont understand basic python knowledge why are you starting a discord bot project its not a good idea for a beginner
but i did this label="📥 Create Ticket", style=discord.ButtonStyle.green
i did know the basics ☠️
yeah i just saw
Forgetting how to create a variable is probably some sign of Alzheimer
fr lmao
hello, i keep getting weird webhook errors, but i dont use webhooks. it doesnt allow some users to interact with a button:
data = await adapter.edit_original_interaction_response(
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found
(error code: 10015): Unknown Webhook```
what is that
i don't use webhooks
Yes you do, interaction responses are webhooks
it was so long ago i coded
i know thats why i am stumped
There is your response either way
Not Found means most likely the message was deleted
yea thanks
when a user presses the button, it sends en ephmeral message whilst its thinking then edits it when the thinking is done, does it edit it too quickly?
i think ima make an whole new bot and start over so my mind refreshes
I'd go over Python basics again before doing that
yea ofc
@slate swan
show code so i can see
of the button?
yes
@thin raft it works!! Thank You!!
first thing that i notice is that arguments order is wrong in this line async def button_callback2(self, button, interaction_1st:discord.Interaction):
interaction should be before button
okay
I need help. I'm trying to make a sweepstakes bot for my Discord server, but when I add the giveaway feature I didn't want to start because of a bug in the console.
console:
Traceback (most recent call last): File "main.py", line 1, in <module> import discord File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module> from .client import Client File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/discord/client.py", line 27, in <module> import asyncio File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module> from .base_events import * File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/asyncio/base_events.py", line 296 future = tasks.async(future, loop=self)
can you show full traceback
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Administrator\Desktop\sparkles_bot\main.py", line 315, in button_callback2
await interaction_1st.edit_original_response(content=f"**Slow Down! You're on cooldown.**")
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 428, in edit_original_response
data = await adapter.edit_original_interaction_response(
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
yeah so looks like the error comes from the cooldown message
possibly cause you are using edit_original_response
is there something i should change it to?
you may want to try using interaction.response.send_message() or if it does not work interaction.followup.send()
await interaction_1st.response.send_message(content=f"**Slow Down! You're on cooldown.**")```
that?
try and see
okay
ill lyk, its weird. it works for some users but not for others
maybe other users are not on cooldown
show full traceback
and code
The code is very extensive
then show what you added and made it stop working
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Thank you
!paste
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.
full error?
bot.loop.create_task(winner_picker()) pretty sure this may cause error but will know when you provide traceback
You staff?
Accept add me
no im not staff
i dont accept dms if you need any help ask here
is there a limit to how many options can be shown in the options section, such as the add and rename option
25
thank you very much
its good to check docs always https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure
tyty ill do that
choices? array of application command option choice Choices for STRING, INTEGER, and NUMBER types for the user to pick from, max 25
but its 25 at a time right, there can be more than 25 options but it will only render 25 at a time. Am I correct
no max 25
Last I remember if you try to render more than 25 it errors
when it says max 25 it is max
when you type into the field and the options change, is that considered different thing from the pic I posted
It's the same field so it as well can only show 25
You can create an auto complete function and show 25 different options as the user enters text
i belive you can have more than 25 when you use autocomplete
Same field, so no, still 25
26 🧐
I see, thank you guys
wait I think I should mention the use case in case you guys have an recommendations
I wanted a command like the screenshot I posted above
and when the user types something, matching names from a list of around 1.2k unique strings show up.
Is there any way to make this work
Hello, just wanted to check if this was an appropriate place to ask for some guidance on a problem I have with a discord bot I've put together?
For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
Not sure
To be honest the fact I can't read has probably contributed to the issue I'm having
Throw it away and we'll see 
Yes, you would use an auto complete function and you would essentially use fuzzy matching to compare the current string to the strings you want to display and then display the top 25. I would also implement a caching system.

like i said you can use autocomplete
sorry I missed that, my bad 🥴
Trying to think how to word my question. Basically I have a really simple bot, one of its functions is to pull data from a small dataset when a user uses a command. The dataset consists of a list of 'players' and then 5 different stats for each player.
The command '!fact' responds with a random player and a random stat for that player
'!fact (player name)' responds with a random stat for that specific player
'!fact (player name) (stat)' responds with the specific stat for the specific player.
The problem I'm having is that there are two stats that are two words, I don't know what is causing the issue but when I use the command '!fact (player name) (two-word stat)' The bot responds to say that, paraphrasing, "(player name two-word stat) does not exist".
I.e. the bot thinks I'm looking for a player with the name of all four words combined.
All the single-word stats work fine, even for players with more than 3 names.
I've tried fiddling about with chatGPT to see if that could help but just went round in circles. I've tried making the two-word stats one word then creating a dictionary so that when the user puts the two words in it will know what they're after and it will format the response correctly. But that didn't work either.
I'm a complete novice, hence the probably daft question, apologies.
Any code we can follow?
😭
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.
Guess you can copy that piece of code into a file and send it, or use the ```
(your code goes here)
Cheers, I used the paste thing above so it's now in that link
Oh, okay
What are you passing in for query
Sorry, I don't know what that means 🙃
hehehe
Nextcord good ?
first project, haven't done any theory since about 2 hours on codecademy 3 years ago
What arguments are you providing when you run your command
Depends on what you're looking for in a bot framework
(player name) (stat)
or just (player name)
Or no arguments (which just picks a random player and random stat)
General commands and moderation and fun
Those are stuff you can make. What are you looking for in the framework? Support? Ease of use? Popularity?
Documentation?
The arguments that are causing the issue are:
'(player name) yellow cards' and
'(player name) red cards'
Documentation
Hm. You might prefer disnake
Though personally I would recommend discord.py (even if the docs aren't very good) since there's more support from more people that use it
Ok ty, me too i remmend discord.py
.split() is splitting those into "yellow" and "cards"
Ok that makes sense
Depends what you want it to do
Anywhere from very easy to intermediate
Sounds like something fun to try, uh?
And discord.py ?
I dont Like it maybe you will
Sure, I'd outline what you want it to do first
Well, just for learning, hmm, a greetings system (in & out), bad words detection, mute system, ban, aaand well, I guess some fun like say commands or similar
What you think?
Eating the documentation xd
Yeah I think that would be a good challenge for learning
:D
Look into databases
:D -> your profile face :D
You'll need a database to manage mutes and bans
JSON "could" do it but it doesn't mean it should lol
Yeah xD
But, but I will test it in a friend's server, no more than 50 as I said, so I guess I can try first with JSON
And then, Docker maybe?
(noob moment ^^)
For databases I recommend PostgreSQL or SQLite
Exactly!
Still can't fix the issue, but it's my problem. I shouldn't be launching straight into a project with zero knowledge of how things actually work. It's how I learn usually but I guess I need some theory embedded first. Thanks for your help.
have you checked out the "consume rest" operator?
where your command arguments would look like
ctx, player, *, stat
instead of
ctx, player, stat
which means that when using
!fact <player> eats beans daily
when using the first example arguments
stat will be equal to "eats beans daily"
when using the second example arguments
stat will be equal to "eats"
Thanks, yea I think I already have that operator;
async def fact(ctx, *, query=None):
command in cogs don't work and there is no problem
!paste
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.
all commands in that cog? or just 1?
are you sure your cog is even loaded?
stop askin dumb questions just google it lol
is there an example for a .py
that opens a modal when a button is clicked?
https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py here's one that opens on slash command, but opening it in a button is very similar
I have the same system for some of my internal tooling
i have it open when i can do / but idk if im being dumb but my brain isnt working on how to get it to open with buttons
You just do the interaction.response.send_modal stuff but inside the button callback
something like this?
class Test(discord.ui.Modal):
def __init__(self):
super().init__()
@discord.ui.button(label="Test", style=discord.ButtonStyle.red)
async def testbutton(self, interaction: discord.Interaction, button:discord.ui.Button):
await interaction.response.send_modal(Test())
@client.command()
@commands.has_permissions(administrator=True)
async def supportsystem(ctx):
view = Test
about = discord.Embed(title="Moon Solutions", description="This is our placeholder for our support system while we work on it!")
about.set_thumbnail(url="https://cdn.discordapp.com/attachments/1117391977516896370/1120006300835778641/6665-moon-foil-balloon.png")
about.set_footer(text="Moon Solutions")
await ctx.send(embed=about, view=view())
You can't have buttons in modals
You need 2 separate classes: one for the view containing the button, and one for the modal
im getting errors/tracebacks when trying to load in cogs
https://paste.pythondiscord.com/aribipipoj
You are not setting up your cog 2
That is what the error is telling u
!traceback
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.
Is your rip command inside a class (or cog)
If it is, you need to add a self argument as the first parameter
the commands name is test and it is inside a cog and self is the first parameter
def __init__(self, client: commands.Bot):
self.client = client
@app_commands.command(name='test', description='interesting')
async def test(interaction: discord.Interaction):
await interaction.response.send_message(content='interesting')
Really?
That clearly doesn't have self as the first parameter
And in here too no self in your function
where exactly should i put it?
As the first parameter??
async def test(self, interaction):
...
Before interaction:discord.Interaction it's a required arg for cogs
I already said it
ok it works but it shows a different traceback now
https://paste.pythondiscord.com/cuxerufatu.py
Show your full code of the extension file
import discord
from discord.ext import commands
from discord import app_commands
class cog2(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@app_commands.command(name='test', description='interesting')
async def tests(self, interaction: discord.Interaction):
await interaction.response.send_message(content='interesting')
async def setup(client: commands.Bot) -> None:
await client.add_cog(cog2(client))
also idk why thats there i had been deleted it
Do u need the main
this might be a issue since you are using .ext import commands and app_commands i would suggest this code instead
import discord
from discord.ext import commands
class Cog2(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@discord.slash_command(
name='test',
description='interesting'
)
async def tests(self, interaction: commands.Interaction):
await interaction.response.send_message(content='interesting')
def setup(client: commands.Bot):
client.add_cog(Cog2(client))
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
No, I asked for the extension file
sorry my mistake
or instead of slash command, you could use regular command such as the following:
import discord
from discord.ext import commands
class Cog2(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@commands.command(
name='test',
description='interesting'
)
async def tests(self, ctx):
await ctx.response.send_message(content='interesting')
def setup(client: commands.Bot):
client.add_cog(Cog2(client))
Regular commands used contexts, not interactions
cog1.py is where the codes from
Is there a proper extension file
And this doesn't seem like discord.py
i usees nextcord lib
It is an extension file
If you could use load_extension to load it, then it is
So do I add that in the main or the extension file
its right here theres not a lot since im only testing
The cog1.py file, or is that its contents?
hey could you clue me in on what problem you are facing?
because after reading your previous message im lost
im trying to load in a cog but it gives this traceback
https://paste.pythondiscord.com/jojogelafa
my other cog is almost the complete same and it works fine
alright, do you have a function or a for loop to load all your cogs file in your main.py?
self.cogslist = ['cog1','cog2']
async def setup_hook(self):
for ext in self.cogslist:
await self.load_extension(ext)
could i see your working cogs full code ? and your cog that not working full code?
ok this might not be a good idea puting file in a list and then load it. it will cause human error like typo etc. i would suggest putting all cogs in a 'cogs' folder and load all of them at once
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
No point
I'm having a difficult time trying to understand why would you have a cog named cog2 in cog1.py
tbh at this point i would rather you screenshare your project and see what wrong with it
his project is rather small, just making him share the code of both the cogs he's trying to load is good enough
i see
ok this is cog1.py and all of the content
https://paste.pythondiscord.com/ixamavuyiv
seems fine
https://paste.pythondiscord.com/qerivugezu and heres cog2.py and its content
cog2 is in its own file
im sorry im giving yall a hard time
alr, can you only load 1 cog and see what that brings?
it alright
^^^^^
i think ik why
your main file (containing your bot) and your cogs are all in the same folder, right?
because you define your command for test and tests as the same name name='test'
The error they sent said that the error came from a function named rip 🤷
seems like a saving issue then
But the code they sent doesn't match it
Traceback (most recent call last):
File "c:\Users\trace\Desktop\MU LFG\.vscode\main.py", line 49, in <module>
client.run('')
File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "c:\Users\trace\Desktop\MU LFG\.vscode\main.py", line 23, in setup_hook
await self.load_extension(ext)
File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cog1' could not be loaded.```
.
because that seems to be like a no
not even sure why you'd put your main file in the .vscode folder in the first place...
i moved them back they were before
alr, now save that and rerun
so i cant have the file and the class name be the same?
you can, don't worry about it
u can have the file name and class name be the same
im just askign is your name of your cog 1 file this: cog1.py
as shown here
under self.cogslist = ['cog1', 'cog2']
yes?
yes
ok
i moved the cog files back in the same file with the main file
https://paste.pythondiscord.com/avefejijuq
is there a better way to do that like in a different folder? that was there by default so i kept it
in the file or in the haste bin?
yes i just removed it from the hastebin
ah ok
That looks exactly the same as the past tracebacks you sent
client was underlined with yellow for some reason
I mean, just do it in the project folder
vscode generates a hidden .vscode folder for the IDE's purposes, you don't want to keep your code files in there
at this point ^^^
I bet my money on
- he's either never saving
- running a completely different file
he just has to show his project's file tree structure
do the command tree in your project folder & show us the output
i am sorry sorry to all three of you
it okay.-.
i didnt save 😢
.-.
jackpot
pain
im sorry
gl hf!
hahaha it okay
ok quick question is there a way to add multiple commands under a cog?
Just add more
class Cog(commands.Cog):
...
@commands.command()
async def command_1(self, ctx):
...
@commands.command()
async def command_2(self, ctx):
...
@commands.command()
async def command_3(self, ctx):
...
personally i would just put all my cogs in a 'cog' folder to be organised
!e
print(chr(1423)
@real harness :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | print(chr(1423)
003 | ^
004 | SyntaxError: '(' was never closed
!e
print(chr(1423))
@real harness :white_check_mark: Your 3.11 eval job has completed with return code 0.
֏
!e
print(chr(1423))
Me when people use random commands
Sorry
Cogs are classes you can't put them in a folder. You put cogs into python files that are called extensions and you put the extensions into folder. Yall confuse cogs and exts
And I thought cogs were gears ⚙️
but you can put them in a folder called extensions. then label the files cog classes and in the setup u just add each cog. therefore cogs are a part of the extensions you make.
plugins when
Quick question about ephemeral interactions.
async def my_command(ctx):
await ctx.send('This is a private message.', ephemeral=True)
this test function doesnt work for me when a user does $test
A bot command is not an interaction
i understand that emphereal only works with slash commands, buttons etc? is there a way to make it work with my $ commands?
Interactions are slash commands, buttons, etc.
And ephemeral only works with responses to interactions
You can't send an ephemeral message just like that
hmm. For some context I have a command called $leaderboard, it shows the scores for the user who uses it. I got it working where the bot DMs the user but I felt that was a little annoying. Was wondering if there was a way for only the user to see the scores in the same channel/chat
aight ty will switch over to / from $ 👍
🫢 ephemeral doesn't have to be slash commands btw.
That's exactly what was said above, thanks
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Can you answer me
I don't understand this
it means if you miss out on adding tabs or spaces between your lines of code you will get this error
why did you leave out line 20?
Look
I fixed it but didn't fix
?
That's what I said
On line 19 you use 2 (or 1 idk) spaces
On line 20 you use 4+ spaces
Have the same amout of spaces or use tabs
Most basic python knowledge you should have 
Didn't fix
And read/translate/screen read/whatever that message and the links related to indentation
!e ```py
def f():
print(1) # two spaces
print(2) # four spaces
f()
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 3
002 | print(2) # four spaces
003 | IndentationError: unexpected indent
when you choose amount of indentation you use you must be consistent
!e ```py
def f():
print
(
1
); (
print(2
)
)
f()
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
your welcome
inside () you can 
Hi
i mean that what i meant but i probaly should have phrase it better
Let's rewrite bobux like this
Yeah lmao
Speaking about that, I've nearly graduated. I'm finished juli 10.
i try putting timestamp in embed but instead jt shows this
Looks like you forgot to await timestamp()?
oh ye
You own bot?
yep
Gd joob
thank you
Can you send me how to create bot Embed In Language python Disnake.py
oh sorry i use discordpy only
Oh
But send it to me because it doesn't make much difference
It should be the same as discord.py (since they are forks and I doubt there's much debate over the implementation of embeds)
@grand hazel
heres an example i found online
import discord
# Create a new client instance
client = discord.Client()
@client.event
async def on_ready():
print(f"We have logged in as {client.user}")
@client.event
async def on_message(message):
if message.content.startswith('!send_embed'):
embed = discord.Embed(
title="Example Embed",
description="This is an example embedded message.",
color=discord.Color.blue()
)
embed.set_author(
name="Your Name",
icon_url="https://example.com/your-icon.png"
)
embed.add_field(
name="Field 1",
value="Value 1",
inline=False
)
embed.add_field(
name="Field 2",
value="Value 2",
inline=False
)
embed.set_footer(text="This is a footer")
channel = message.channel
await channel.send(embed=embed)
# Replace 'YOUR_TOKEN' with your bot token
client.run('YOUR_TOKEN')
Ty man
Discord.py easy?
yep
Where to learn
online
anywhere actually, theres tons of information everywhere
youtube google even chathpt
Thank you So much.
A learning guide for the discord.py bot framework written by members of our community.
Ty man
Is disanke.py better or discord.py?
which ever u are used to
then use that
But many people use discord.py
They use it
They use what they know
Neither
Choose whatever you want
They have different ways of doing things, there's no better and worse
What problem
3 problems:
- you should not name
Botinstanceclientits impractical - there is no such event named
onyou are possibly looking foron_readyevent Event reference: https://discordpy.readthedocs.io/en/stable/api.html#event-reference - you showed your token reset it and dont do that again (also when coding on replit dont put your token right away everybody can see your code which means they can see your token as well)
But I'm watching a course
and what does it change
Where can I use it Python
Only Replit
well you can code on the IDE on your computer like Visual Studio Code
if you still want to stick to replit there is something called Environment Varriables
hey so i have import interactions but its not working. done the pip install got the latest version but still getting "Import "interactions" could not be resolvedPylance"
do you have more than one python version?
installed on your pc
I have only mobile
if I do python --version It just says 3.10.8
are you on windows?
how do I check for multiple versions. im on mac
go to you Applications and see if you have more than one Python installed
nope just a 3.10 folder
okay do you code in vs code?
yea
do you see Python 3.x.x on the botton of your screen when on vs code
yea
choose the one that says 3.10.8
no just select the one with 3.10.8
looks like you have many python versions installed
ill do a clean uninstall of all my pythons
/usr/bin/python3 is your system python so dont uninstall that
okay I got it to work but now im running into a different issue. Use interactions.slash_command instead. they made some changes from v4 to v5. im doing a small scale test to learn it before trying to add it to my actual bot: ```from interactions import slash_command
client = interaction.Client(token="token")
@client.command(
name="ping",
description="Ping pong",
scope="server_ID"
)
async def _ping(ctx: interactions.CommandContext):
await ctx.send("Pong!")
@client.event
async def on_ready():
print("Ready!")
client.start()
the import is working but client = interaction.Client.... doesnt register.
Look at your imports
also wanted to know if I wanted my bot to be used on different servers how would I get around the scope="sserver_ID"
ok but why would it work without s if you dont even import interaction
class AutomaticModal(ui.Modal, title="Support"):
def __init__(self):
super().__init__()
issue = ui.TextInput(label="What is your issue?", placeholder="Please describe your issue here in as much details as possible!", style=discord.TextStyle.long)
async def on_submit(self, interaction: discord.Interaction):
if self.issue == "embed":
await interaction.response.send_message("lol")
else:
embed=discord.Embed(title=" ", description="Our database wasn't able to find your issue in our database. If you would still like support on this issue, please create a ticket describing your issue!", color=discord.Color.red())
await interaction.response.send_message(embed=embed, ephemeral=True, view=Button())```
is there a way to detect if a message in a modal is the same as one that is saved it will respond with a different message than if something else is typed?
"is saved" where exactly?
but yeah, if you can store that in some DB & react based on what your return value is, then that's perfectly possible
would it not work with something like that?
if the issue already exists?
its like an automatic support system for a bot but im just wondering if i can set it to respond with like different links when the modal input is something else?
just store your issues in a DB...
if it doesn't already exist, proceed, else tell the user with an ephemeral message he would be posting a duplicate
no like ur not understanding
so if they have the flagship bot in their server and they come into the "support server" then they can type the issue like "embed generating" in the modal and it will respond with a docs link or something
yeah, and why wouldn't a database storing the responses based on a given input be a bad idea?
would it not be possible for it to just be in the .py file?
for like "if self.issue == "embed":
await interaction.response.send_message("link")
else:
await interaction.response.send("get more help")
you could hardcode it, sure, but if you wanted to add new responses based on certain input, you'd have to restart your bot every time
how would i hardcore it?
you just did...
that doesnt work
...
the error message says it literally
"our DATABASE..."
I'm not sure why you're avoiding that implementation
you're not even using a db, lol
im not gonna write "the .py file cant find ur issue"
Our database wasn't able to find your issue in our database.

ite u got it fr
How many times do you want to say "our database"
Yes.
"no appropriate response has been made for this issue..."
I'll show you in a dict format
issue_inputs_dict = {
"embed": "I like turtles",
"hurting knee": "ask a kiss on it",
"default": "nothing was found"
}```
```py
appropriate_response = issue_inputs_dict.get(self.issue)
if appropriate_response is None:
await ... send_message( ... issue_inputs_dict.get("default") )
else:
await ... send_message( ... appropriate_response )
see what I did here?
based on a given input, we'll send an appropriate response
ofc, this implementation is for educational purposes & you should use a database instead
JSON my beloved
how many command categories in a help command is generally good? like a range of what is too much and what is fine
doesn't really matter, make it scrollable if needed
first page could be a legenda
i've got a select menu for that with a paginator, and the first embed is just like some info stuff about the bot
I wouldn't add that to help
maybe as a page in the legenda, but I think most people like to see all the commands first and info about the bot last
right but, it has information like choose from the category below, what should i change then? what should the first page have?
help me .-.
dotenv
like this .-.
yes, and the whole point of using environment variables is so that you don't need to keep your token in your script
please reset your token and remember to never share it
also I'm guessing you haven't installed the python-dotenv package which is why the import is underlined
what should the first embed be then? like some information text or should i remove it entirely and display commands already
would be helpful if someone could help here https://discord.com/channels/267624335836053506/1120750844405616660 😅
Tks you so much :>
You probably don't want all these access tokens and refresh tokens to be publicly available
its all hidden tho?
the thing is
u cant do anything with them without client secret
its basically useless
just a short description of all cogs
"Useless" you said, right?
Dunno, replit is shit imo
well free
Well that's one of the downside of such a free service, your data is free for users as well
thats not even the biggest issue with replit
Replit has lots of issues
they use a shared ip for everything running on the service
database?
y'e
i suggest supabase, u get a free 500mb of db storage
is there anything better than better-profanity?
Perspective API is pretty neat
whats the difference between the has_permissions and the default_permissions decorator
has_permissions is a bot side check; default_permissions enforce permissions in discord (admins can overwrite them)
so for example if you have an application command that uses has_permissions and that requires the administrator permission the slash command will be visible to all the members but they won't be able to use it (since you have that permission check)
instead if you use default_permissions the slash command will be visible only to members that have the administrator permission (though if an administrator change the permissions of a command from the settings of the guild the command will be visible and usable according to the modified permissions)
ah, so which one is better to use then?
depends
depends on your usecase...
if you need to enforce permissions check use has_permissions
if you want for example the command to be only available for you as the bot owner you will need to use has_permissions
oh, but i have my own check for developers, so if i want to use it for lets say a kick command default permissions is more flexible for server owners as well no?
yes
okay so use default permissions for commands that are used by others than me pretty much
possibly
Add Media Channels as an premium perk

sigh
I have problem in cogs
Everything good and cogs loaded
But there is no response to commands
Console errors?
No errors
But i can't use the / command
Then we'll need code, screenshots of what happens when executing command etc.
probably he/she is not syncing them
Wouldn't say there's no "response" to the command in that case
Unless they missed the point of slash commands that it's not prefix commands with / as prefix
Hello, I am trying to create a discord bot that will analyze stock news and tell if it is good or not, please DM me if you are interested in collaboratign
is it possible to make a discord.py that uses buttons if 2 people click the same button it will create a text channel linking to a database
How do you link to a database?
i dont rn im going to create a new .py for it
like a whole new client
quick question
guys is it possible to put a link in a set_footer(text="link here")
not a clickable link
something like a queue system where there is buttons attached to an embed and then someone will clikc it and it will place them in a queue until someone clicks it and then it create a text channel
so when 2 people interact with the button it creates a new channel
class changenamebutton(View):
def __init__(self):
super().__init__(timeout=20)
@button(label="Change Name", style=discord.ButtonStyle.blurple, custom_id="namechange", emoji="📝")
async def gemtransfer(self, interaction: discord.Interaction, button: Button):
await interaction.response.send_modal(namechangemodal())
async def on_timeout(self):
for button in self.children:
button.disabled = True
I can't figure out how to edit the original message with the disabled buttons after I have disabled them in the on_timeout function
await self.message.edit(view=self)
AttributeError: 'changenamebutton' object has no attribute 'message'
Show the code where you use this view
You need to set the message attribute
for now not being properly used I was just testing some stuff with the bot, but
@bot.event
async def on_message(message):
if message.guild == None and message.author.id != 1120682150639968296:
await message.channel.send("test", view=changenamebutton())
have a database
store all user IDs of allowed members in there
have an event (on_member_update) which checks when someone gets a role => if not in database, remove given role
no, you'll need an actual database
because once your bot restarts, you'll ofc want to keep your list and not start all over
unless you hardcode those user IDs and will never change them in the future...
then you can use a botvariable with a list of user IDs, sure
should have a before and after argument
if it's in a class, it also needs the self first ofc
irrelevant
if you're in a class, you just add self, else you only need the 2 parameters I told you
make sure you have member intents enabled
else that event will never trigger
so i made a cog class using commands.GroupCog afterwards when i went to go and run the main file it didnt register the command i had in the main file
when i press run in vscode this comes up vscode % /usr/bin/python3 /Users/zagzag/vscode/main.py but nothing happens how do i fix?
intents.messages = True
intents.message_content = True
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
@bot.event
async def on_ready():
await bot.change_presence(status=status, activity=presence)
print(f'Loaded {bot.user}')
async def on_message(message):
print(f"{message.author}: {message.content}")
if message.content == "setupInfo":
await bot.wait_until_ready()
print(f'worked')
channel = bot.get_channel(1120938903487131648)
await channel.send(embed=info_embed)```
the onready works, but my onmessage embed thing doesnt
it worked when i used a client not a bot
can someone tell me why and how to fix it
Where's the event decorator
Also if you have all these intents enabled, you can just do
bot = commands.Bot(command_prefix=prefix, intents=discord.Intents.all())
anything else that would not make it work
And messages is already included in default so that one is already redundant
worked thanks so much

aren't custom emoji's <a:name:id> or <:name:id>? or are they just <a:name:> or <:name:>?
so that would just be <:pithink:> right?
o.o how do I get the id #?
Put a \ in front of an emoji
ooooo ty!
u dont really need the name u can substitute it with a placeholder also
<:_:id> will work too
Or with a better name 
\😻
how to remove the page counter in pagination
hello i have this code for send an embed when a member join a guild :
guild_id = client.get_guild(member.guild.id) # This function is called get_guild so presumably it returns a Guild object
channel = guild_id.get_channel(recuperer_valeur(member.guild.id, "config_bienvenue_id"))
await channel.send(embed=embed)
but i have this error :
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event await coro(*args, **kwargs) File "/home/container/bot proto/main.py", line 33, in on_member_join await channel.send(embed=embed) ^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'send'
channel is none
use something like
channel = guild_id.get_channel(...) or await guild_id.fetch_channel(...)
So that you first try to get from cache and otherwise make an API call
hummm okay thanks !
how to make something to send a message at sharp midnight
class changenamebutton(View):
def __init__(self):
super().__init__(timeout=20)
@button(label="Change Name", style=discord.ButtonStyle.blurple, custom_id="namechange", emoji="📝")
async def gemtransfer(self, interaction: discord.Interaction, button: Button):
await interaction.response.send_modal(namechangemodal())
async def on_timeout(self):
for button in self.children:
button.disabled = True
@bot.event
async def on_message(message):
if message.guild == None and message.author.id != 1120682150639968296:
await message.channel.send("test", view=changenamebutton())
Hey, I am trying to disable my button after timeout but self.message.edit(view=self) does not work, would anyone know how to edit the message?
You want to send message every midnight?
Well
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
You need to specify time
Not every , actually just an example . Trying to make reminders
!source remind
Commands for managing your reminders.
You can check out how the remind command is done here
.....
!d disnake.Embed
class disnake.Embed(*, title=None, type='rich', description=None, url=None, timestamp=None, colour=..., color=...)```
Represents a Discord embed...
🫡
indentation lmao
Hello. Im trying to convert a $ command to an interaction. would anyone know how to convert this part? ```@bot.command(name='score')
async def show_score(ctx, user: discord.Member = None):
guild_id = ctx.guild.id
target_user = user if user else ctx.author
owes_text = []
owed_text = []
ive got this so far: ```my_guild = discord.Object(id='server_id')
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=my_guild)
await self.tree.sync(guild=my_guild)
intents = discord.Intents.default()
client = MyClient(intents = intents)
@client.tree.command(description = 'display the score to the user')
async def score(interaction: discord.Interaction):```
having issues with ctx and how to change it with regards to interactions
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
Just look through the attributes and methods there and use what you need
would really appreciate an answer if someone knows 
reminder = await self.bot.api_client.post(
"bot/reminders",
json={
"author": ctx.author.id,
"channel_id": ctx.message.channel.id,
"jump_url": ctx.message.jump_url,
"content": content,
"expiration": expiration.isoformat(),
"mentions": mention_ids,
}
)
Hello, i saw this in reminder's source code. Is this some kind of personal database for bots?
Yes
How can i use it? I couldn't find any documentation for it
It's most likely a custom API that is only made for @unkempt canyon
So you cannot use it, make your own
how do i make my own?
Learn web development and make an API that accepts POST request and the JSON body as shown above and then saves everything in a database
Or just forget about that API part and just use the scheduler for now as you can see below in the source code (https://github.com/python-discord/bot-core - https://bot-core.pythondiscord.com)
You should try to read code more and not just stop once you see something interesting
i just need some visual advice, does it look good when bots add the "Requested by {whatever} | time" at the bottom of the embed or does it not look good
Depends for what
Sometimes it's useful and nice to have, sometimes it's just pointless - people can scroll the chat or look up to know who requested it - and the time, well it's shown on Discord's UI anyways so that's definitely useless - depending on what time you show
If it's something like a reminder etc. then yes, it may be useful by showing who has set the reminder and the time when they have set the reminder
ah okay thanks
Hey, I'm using a discordapp, not a discordbot. and I am querying the discordapi so I can get my roles and all I am getting is the role id? How do I convert this to a role name?
Not possible, use a bot token
Yes
What's the point in being able to "read" your roles if you cant actually read the roles? lol
And how do I convert that to a role name without actually having a bot in the server? lol
You don't
Then again - What's the point? lol
What can I do with an ID?
My account owns the server I am querying. the app has the above perms.
I dont want to invite a discord bot to the server just to convert a role id to a role name. So what can I use a role id for?
Everything related to the API that uses role IDs
I appreciate how you're replying without actually giving anything useful
Because I've already told you
Use a bot to get specific data about the roles in a guild
If you're unhappy about that -> https://dis.gd/contact
sooo the cmd WITHOUT the buttons is working perfectly, but WITH the buttons the cmd just stops...i added different logs, here is the result:
- the bot IS making the file, but not sending it
help .-.
Enable the message content intent in the developer portal, as the error says - if you'd read it
ohhh
Did you get any errors/tracebacks
Because you should
nope
Do you have any error handlers
discord.ui.View(select)
Is not how you add items to views
!d discord.ui.View.add_item you need to use this method
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
yeah
Then it's probably eating the tracebacks
the file is being made, everything is working except the sending of the message/embed
Show the code of the error handler
can we set title color for embed in discord
No
but i saw some bot having it blue
Show screenshot
Click it, it's a hyperlink, isn't it
Where
!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...
u see on the botton by altpapier helpfund the bot etc
i think its footer
Set the url kwarg
It is
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
still nothing :/
I get this error every time I try to import app_commands
make sure discord.py is up to date and uninstall any other dapi wrappers you have (eg, py-cord)
Works! Thanks!
What i need to install to use cogs ?
oof
And how are you setting them up and loading??
It's not sending or the select doesn't respond? Try to be more specific
And your on_select is unused, also that's not how you set select callbacks
What is the library you're using
Then you need to await the load_extension
It doesn't work
What doesn't work? Be specific
Cogs
See
That doesn't explain anything
And I already told you to await the load_extension
can yall help me? I cant download easy_pill ive already tested pip install eas_pill just says it didnt find the file even tho i reinstalled the whole python
Yeah i await it
And?
Still doesn't work
1m
What happened if you try to install it? Or does it just say that it couldn't find the package
Find the file?
Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install easy_pill': Det gÕr inte att hitta filen.
That
the last bit is swedish
You probably don't have pip installed
but i do
You didn't even call the load function
In cog file
no where u importfrom the top

bruh i need this fr fr
I don't know windows stuff
he did. and how it's anyways related to the problem?
oh mb i saw wrong lol
Try answers from SO
https://stackoverflow.com/questions/37220055/pip-fatal-error-in-launcher-unable-to-create-process-using
There is a different thing but error is the same
(this)
python -m pip install --upgrade --force-reinstall pip
Also anyways better to check if you do have pip in C:\Program Files\Python310\Scripts\
maybe you have pip for some another python version and for that you don't
Thx cog file loaded but the command is not responding
now i get this ERROR: Could not find a version that satisfies the requirement easy_pill (from versions: none)
ERROR: No matching distribution found for easy_pill
!pip easy-pil
By running the command python -m pip install easy_pill
Try easy-pil instead of easy_pil
YES IT WORKED
AHHH FINALYYYYYYYY AFTER 1 MONTH LOL TYSM
wait.... it still didnt solve my problem
my code still says i got an error .........
import discord
from discord import File
from discord.ext import commands
from easy_pill import Editor, load_image_async, Font
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("The Bot is officially online!")
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel
background = Editor("pic2.jpg")
profile_image = await load_image_async(str(member.avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90, 475, 240), outline="white", stroke_width=5)
background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
image_bytes = background.image_bytes
file = File(fp=image_bytes, filename="pic1.jpg")
await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name}**. Have an great day!.**")
await channel.send(file=file
Mind cheking my code to see if i did anything wrong
bc it only says that easy_pill is wrong
What does it say?
Traceback (most recent call last):
File "c:\Users\OneDrive\Dokument\Discord Bots\Learning.py", line 4, in <module>
from easy_pil import Editor, load_image_async, Font
ModuleNotFoundError: No module named 'easy_pil'
and when i do easy-pil it givs me even more errors
well i am afk ima go eat
What was the output of the pip install?
How are you running the file?
Show your error handler code
the bot stops here: Command execution started.
That's no error handler
wha~
What what?
then maybe some of these functions (you can add prints to check)
prompt = await translate_to_en(prompt)
imagefileobjs = await generate_four_pollinations_images(prompt, ratio.value)
are freezing? show their code too if they are
i might be mixing error handler with something else... can you explain a bit?
uh... alright
!d discord.on_error - error handlers in discord.py are generally events, like this one
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
ohh that thing
huh wdym
What did you got when you used
pip install easy-pil
(when installed library in terminal. you can run it again and show, doesn't matters)
And what command are you using to run your code
File "c:\Users\OneDrive\Dokument\Discord Bots\Learning.py", line 4
from easy-pil import Editor, load_image_async, Font
^
SyntaxError: invalid syntax
it said it didnt find the file
but it did work before
that worked... now i got new errors 😅
- this is the error i m getting:
[2023-06-21 22:24:09] [ERROR ] discord.ui.view: Ignoring exception in view <PollinationsView timeout=180.0 children=1> for item <Select placeholder='Select an image to view' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Image 1' value='0' description=None emoji=None default=False>, <SelectOption label='Image 2' value='1' description=None emoji=None default=False>, <SelectOption label='Image 3' value='2' description=None emoji=None default=False>, <SelectOption label='Image 4' value='3' description=None emoji=None default=False>]>
Traceback (most recent call last):
File "D:\shayan\python installation files\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "D:\Raza\discord orders\gpt4- hugging face\new era\final 3\smit smit\smit dall-e\main.py", line 506, in on_select
await interaction.response.edit_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'files'```
2. the bot is not showing the 4 images, it is showing nothing
code https://srcb.in/IhlMhBLqiZ
?
that's not what i asked
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
what should i do now?
re-read and try to answer again 😄
thanks!
yeah yeah that was da issue
it said that it worked it succesfully installed it
ok, i guess it was so. and second question?
dont get it
With which command are you running the file
Like usually it is
python main.py
how are you running your program?
What's the first line of output when you run it?
Something that looks like path
from easy-pil import Editor, load_image_async, Font'
the yellow + blue text
hey i do have a question regarding a currnt project just simpple querry
if anyone can clear the doubt
ok
show the output of doing pip -V in terminal
aye bro can i ask sometthing pls
Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" -V': Det gÕr inte att hitta filen.
yea?
sorry i mean ya can i ask something pls if u dont mind
if it's about discord bots, sure
thx mate
just ask. and someone will reply
So wait. How did you install the library? You said you got "successfully installed". What did you run for that?
so i did pip install easy-pil just like catlover said and that was succesful
i used pip install easy-pil
huh
import discord
import os
client = discord.Client()
@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($hello):
await message.channel.send('Hello')
client.run(os.geten('TOKEN'))
but now i get this Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install easy-pil': Det gÕr inte att hitta filen.
i see
it was python -m pip
do
python -m pip -V
or just
python --version
🔼 I don't know why it doesn't work
yea
so i am making a discord game bot
so when user type command start i fetch server details like guid id and etc and store it in mongo db to be userd in future
the game use a map like stuff
so i assgin a x and y cooridnate to a server
i want to make sure that one server gets only one value
and if user type start comand agian it should not work
any way to detect that and make it work only once per server
i know i can compare the guid id and chekc if currnt id exists or not
but wont it take to log if there are many guid ids?
i want the code to be fast
any other way for that sir ?
@vocal snow
you need to enable message content intents, and probably update discord.py
pip 23.1.2 from C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pip (python 3.10)
ok thank you
uhm
should be good
add this
intents.message_content = True
bot = discord.Bot(intents=intents)```
what is that even?
ok
If you are using mongodb to store the guild ids, then it should be pretty fast
there's a red line on line 16
I was checking that you have pip corresponding to the python you are running
try
python -m pip install --upgrade --force-reinstall easy-pil
and running the code again idk
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
decorator must be indented the same as the function it is assigned to
sorry
so i can go with that compare stuff
no need to worry about that it will fech the id and then compare and then assgin the value?
shall i make a specifice documetn for it ?
indentation line rest is good
and if u are using client then replace that bot form code i give u wiht client
haii sirrrr
ok
how do I fix indentation line?
yeah also just noticed @main fiber why to create client and bot at the same time
and only use client
unindent it?
oh ok thanks
lol
just type back space at @client thing in line 15
Do you see why lines 11 and 12 don't have an error, but 15 and 16 do?
What's different between them?
indentation
yea thanks i think it worked idk
I'm aware, that was directed at OP
sorryyyy i am also a newbii so exited
@main fiber u can use indent-rainbow extention too
if u get confused in that sometimes
I mean I fixed it but on line 17 it has a syntax error
ok
u shold type back space in line 23 2 times to get your client.run out of that decorator
k
I'm getting so much pings lol
Don't want to be toxic, but learn some python basics before creating a bot : )
!e $hello
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | $hello
003 | ^
004 | SyntaxError: invalid syntax
vitness i sent in dms bc i couldnt send here
I would highly recommend going over the Python tutorial I linked above, discord bots are not beginner-friendly and are an advanced topic
ok
ohh btw can u review my code of so far pls
its a simple code that fecht server info and
assign it X and Y cooridnatess to be used in map and i have some doutbs if u can clear to ?
you cant just put random characters if you want to check for strings you need to say that it is a string by puting it in "
(or ')
like you did line below
@main fiber
ok
i can help you solve some problems but i dont think im right person to check code in project im not into
and replce that ; with : and give return funtion some indentation
am i wont mind i want review on it
i can look at it but i wont promise i will read everything carefully
haha sure thx
shall i share live share extention of it
vs code live share i mean
or lets just pass that i will explain my code to u here
never used it maybe you have it on github?
didnt putted it there so far
alr i will upload it when its bit funtunabel
currnty it just do one thing
when u type start command
if its not too long you can upload it here
alr let see
btw how to use that python ext of discord to decorate your code in discord msg
!code
yeah but can be just py in short
import discord
from discord.ext import commands
from pymongo import MongoClient
from serverinfo import ServerInfo
from location import LocationManager
from datainfo import MONGO_CONNECTION_STRING, MONGO_DATABASE_NAME , SERVER_INFO
import setting
logger = setting.logging.getLogger("bot")
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Set up your bot
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name} ({bot.user.id})")
print("Bot is ready")
@bot.command()
async def start(ctx):
# Create an instance of the ServerInfo class
server_info = ServerInfo(ctx.guild)
# Assign a location to the server using LocationManager
location_manager = LocationManager()
location_manager.assign_location(ctx.guild)
server_info.x_coordinate = location_manager.x_coordinate
server_info.y_coordinate = location_manager.y_coordinate
# Store server info in MongoDB collection
client = MongoClient(MONGO_CONNECTION_STRING)
db = client[MONGO_DATABASE_NAME]
collection = db[SERVER_INFO]
server_data = {
"_id": server_info.guild_id,
"guild_id": server_info.guild_id,
"guild_name": server_info.guild_name,
"guild_pfp": server_info.guild_pfp,
"region": server_info.region,
"member_count": server_info.member_count,
"owner_id": server_info.owner_id,
"x_coordinate": server_info.x_coordinate,
"y_coordinate": server_info.y_coordinate
}
collection.insert_one(server_data)
client.close()
await ctx.send(f"Location assigned to {ctx.guild.name}: ({server_info.x_coordinate}, {server_info.y_coordinate})")
# Add more commands or event handlers as needed
bot.run(setting.Discord_api , root_logger=True)
its main.py file as i have stored the private info in other file
wont be a issue
from location import assigned_x , assigned_y
class ServerInfo:
def __init__(self, guild):
self.guild_id = guild.id
self.guild_name = guild.name
self.guild_pfp = str(guild.icon.url) if guild.icon else None
self.region = self.get_region(guild)
self.member_count = guild.member_count
self.owner_id = guild.owner_id
self.x_coordinate = assigned_x
self.y_coordinate = assigned_y
def get_region(self, guild):
try:
return str(guild.region)
except AttributeError:
return None
this is serverinfo.py
import random
from pymongo import MongoClient
from datainfo import MONGO_CONNECTION_STRING, MONGO_DATABASE_NAME, RESERVERD_COLLECTION
class LocationManager:
def __init__(self, connection_string=MONGO_CONNECTION_STRING, database_name=MONGO_DATABASE_NAME, collection_name=RESERVERD_COLLECTION):
self.client = MongoClient(connection_string)
self.db = self.client[database_name]
self.collection = self.db[collection_name]
self.x_coordinate = None
self.y_coordinate = None
def assign_location(self, guild):
x, y = self.generate_random_location()
while self.is_location_reserved(x, y):
x, y = self.generate_random_location()
self.x_coordinate = x
self.y_coordinate = y
self.store_location(guild.id, x, y)
print(f"Assigned location ({x}, {y}) to server {guild.name}")
def generate_random_location(self):
return random.randint(0, 1000), random.randint(0, 1000)
def is_location_reserved(self, x, y):
query = {"Data": "Server_coordinates"}
reserved_data = self.collection.find_one(query)
if reserved_data:
reserved_locations = reserved_data.get("Locations", [])
return any(location.get("X") == x and location.get("Y") == y for location in reserved_locations)
return False
def store_location(self, server_id, x, y):
query = {"Data": "Server_coordinates"}
reserved_data = self.collection.find_one(query)
if reserved_data:
reserved_locations = reserved_data.get("Locations", [])
reserved_locations.append({"ServerId": server_id, "X": x, "Y": y})
update = {"$set": {"Locations": reserved_locations}}
self.collection.update_one(query, update)
else:
reserved_locations = [{"ServerId": server_id, "X": x, "Y": y}]
data = {"Data": "Server_coordinates", "Locations": reserved_locations}
self.collection.insert_one(data)
def close_connection(self):
self.client.close()
# Create an instance of LocationManager
location_manager = LocationManager()
# Access the X and Y coordinates after assigning the location
assigned_x = location_manager.x_coordinate
assigned_y = location_manager.y_coordinate
this is location_manager.py
want me to explain the code in short as i didnt added any comments at moment
?
first what i can see you create MongoClient instance each start command call which is prolly not what you want you should create one at startup and use it each time
i didnt get what u are trying to say here
i am noob ig
that you connect to mongo db database each time someone runs start command
you should establish connection when you start the bot store this connection in a varriable
and then use it
something like:
bot.db = MongoClient(...)
so shall i put that in on_ready funtion ?
can be
yeah
let me do it
shall i assgin it as global variable
wdym
if you are thinking of using global keyword
no never do that
assign it to bot
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
why it sent twice huh
so i should be replacing that bot.test with connetion string
no
its just example with simple string
you are supposed to put MongoClient instance here

show it
last one
was kidding about error btw
programming jock
if something works dont touch it
idk what just i did btu it workd
do you use it tho?
yaa used
it and workd well
want me to show whole code?
btw i do have a doubt if can clear ?
?
as u can see in location_manager
not only there but for start command to
i want to add a error hander
in which if person types that start button in a server whose data already exists with my database
then it should throw a error saying that u are registerd
so i was thinking to store all guids id in a document in mongodb
and compare it when person type that command but it feels like it will increase load on my machin only
and if there are a lot of server it will take time for it to chekc
so any way to just do it fastly
hm no idea
What's the prob
It would not be slow
Just store the registered guilds in mongo db, and when the user makes the command you can easily check
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/Users/zagzag/vscode/zagzag.py", line 501, in verify_setup
await channel1.send("type !verify to verify")
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'verify-setup' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
channel1 is None
its not tho
Errors don't lie, it is.
what is it then
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
r.set(f"vchannelid {str(interaction.guild.id)}",verify_channel.id)
r.set(f"vrole {str(interaction.guild.id)}",verified_role.id)
channel = r.get(f"vchannelid {str(interaction.guild.id)}")
channel1 = client.get_channel(channel)
await channel1.send("type !verify to verify")
await interaction.response.send_message("verification system setup")
channel2 = client.get_channel(1112053260879147130)
await channel2.send(f"verify-setup command used by {interaction.user}")
i set it up
what's r



