#discord-bots
1 messages Β· Page 229 of 1
btw did you actually use that command i described or just pip install discord.py? the former is for installing the development version which isnt recommended
i used this:
await interaction.edit_original_response(content="Hello again !")
the one u said to use.
i was talking about the pip install command, but that line looks correct
Inter process communication
to install the library i had just used pip install discord.py
any recommendation before I start to research?
This
ty
Ipc let's two processes communicate
So your site can request data from your bot
And vice versa
It's like an api
But way easier to use
discord-ext-ipc is what i had once used, but the project died
now on my last exploration i just used the same event loop to host the webserver and bot
i made a aiohttp application from scratch to add routes and stuff more like a mini fastapi by mini i mean really mini like one files mini 
I REMEMBER THAT
it was sadge updating to 2.x
and no longer suported :c
I also did once in two separated py instances but connected through a mysql
exploring on github is so complicated
they have an examples folder
where the exploration
well you can say, i dont know how to find stuff on git hub
i have never used it like that
i have only clicked on links
technically i dont really look at github either i just discover or click on interesting repos i may find when searching up on coding stuff
thats how u find hidden gems
whats ur question tho?
you see this sample code for discord.ui.Select
one like this of discord.ui.Button will really help
i am trying to find it
dont really need to subclass buttons in general tho
u can use the decorator
!d discord .ui.button
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
wut
.
y the diffeerence
*discrimination
anyways any reason u wanna subclass in general?
well yes
thats why i was finding one with like a basic method of how buttons are used generally
in buttons you only subclass the view class right?
bunch of ways u can do it
the common one
nice let me see
whats the use case one way is as show in the link i gave u
view = discord.ui.View()
button = discord.ui.Button()
button.callback = some async function
view.add_item(button)
this is way too more of a monkey patch way tho
i was trying something like this and i was only getting one button
u cant stack
i have to separate call back of each
uh no
then make diff
oh well
i think i misunderstood call back with on_interaction thingy
okay thanks
discord.ext.commands.errors.ExtensionFailed: Extension 'market.itemFunctions' raised an error: TypeError: Command 'update' is a duplicate
what does this error mean?
u have two commands with same name
with open(f'users_data/{ctx.guild.id}.json', "a") as users_data :
sdl = "\n"
json.dump(dict, users_data)
users_data.write(sdl)
return await ctx.respond(embed = discord.Embed(title = f"", description = f"\β
*γ» Successfully saved your payment method infos as :*\n\n> **Name :** `{payment_method_name}`\n> \n> **Address / Link :** `{info}`\n> \n> **(Extra) Fee :** `{fee}`", color = 0x45b557))
print(Fore.GREEN + "Successfully calculated for {ctx.author}")
users_data.close()
pls help i don't know what's the problem here
you meant that only a specific permission can use a command?
@commands.has_permissions(administrator=True)
@code_bot.tree.command()
async def add_coins(interaction: discord.Interaction , user_id: str , coins: int):
await interaction.response.send_message("You have admin permission.")
how do i check for this?
u can change administrator to the permission u want it to have
@code_bot.tree.command() @commands.has_permissions(administrator=True) async def add_coins(interaction: discord.Interaction , user_id: str , coins: int): await interaction.response.send_message("You have admin permission.")
should work like this i think
it is not working
is a error coming?
you are using data which is not correct json format
hm ?
can you explain more ?
not unless i have seen the code
no no
it is not giving an error but even when i don't have admin perm it is responding with that message
oh yeah
you have to do an error thingy
`@code_bot.tree.command()
@commands.has_permissions(administrator=True)
async def add_coins(interaction: discord.Interaction , user_id: str , coins: int):
await interaction.response.send_message("You have admin permission.")
@add_coins.error
async def add_coins_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permissions to use this command!")`
like this
still working the same π’
bruh
@code_bot.tree.command() async def add_coins(ctx, user_id: str , coins: int): if ctx.author.guild_permissions.administrator: # Execute the command await ctx.send("You have admin perms") else: # Send an error message await ctx.send("You don't have permissions to use this command!")
i hope this works xD
now it is giving error
Traceback (most recent call last):
File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\JAPAN COMPUTERS\Desktop\Codestore Bot\zmain.py", line 104, in add_coins
if ctx.author.guild_permissions.administrator:
^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'add_coins' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
oh im stupid
@code_bot.tree.command() async def add_coins(interaction, user_id: str , coins: int): if interaction.user.guild_permissions.administrator: # Execute the command await interaction.response.send_message("You have admin perms") else: # Send an error message await interaction.response.send_message("You don't have permissions to use this command!")
i used ctx instead of interaction

bro it is working
Nice
thanks alot
no problem
huh ?
help pls,i don't know what's the problem :/
from discord.ext import commands
import discord
import time
from colorama import init
from colorama import Fore, Back, Style
import json
config = json.load(open("config.json", encoding="utf-8"))
init()
print(Fore.BLUE + """
Discord : --link--
Instagram : @true_medra\n\n\n
""")
can anyone help?
config.json is probably invalid json
who can help me with discord bot
did Discord really fuck up the hyperlinks in the embed descriptions π
?
oh my bad
^
search for a json format checker online, there's a bunch and they're really useful to see if you missed something
i use that
hm ?
The content of the JSON file
i cant fix my stupid bot tho
[2023-04-18 03:32:02] [ERROR ] discord.client: Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\georg\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\georg\OneDrive\Desktop\BOTVERIFY6.py", line 45, in on_member_join
captcha_image = generate_captcha()
^^^^^^^^^^^^^^^^^^
File "C:\Users\georg\OneDrive\Desktop\BOTVERIFY6.py", line 28, in generate_captcha
image_data = image.generate(code)
^^^^^
NameError: name 'image' is not defined
audio_state = participant.voice.audio
AttributeError: 'VoiceState' object has no attribute 'audio'```
Send code
Read the error, how clearer could it be
!e
uwu
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | uwu
004 | NameError: name 'uwu' is not defined
The variable doesn't exist
yes
Send it to me
i changed 15 times things or anything but is not working
You are not defining an image variable
i am trying to make a discord bot which translates the given content.
but i am getting a problem where its also translating the language code with the content itself. I will be really thankful if someone can help
I can help if you describe the problem better
so basically i made a bot which translates the sentence its given
it does that with googletrans library
the syntax is this
!translate how are you ru
the !translate is to activate it
how are you is the sentence to translate
and ru is the language code
u with me?
what's your question
.
yes what's your problem
the bot is also translating the language code with the sentence
just check if the last word is a valid language code with .split()
!e ```py
string = "how are you ru"
text = string.split()[:-1]
language_code = string.split()[-1:]
print(text)
print(language_code)
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['how', 'are', 'you']
002 | ['ru']
if language_code.lower() in (
"en",
"es",
"ru",
"fr"
):
translate(text, language_code)
else:
print("error")
thx so much i will try it in a second
github bot not works
chatgpt bot not works π¦
I cant make a simple bot to work
?
nothing is working
only errors and errors and errors
idk how to even fix them even if i ask chatgpt he is fixing and and again another errors
Perhaps we can help fix them for you? ChatGPT will just lead you into a game of whack-a-mole, it sucks. Don't ask it.
Isnt chatgpt good for making simple bots?
It's bad for pretty much anything programming related
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I got this
I want verify bot for new members to verify and after they got verified the bot should give them a role
can i dm u the code ?
ohh sorry
i thought i could send u the code and maybe u would implement the changes in that?
i can't code your bot for you
i can't code it for you
thats fine i will just do the changes and if it doesnt work i will ask u
is that alright?
ok
noice
@smoky sinew uhh sorry to ping but its not working
it's @commands.hybrid_command
also you can remove name="ping" and with_app_command=True because those are the defaults
then check if the cog is loaded
also make sure your bot tree is syned
I think I have asked this before but is it not possible to sync a change to global slash command to one guild only
as syncing with guild specified only syncs the guild commands
!d discord.app_commands.CommandTree.sync_global_to if you're using dpy 2.0
No documentation found for the requested symbol.
copy_global_to(*, guild)```
Copies all global commands to the specified guild.
This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.
Note that this method will *override* pre-existing guild commands that would conflict.
using that results in 2 copies of slash command in my server, I know it is because I synced a global command before but I couldn't find a workaround for it
then your only choice is removing your global commands
trying to make a discord bot, the bot currently stores the user id as a string but when Im trying to call back the user name it retains the indents and is unable to make a comparison. Can anyone give me guidance on how to do this verification properly?
https://pastebin.com/nHSB2hYK
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.
all that is really unnecessary
if you used a bot instead of a client you could do:
@bot.command(name="startgame")
async def start_game(ctx, members: commands.Greedy[discord.Member]):
for member in members:
print(member.name)
i think mudkip purposefully gives bad advice so that Leaf will be the best bot in the world
is true @smoky sinew ?
Anyone knows how to directly access discord API using https requests (or something similarly "low level"), not through a library like discord.py?
I can't find any tutorial for that.
Just use an http library of your choice (requests, httpx) and read the discord developer documentation to check the endpoints, authorization info, etc
I'm lost in the documentation π΅βπ« Do you know any beginner friendly tutorial?
first bot i ever made jumped headlong into it. Thank you so much. I'll definelty go that route on my next one
Heh no it's the only
Most of API docs are similar
- Find how to authorise
- Use endpoint you need
Is this normal behaviour? It's RESUMING almost every hour.
0|blitzcra | [2023-04-18 05:12:46] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 05:35:35] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:05:45] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:20:21] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:36:14] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 08:22:43] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 08:56:19] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 09:28:45] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.```
Yes
It's normal
what are you trying to make? We can point you to the specific resources
also are you familiar with http at all?
Good example of why not to use the on_ready to setup stuff.
You mean this?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready(self):
print('Bot is ready!')```
Yes
So where should I keep it?
Keep what?
I mean to print the message when bot is online
Where can I add it to avoid this kind of stuff?
That it will print that message? I mean it's a nice reminder that the bot is still online.
But what you mean is to get rid of it completely?
No I was implying that it's a nice example of why you shouldn't use on_ready to setup your bot, since it triggers more than once.
I cant make a faking bot to work
People already made this bot snd shared the code. Why i cant make them to work
What is the issue?
He isn't using it tho
Idk
Oh. I can only see the "Bot is ready" message once, but I'm encountering an issue where the message "Shard ID None has successfully RESUMED session" appears multiple times every hour or so
Do you have an event like on shard resume?
Is this Hikari btw?
I don't think so. My bot is in only one server btw
What is Hikari? π€
nope π
Ah nvm the logging just looked like it.
Nothing in particular, just want to learn how it works.
Can I post my code for you to review? Maybe you could see what's going on
Sure.
I will DM you the code and then we can keep the conversation here
!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.
I know. I just prefer to DM you the link to not post my code in public. But we can keep the conversation here, it's just for the link.
oki
I still recommend changing the API key since there are people that like to guess paste urls.
Changing it rn
Anything in particular why you said: "Maybe you could see what's going on"?
The logs @cloud dawn
Yeah that's very normal it's Discord making sure your bot is still online. It reconnects to the gateway again. Happends every 15m-4h
As for the code if you wrote it yourself, very nicely written. Could be cleaned up a bit but other than that looks gut.
cant set a gif pfp for my bot can i?
Nope
....back to da gloom.....thenks mayte
who can help me to setup a bot from github
What help do you need? Have you worked with python before?
no
you need to learn some good amount of python first because discord.py (or other libs) are a rather complicated library to use
Use optical illusion
iirc no
They're just willing to run the ready script ig
What project is it, could you give a link?
If your not planning on making changes to the code, then all you need to do is
- set up an application in the discord developers portal
- read the docs on the github page to what permissions/intents its need, do NOT give it admin,
- Find a host for server (if you want it 24/7) otherwise, use a VM on your own machine if your not fussed about availability.
- copy the files into a directory on the server
4 Addd the auth token from your discord app to the code and then you should be able to invite it your server with invite link in the discord portal.
So there is nothing I can do about it as for my code?
I guess you can suppress the logger but I don't suggest that
I have a another question. I'm currently using ReturnDocument from PyMongo, but I want to switch to using Motor instead. Is it possible to achieve the same functionality using Motor?
from pymongo import ReturnDocument
counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}},
return_document=ReturnDocument.AFTER)```
thats more of a #databases question
if you specifically want to select (category) channels, use discord.ui.ChannelSelect instead
ok got it but how do i send that menu in interaction.edit_original_response()?
use the view= argument like you normally would when sending a message
options = [
dd.SelectOption(label='Option 1', description='This is option 1'),
dd.SelectOption(label='Option 2', description='This is option 2'),
dd.SelectOption(label='Option 3', description='This is option 3'),
]
my_dropdown = ddu.Select(placeholder='Select an option...' , options=options , custom_id='dropdown_menu')
await interaction.edit_original_response(content=f"**Choose a category from the dropdown below! :smiling_imp:**" , view=my_dropdown)
is this correct?
there's a difference between views and components like select menus
the view= parameter only takes a view, and views contain the components to be sent with your message
then how do i do it?
the other syntax is to subclass View and use the select decorator, which might be easier to understand since you only have to instantiate one class to pass to view=
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py py class MyView(discord.ui.View): @discord.ui.select(options=[...]) async def on_select(self, interaction, select): value = select.values[0] await interaction.response.send_message(f"You picked: {value}")
It's weird because I'm not receiving these messages with my Modmail bot (which was not coded by me)
Prob the way they setup logging
could any of you link me the discord markdown guide that was sent here before? I cant find it
found it
can u dm me?
pls how to make a slash command only usuable py server crown owner ?
You can add something like @ app_commands.checks.has_permissions(Administrator=True)
thx
https://discordpy.readthedocs.io/en/stable/discord.html This will guide you in setting up a discord bot in the portal, you also need a server to host it, or a VM on your own machine if you don't need availability and then add in the discord token generated in the dev portal to the bot from Git.
i put token everything is not working
idk whatys going on
So what discord bot is it?
and for crown owner ?
what should i write ?
Anything in the terminal?
what u mean'
Crown owner?
guild owner
Oh server owner, that is how.
it check if he / she has admin perms only no ?
Yes it does check that. The server owner is an Administrator the only difference is, a normal admin can't remove the server owner or change server owner, etc. Unless I have completely missed something in the role heirarchy. I would highly recommend not giving admin to anyone else, there is really no reason too.
Hi
okay, thank you for giving me a bit of your time π«
and how can i define @app.commands ?
@slate swan πΉ
oh i found
my bad, thanks for everything
Sure dm me
for some reason i cant ;/
whats the issue
idk whats the issue
i need verification bot i got some from chat gpt nothing works found on github still nothig
... so basically ur trying to setup some code without verified source or wether it works?
yes
@app_commands.checks.has_permissions(Administrator=True)
@bot.slash_command(name="setfee", description="CMD used to set a payment method")
async def setfee(ctx, Payment Method Name : discord.Option(str, "Write Here The Payment Method Name", required = True),info : discord.Option(str, 'Write Here The Payment Method Link / Address ...', required = True), fee : discord.Option(float or int, 'Write Here The Payment Method (extra) Fee (X%)', required = True)) :
i want to make the option with spaces, but i get error, could you help me for ?

i don't think it exist in any programming language
you should space using the snake case e.g this_is_a_spaced_var
bcz, that's ugly π
you can change it, iirc there was a kw
how ?
dpy
the namespaces in half the packages are same thats why u cant have multiple installed at same time
with discord libraries
eh
just do pip freeze and check if its pycord or discord.py
okay
aiohttp==3.8.3
aiosignal==1.3.1
altgraph==0.17.3
anyio==3.6.2
async-timeout==4.0.2
attrs==22.1.0
auto-py-to-exe==2.31.1
bottle==0.12.24
bottle-websocket==0.2.9
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
DateTime==5.0
discord==2.1.0
discord-webhook==1.0.0
discord.py==2.2.2
Eel==0.14.0
Flask==2.2.2
frozenlist==1.3.3
future==0.18.3
gevent==22.10.2
gevent-websocket==0.10.1
greenlet==2.0.2
h11==0.14.0
httpcore==0.16.3
httpsx==0.0.1
httpx==0.23.3
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
multidict==6.0.3
pefile==2023.2.7
py-cord==2.4.0
pycparser==2.21
pyinstaller==5.8.0
pyinstaller-hooks-contrib==2023.0
pyparsing==3.0.9
pytz==2022.7.1
pywin32-ctypes==0.2.0
requests==2.28.2
rfc3986==1.5.0
sellpass==1.0
six==1.16.0
sniffio==1.3.0
spark-parser==1.8.9
tls-client==0.1.8
typing_extensions==4.4.0
uncompyle6==3.9.0
urllib3==1.26.14
utils==1.0.1
Werkzeug==2.2.3
whichcraft==0.6.1
xdis==6.0.5
yarl==1.8.2
zope.event==4.6
zope.interface==5.5.2
huh
both
he has both 
ur using pycord tho
u can delete discord.py
to avoid confusion and namespace clashes
lemme check docs
okay π«
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
just supply a kwarg name
shall try thenks mayte
π΅βπ«
hm ?
can someone tell me how can i get the number of times a member have booster a server?
try reinstalling the discord.py library
install it then
nah its fine
but ?
thats not how it works for slash commands
you should watch a tutorial on yt or search for sample cods
huh
it works for pycord i guess
yes, i dont know pycord
I need help making a discord bot with making a vc channel that will make more when you join and invite counter
AAA
for discord.py
its like
@client.tree.command(name="", description="")
i am a learner too so cant explain like a professional, but yeah
it's fine, you're trying to help, so that's kind from you π«
no i am just waiting for someone better to come and help me π
anyone know how can i get the number of times a member have booster a server?
u cant unless u manually store it in db
u can get a message event like where u watch for system messages like this person boosted the server
using on_message event
interesting, i can try this
nah
in discord.py you can only get the time since the member is boosting
there is a message type for that wait a sec
oh okay
yes it will be helpful
also u might do well to refactor ur code to use a single library
dont use both pycord and discord.py
u may have version or component conflicts at any moment or update
how πΉ ?
stop using it in your code
but check that
@shrewd apex that's my all imports :
import discord, discord.ext
from discord.ext import commands
from discord import app_commands
import time
from colorama import init
from colorama import Fore, Back, Style
import json
@timid spade
?
issue is both have similar code names but how they work is completely different
so the methods you are using will change
pick one pycord or discord then solve all the errors
how can i do ?
thanks king
np
while coding ofc you test code many times
how do i test codes likes this, i cant boost again and again
is there in alternate way?
its just the if check u can test the code below it
and if check is unlikely to be buggy just an equality type check
if message.type == discord.MessageType.premium_guild_subscription
the main line if check is just this not much to test
other than the server or boost channel u setup for the server
like i mean
i want to give a role to the booster on one boost and different role if two boosts
so how do check if overall code it working
how do i check if on boosting one time members is getting the role and same with boosting 2 times
just use normal message event in the boosting channel
record the messages
message.author is the booster store it in the db
oh
so that system message, if we do message.author for that
will it be booster?
ok nvm nvm
sorry i figured it out
thanks tho
did you uninstalled pycord?
he is using modules from both in his code π
I think it's raising that error because it's discord.py now
because pycord has discord.ext.commands.Bot.slash_command, discord.py no
how cna i check if someone has nitro
no way unless user is boosting the server
ok
guys, help me pls with this error:
i make discord bot on replit and when i try to connect to Mongo db - i get this error:
ik i need require #databases but maybe someone knows about it
two cases one is ur ip is not white listed in db settings u generally need to add 0.0.0.0/0 and sometimes working with mongo i noticed is it dosent quite work well with few internets like sometimes when i had a vpn on it used to time out frequently
finally make sure the mongo link is correct
i have it, still error
and sometimes it works and sometimes doesnt
its correct
because my parents forbid download PyCharm hahahahhaahhaha
btw
one guy one time helped me with this advise
import dns.resolver
dns.resolver.default_resolver = dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers = ["8.8.8.8"]
but it has this issue
wait
whats wrong?
@code_bot.tree.command()
async def shop(interaction: discord.Interaction, max_coins: int = 1):
"""
Allows user to buy items on the shop.
"""
if str(interaction.channel_id) == channel_details[0]['ChannelID']:
with open("./AddedUsers/AllUsers.txt" , "r") as file:
all_users_str = file.read()
all_users_replaced = all_users_str.replace("'", "\"")
all_users = json.loads(all_users_replaced)
counter_4 = 0
for each_user in all_users:
if str(interaction.user.id) in each_user:
options = [
discord.SelectOption(label='Option 1', value='option1' , emoji="β€οΈ"),
discord.SelectOption(label='Option 2', value='option2' , emoji="β€οΈ"),
discord.SelectOption(label='Option 3', value='option3' , emoji="β€οΈ")
]
select = discord.ui.Select(options=options, placeholder='Choose a category...', custom_id='category')
view = discord.ui.View()
view.add_item(select)
await interaction.response.send_message(content='Choose a category from the dropdown below! :smiling_imp:', view=view)
else:
counter_4 += 1
if counter_4 == len(all_users):
await interaction.edit_original_response(content="**User Does Not Exist. Please Use `/add_user` To Add User.**")
hello i am doing this but i want the bot to send a message when the user selects any of the item in dropdown menu
how do i do it?
await interaction.response.send_message(f"something", ephemeral=True)
i want to send message when user selects anything from the dropdown menu. how do i check if user has clicked on something?
if self.values[0] == "<Option Name>":
await ...
[0] - first value
[1] - second and etc
and it must be in callback event
can u plz explain a little
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "<Option Name>":
await ...
This should run and print this text instead
where did that self came from?
because i copied it from my file, i made it in cogs, you dont have to put it then
then how do i check if user selected or not
ahhh wait
ill make example for you
async def interaction_check(interaction: discord.Interaction):
if author == interaction.user.id:
return True
else:
await interaction.response.send_message(f"This menu is not for you", ephemeral=True)
ohh soryy
incorrect a bit
but isn't this checking if the allowed user interacted with the message?
yea

i said i want to check if the user interacted with any of the items in my dropdown list
any one of these. how to check if user selected any one of the options?
why u need check this ?

then how am i supposed to display something when user clicks on either one of the boxes????
You mean this ?
how can i make a button only clickable 1 time?
i used button.disable, the button is disabled but is still interactable
What button? Are you talking about a GUI? because that would be for #user-interfaces
gui? no, discord buttons, but doesnt matter now i fixed it
Hi! I have this code, the bot sets up correctly, the permits are correct but he isn't responding to the command..
weyo i nedd help
same xD
your order is messed up
first of all, you can't have two bots running at once (not with .run alone anyway) so remove all the bot = ... stuff
then @client.event needs to be before client.run
and client needs to have the message content intent
how to make tree command bot work in 2 servers like
@tree.command(guild = discord.Object(id=id1 id2)
instead of passing guild pass guilds
which is List[Snowflake]
e.g. ```py
@bot.tree.command(guilds=[
discord.Object(id=...),
discord.Object(id=...),
discord.Object(id=...)
])
dam bro i wish u said that before
i made it global
eh its okay it was my last update on the bot anyways 
because nothing else left to add it to the bot after 1.7k lines of coding its now done
i made a language translation bot but it's picking up target language code too. One language code works and it gets failed in other languages like worked in ES=Spanish but doesn't work in FR=French or DE=German
please help me out
i thought i helped you yesterday
nope
only 1.7k π
i am new to coding please help me out. Where to put these?
Put what
the code snippets
you want to make a command first
use @client.command()
So Iβm guessing u didnβt code them
And your expecting people to help you
?
Is it possible to add a persistent view using .add_view without having to instantiate it? I've got a view like so:
class MyView(discord.ui.View):
def __init__(self, arg1, arg2, arg3) -> None:
...
async def setup(bot: Bot) -> None:
... # ?
I won't have the appropriate arguments to pass into MyView - but I do believe I actually have to pass in an instance of MyView into .add_view which I don't think I can do. Wondering if there is another way to register persistent views?
can you retrieve the necessary arguments during on_interaction? if so, you can use internal methods for dispatching your view, which is what ive done before to use dynamic custom ids
https://github.com/thegamecracks/thegamebot/blob/533f6d3b40df0f680da6e9f3a5736628e8ff5dcf/bot/cogs/games/hangman.py#L273-L297
(the actual method calls here are probably obsolete)
I ended up going with a solution where I .add_view in the same place I actually construct the view and send it, not sure if that's really idiomatic?
if you're sending the view right afterwards, add_view should be redundant
Jinja2 template is fetched
View is constructed with the proper arguments
View is added using add_view
And it's sent along in a message
why do you want to add the view then? thats done automatically when you send/edit
Is it? Old views still fail when bot is restarted
ya, add_view doesnt change that
Am I misunderstanding the purpose of add_view?
usually you'd store the necessary information for constructing a view in your database then during bot startup, reconstruct and add those views so dpy knows how to dispatch them
though it is also possible for a single view to be dispatched across multiple messages if you dont provide add_view(message_id=)
Unfortunately I don't know the arguments of a view ahead of time, it's sort of dispatched on the fly
(It's on a @tasks.loop)
For all intents and purposes we get a message with the same view every 60 seconds
why do you need to add_view in the first place? why not just send it
oh it's persistent
i'm not really sure adding a persistent view every 60 seconds is the best idea though
assuming all the custom ids are the same, you could make your view parameters optional, add one view without a message id, and then retrieve the needed information during your callback
though trying to be stateless by inferring it from your message is somewhat annoying of an approach
Yeah unfortunately
Looks like adding the view as I send it doesn't work either (at least not until the bot has first sent the view for the first time on reboot)
If it makes any difference I only really need the view to accept parameters so I can pass it down to a modal that's sent when the button is pressed
mhm, dpy doesnt have any kind of disk cache that your views go into
Would be cool if I could just like, pass in a custom ID or something into the add_view
Rather than a rich object
if you want to parameterize your components' custom ids you can do that just fine, though i suspect what you actually mean is having dynamic custom ids (e.g. matching by regex) which is a feature that afaik is still in "design purgatory hell", as danny put it
Oh, no. My custom IDs is static for all buttons of the same type sent out
oh, what do you need to pass a custom id for then? if you want a way to register a callback function, make a wrapper that creates the appropriate component type, sets the custom id and callback, adds it to a view, then adds the view to the bot
Miscommunication on my part, sorry.
I just guessed that since all my buttons have a custom ID like MY_BUTTON I wished I could do something like
bot.add_view(custom_id="MY_BUTTON") and that would add all buttons with that custom ID as persistent, if that makes sense
I'm guessing under the hood, the discord API works similarly, right?
Either that or a snowflake ID of some sort
uhh, well "views" in dpy is completely their own abstraction
Right. I believe the IDs do actually exist on the API-level?
discord's api just expects you to give them a custom id for each component, and when a button is clicked you get a payload containing said custom id, but figuring out the correct callback to invoke by yourself is inconvenient
Oh that makes sense
views abstract that process into a single object that can be added to your bot's internal view store, and once an interaction is received it looks through that store to find which callback to call
Discord.py couldn't know which class is associated with which custom IDs
From nothing but the custom ID, of course
Once added to the internal store like you mentioned I suppose it's quite trivial to loop through and figure out which component is associated with which custom ID and what the callback is
the mechanism is implemented here if you're interested in that
https://github.com/Rapptz/discord.py/blob/v2.2.2/discord/ui/view.py#L582-L625
use a function that dynamically fetches your prefix
how do i check if someone has removed only one boost but still is boosting with 2nd boost?
This prefix could [be] a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate βdynamicβ command prefixes.
doesnt look like information that discord's api provides
well sad
what is prefix
what is it though
like what is the value
yeah then it never changes
you need to make get_prefix async and use find_one in get_prefix
also you should be using motor not pymongo
an async python wrapper around mongodb
its usage is pretty much the same as pymongo
i have this on_message event
and when i have it the prefix commands stops working, but as i comment it out they start working again
Is there an inbuilt way to display colors? Like say I want the user to pick between 4 colors, Red, Green, Blue and Yellow. Is there a way to display those as actual colors?
it needs to take message and bot
also like i said use motor
and you shouldn't override _id
Display where
yes
you literally just add await everywhere
that's about it for migrating from pymongo
yes dead ass
show code so we can help
from discord.ext import commands
from discord import app_commands
import discord
class HelpCMD(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(description="Xeton - Parancslista")
async def help(self, ctx: discord.Integration):
view = View()
await ctx.response.send_message(view=view)
class Core(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="FelhasznΓ‘lΓ³i parancsok",
description="Alap felhasznΓ‘lΓ³i parancsok")
]
super().__init__(placeholder="VΓ‘lassz ki egy kategΓ³riΓ‘t!",
min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "FelhasznΓ‘lΓ³i parancsok":
embed = discord.Embed(color=discord.Color.blue())
embed.set_author(name="Parancslista", icon_url=interaction.user.display_avatar)
embed.add_field(name="FelhasznΓ‘lΓ³i parancsok", value="**/ping** - Bot ping\n**>avatar (emlΓtΓ©s)** - ProfilkΓ©p lekΓ©rΓ©s\n**>botinfo** - Bot informΓ‘ciΓ³k\n**>userinfo (emlΓtΓ©s)** FeelhasznΓ‘lΓ³ informΓ‘ciΓ³k\n**>serverinfo** - Szerver informΓ‘ciΓ³k\n**>dc** - Support szerver\n**>invite** - Bot meghΓvΓ‘s")
embed.set_footer(text="Xeton Γ help")
await interaction.response.send_message(embed=embed)
class View(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Core())
async def setup(client):
await client.add_cog(HelpCMD(client))```
@slate swan
or someone
Hi
Hey
Run it again and see if it's going to do this again
It's probably just Discord saying that you can get an active dev badge π€·
From what I see in that image anyway
lol = f"{packtitle}-{rv}.zip"
await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=lol, ephemeral=True)```
I'm trying to do this
and im getting
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\lux\Desktop\jojobot\bot.py", line 87, in download
await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=lol, ephemeral=True)
File "C:\Python\lib\site-packages\discord\interactions.py", line 763, in send_message
params = interaction_message_response_params(
File "C:\Python\lib\site-packages\discord\webhook\async_.py", line 606, in interaction_message_response_params
attachments_payload.append(attachment.to_dict())
AttributeError: 'str' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'download' raised an exception: AttributeError: 'str' object has no attribute 'to_dict'```
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
im sending that for myself
Oh π
ttachments_payload.append(attachment.to_dict())
AttributeError: 'str' object has no attribute 'to_dict'
ow do
what's "lol"
a random variable
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
?
file=discord.File("path-to-file")
π
defer it
using defer, it will not timeout for 15 mins
put await interaction.response.defer() at the top of your command
if you want to send more messaged, you might need to followup it
await it
first line of the command
await interaction.response.defer()
pack = ...
you can add thinking=True too iirc
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...

yeah u can
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\lux\Desktop\jojobot\bot.py", line 87, in download
await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=discord.File(f"{packtitle}-{rv}.zip"), ephemeral=True)
File "C:\Python\lib\site-packages\discord\interactions.py", line 751, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'download' raised an exception: InteractionResponded: This interaction has already been responded to before
you need to followup
??
as i said
not response
followup
Returns the follow up webhook for follow up interactions.
doesnt work for some reason
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the libraryβs internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
its awat interaction.followup.send(...)
you can do that too
yeah its .send
banned

Why was I expecting the emoji name to be Down

I'm out
π
how to let people with admin perms only execute a cmd ?
are you using pycord or discord.py? and is it for a text command or a slash command
dpy text command: @commands.has_permissions() or @commands.has_guild_permissions()
dpy slash command:
@app_commands.default_permissions()to configure a default permission requirement for members to see the command, though server admin can change this@app_commands.checks.has_permissions()if you want to enforce that requirement regardless of what the server admin sets it to
pycord text command: same as dpy
pycord slash command: couldnt figure that out from a quick look through their docs
pycord
for slash command pls
oh they do support default_permissions at least
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.default_permissions
but no has_permissions() equivalent
and if i want to do exception like if someone use the cmd is not admin : "You have to be administrator to use this command" ?
thats not a thing when you're using default_permissions, after syncing your command with that decorator, discord will make the command completely unusable to people that dont have the permission
If you don't want to help it's okay brother
Trying to figure out why my slash commands aren't working, anything look incorrect in here to anyone?
import os
import discord
import discord.ext
from discord.utils import get
from discord.ext import commands
from discord import app_commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
extensions = ("embed","joinleave","moderation","responses", "reactions", "gameservers",)
bot = commands.Bot(command_prefix="?", intents=intents)
ALLOWED_GUILDS = (left blank in example,)
bot.add_check(lambda ctx: ctx.guild.id in ALLOWED_GUILDS)
ALLOWED_ROLES = (left blank in example,)
bot.add_check(lambda ctx:
any([r in ctx.author._roles for r in ALLOWED_ROLES]))
@bot.event
async def setup_hook():
for extension in extensions:
await bot.load_extension(extension)
@bot.event
async def on_ready():
await bot.tree.sync(guild=discord.Object(id=709208493684555858))
print("Ready!")
@bot.event
async def on_ready():
print("Turlington is online and watching!")
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="the servers."))
bot.run(TOKEN)
By not working I mean they aren't even showing up as options when prompting with the / in discord
Its been about 12 hours now, think thats still normal?
I am fine waiting if it will take longer just not sure if its supposed to take that long
If it would have been 12 minutes then it would be normal π
So something is wrong in my code essentially hahaha
Yea.... but sorry can't really help u I never used app commands with dpy
No worries, ty for responding though!
As far as I can tell everything is right, and it throws zero errors...but isn't working.
I would be happy to take a look at the code but it will take some time since I'm away from my laptop
No rush, if you or anyone sees anything wrong just let me know. Gunna keep plugging away at it
why do you have 2 on_ready events tho
Oh, didn't know that would cause an issue
I guess I can merge them
you shouldn't sync your tree on_ready
from what I have heard syncing with a normal text command is better
So I would need to just initiate the command in discord to sync it?
Which is fine, just wanna make sure I understand
yeah
i have installed discord but it still happens
from discord.ext import commands
thanks
Hello, I can't find the way to write the numbers like this, for example, at the moment he writes like this: 10000000 and I would like him to write like this: 1 000 000, I don't know how to do it...can you help me please?
__expr = {
'qty': re.compile('\(x\d+\)'),
'seller': re.compile('``[\w_]{3,48}``'),
'item': re.compile('nte ``.{1,32}`` \('),
'price': re.compile('\*\*[\d\s]+βΈ\*\*$')
}
@bot.command()
async def sync(ctx,):
await bot.tree.sync(guild=discord.Object(id=709208493684555858))
await ctx.send("Slash commands have been synced with Discord.")
This look ok?
it works I guess? should add an owner check tho
Why would I need that for this?
so not anyone can use this?
Well the slash commands aren't working anyways, so theres something wrong elsewhere
Oh, its limited to specific roles overall
So thats taken care of anyways
@bot.command()
async def sync(ctx,):
if ctx.message.author.id =='288522211164160010':
await bot.tree.sync(guild=discord.Object(id=709208493684555858))
await ctx.send("Slash commands have been synced with Discord.")
else:
await ctx.send("Sorry, you dont have the required permissions to perform this command!")
Look better?
Oh
Thats telling me I don't have permission to use it, wtf lol
oh I had the ' ' still nvm
i have smth better for u
Please do
@commands.command()
@commands.guild_only()
@commands.is_owner()
async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object],
spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")```
So most of that makes sense but what is the optional section doing for me?
Just trying to understand
Also if this is just going into my base file I would just translate it to @bot.command() correct?
@gusty flax gives this File "C:\Users\PrimaryBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 691, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
Seems I had to remove self from it
THAT WORKED!
Slash commands function now.
Do I just need to set a universal response so it doesn't do this?
How can I get what the user is playing right now? I can only find out the user status but not what game he is playing
just use jsk sync
this is so pointless
It worked for me
I don't like relying on additional modules so this works better for me
how can i load the commands in multiple guilds?
a list doesnt work obiously..
await bot.add_cog(key(bot), guilds=[discord.Object(id=267624335836053506)])
huh
oh you mean group cog
guilds= should work
do you mean, then a list?
but where do i put the id= then?
but when i put
await bot.add_cog(key(bot), guilds=[267624335836053506, 336642139381301249]
it just returns
discord.ext.commands.errors.ExtensionFailed: Extension 'keySystem.create_key' raised an error: AttributeError: 'int' object has no attribute 'id'
it's not a list of integers
it's a list of objects
you just put multiple objects in the list
ahh okay thank you very much
hello how can i make the callback of a select menu to be sent inside the origional response?
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
How do I make it show that response
basically, "you are missing this role"
aka
like error response or else statement
use CommandTree.error() to add your own error handler, then check for the exceptions you're interested in and send an appropriate response
huh
like
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:```
yup
you could literally write if isinstance(error, discord.app_commands.errors.MissingAnyRole): ... in this case, but assuming you have app_commands imported the shorter form would be if isinstance(error, app_commands.MissingAnyRole):
make sure if you dont know how to respond to the error that you print the traceback, otherwise you'll hide error messages when your commands fail
It's only for one command overall anyway
So I just need the response for one command
@client.tree.command(name="dl")
@app_commands.describe(pack=cmddesc)
@app_commands.checks.has_any_role(762044720762716190, 762044945233739816, 762045678426914906)```
there is a @error decorator provided by individual commands, but for handling check exceptions its more convenient to use the global tree handler in case you later have more commands using the same check
I'm interested in this
!d discord.app_commands.Command.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
The local error handler is called whenever an exception is raised in the body of the command or during handling of the command. The error handler must take 2 parameters, the interaction and the error.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
and for the global
thats what i showed you earlier
yeah that seems about fine
i mean, the if statement's fine but you also should print the traceback if you dont have a response for the error
!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.
I'm just going off brain power LOL
use traceback.print_exception() if you want to be fancy
ah
and raise error if you want to be lazy
the command() decorator transforms your function into a Command object, thats where you'd access the error method from
@tree.command()
async def my_command(interaction): ...
@my_command.error
async def my_command_error(interaction, error): ...```
@client.tree.command(name="dl")
@app_commands.describe(pack=cmddesc)
@app_commands.checks.has_any_role(762044720762716190, 762044945233739816, 762045678426914906)
@client.dl.error
async def error():
print("You need the Early Access role to use this command.")```
line 92, in <module>
@client.dl.error
AttributeError: 'Bot' object has no attribute 'dl'
oh wait
Read this example
figured it out
I had to put it after the definition
error() takes 0 positional arguments but 2 were given
π
interation
and then error
I'm so lost
I wish there was an example π
what's the error now
Is there any way i can udpate the choices in real time in the code
because it seems i just cant udpate them
my select menu shows interaction failed even when i interact with it how do i fix it?
don't use choices at all
use a custom autocomplete
i did that
no the autocomplete is a function not a string
but there is error
did you look at the example
my select menu shows interaction failed even when i interact with it how do i fix it?
what's your code
@CodeBot.tree.command()
async def shop(ShopInter: discord.Interaction , max_coins: int = 1):
"""
Allows user to buy items on the shop.
"""
with open("./ServerDetails/AllData.txt" , "r") as file:
# Getting the id of channel that user has selected for the shop:
DetailsStr = file.read()
DetailsRep = DetailsStr.replace("'", "\"")
ChannelDetails = json.loads(DetailsRep)
# Checking if the user has used the command in specified channel:
if str(ShopInter.channel_id) == (ChannelDetails[0]['ChannelID']):
await ShopInter.response.send_message(f"**Please Wait Loading Categories For You...**")
# Getting all the existing users in our database:
async def CategoryLoader():
with open("./AddedUsers/AllUsers.txt" , "r") as file:
UsersStr = file.read()
UsersRep = UsersStr.replace("'" , "\"")
AllUsers = json.loads(UsersRep)
Counter = 0
# Checking if user exists in our database:
for EachUser in AllUsers:
# If user exists in database then showing him the shop:
if (str(ShopInter.user.id)) in EachUser:
async def CatViewCallback(interaction):
await interaction.response.defer()
await ShopInter.edit_original_response(content=f"This is a test for: {CategorySelect.values[0]}")
CategorySelect = CategoryDropdown()
CategorySelect.callback = CatViewCallback
CategoryView = discord.ui.View()
CategoryView.add_item(CategorySelect)
await ShopInter.edit_original_response(content=f"Choose A Category From Dropdown Below..." , view=CategoryView)
else:
Counter += 1
# If user doesn't exist in database after checking it completely then telling him to register:
if Counter == len(AllUsers):
await ShopInter.edit_original_response(content=f"**User Does Not Exist. Please Use `/create_account` To Add User.**")
ViewCategory = await CategoryLoader()
ty so much it works
edit_original_response is not technically a response
you need interaction.response.edit_message
when i don't use it, it gives me that error
when i use it it doesn't
yes but by using defer you are saying that you will give a response later
delete both lines and add interaction.response.edit_message
only this line?
dam wow
it worked like charm. thanks alot
how do i make a slash command to generate
like
/generate apikey: mhs54d89g7asdufji
pretty mcuh like these options things
!d discord.ui.ChannelSelect
class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.
Please note that if you use this in a private message with a user, no channels will be displayed to the user.
New in version 2.1.
@app_commands.command()
async def generate(self, api_key: str) -> None:
...
thanks
if you're using a cog this is pretty much what you need to make a required argument
just make sure to sync slash commands if this is your first time making a command
thanks
can u use pyexecjs for discord.py
i don't know what that is
PyExecJS (EOL)
End of life
This library is no longer maintananced. Bugs are not be fixed (even if they are trivial or essential).We suggest to use other library or to make a fork.
this?
is there a error handler which handles all errors of the slash commands in a cog?
so not only command_name.error() but for everything
im usuing nextcord and menus.ButtonMenuPages, how would i send this to another channel, this doesnt work
AttributeError: 'TextChannel' object has no attribute 'bot'
pages = CustomButtonMenuPages(source=MyEmbedFieldPageSource(list))
channel = bot.get_channel(1096435088775979078)
await pages.start(channel)
yes
!d discord.app_commands.CommandTree.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
could you help with it ?
@bot.slash_command(name="setlogs", description="CMD used to set logs channel")
no i do not know pycord
eh
but i imagine the select system is pretty similar
okok
in the docs there is nothing like this, if i looked right
could you give me the syntax with it ?
?
any1?
are you sure that error is with that code in particular?
yes but i dont understand what i need to put at the @
yeah it is
it executes javascript files
can it execute discord.js
i use it for fingerprinting things
import execjs
package_pwd_script = open("tasks/packagepwd.js").read()
script = execjs.compile(package_pwd_script)
def package_pwd(password, random_num, key):
pwd = script.call("encrypt", password, random_num, key)
return pwd
can anyone help me
AttributeError: 'CustomButtonMenuPages' object has no attribute '_state'
im getting this error when trying to start a tasks.loop in a specific channel:
pages = CustomButtonMenuPages(source=MyEmbedFieldPageSource(list))
await pages.start(ctx=None, interaction=pages, channel=channel)
did you edit the message with the new view?
wdym
you have to update the message
await interaction.message.edit(view = self)
yeah
what
why not just port the javascript code to python
bc im lazy lol
Would you guys use the first or second example?
1.
player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid), None)
if player_team_id is None:
continue```
2.
```python
for participant in match_data['info']['participants']:
if participant['puuid'] == summoner_puuid:
player_team_id = participant['teamId']
break
else:
continue```
so the first 1 basically searches the participant with the given id, if it doesnt find it returns None, second: if no id is found it will begin with the outer loop iteration until an id is found. both are good but depends on what you want to do
Just find which team the participant belongs to π
Doesn't continue mean it will loop endlessly?
if player_team_id is None:
continue```
oh yeah you're completely right i didn't see that
yeah now they do in fact the same thing
only difference is in the syntax, choose which one you want
Oh wait it's inside another loop so it will actually skip that particular match and go to the next one.
for match_id in match_ids:
player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid),
None)
if player_team_id is None:
continue```
Nvm thanks @slate swan
So just to make sure it will go to the next match in match_ids?
Here is the full code:
for match_id in match_ids:
url = f'https://europe.api.riotgames.com/lol/match/v5/matches/{match_id}'
headers = {'X-Riot-Token': api_key}
async with rate_limit: # use AsyncLimiter
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url) as response:
if response.status == 200:
await asyncio.sleep(0.3) # add 0.3 second delay
match_data = await response.json()
else:
await asyncio.sleep(0.3) # add 0.3 second delay
return None
player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid),
None)
if player_team_id is None:
continue```
yeah should be, the codeblocks on phone are really weird, could u send that in the python discord pastebin
For sure let me fix that
!p
pep_number
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
!pastebin
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.
Sorry for the mess
np i'll look into rq
How can I use a custom emoji for a discordpy button
@young dagger yeah the code is right, if it returns None it will skip this iteration for the generator expression next until it finds an id
and also it will create another request for the other ids
set emoji= kwarg of the button to a string of the custom emoji formatted as <:name:id>
I used the >:name:id>
Then it might not be settable
Custom emojis work in embed description and messages
As for buttons I don't think they work only unicode emojis work
nope you can definitely use custom emojis in buttons
and what happened
i have this on_message event
and when i have it the prefix commands stops working, but as i comment it out they start working again
Ir worked
forgot to process the commands?
maybe, i dont know what processing commands is
will it fix it?
async def on_message(message):
if message.content.startswith('prefix'):
return
e.g you have defined your bot as client you need to process the commands in on_message, so it would be await client.process_commands(message)
okay, let me try
right?
yeah
thanks, it worked
what do you mean
no, it's not a normal prefix, if you want to use it you have to invite your bot with the application.commands scope
and then the required decorator and stuff
anyone know how can a make something like a question and answers system?
you can say like the bot will ask a question on running a command and then look for all the messages in that channel and if in 10 seconds someone's text matches with the actual answer the command will stop by sending a message like "you won".
will it be like adding a on_message event inside a command or something?
you can do like a start game command and there is something called wait_for(), in this case it would be wait_for("message"), you would do a timeout of 10 seconds, and then you just check the message content in the 10 seconds
whatever lib you're using here is an example of that
i recommend doing it in a command and not in on_medsage
it's not that hard
okay thanks man
by adding the timeout it is sending the reply after 20 sec
can i make it so it instantly replies as someone types right answer
yes
just add a check
can you show your current code
@client.command()
async def flag(ctx):
data = get_any_flag()
await ctx.send(f"https://flagcdn.com/256x192/{data[0].lower()}.png")
print(data) #ignore
channel = ctx.channel
def check(m):
return m.content == data[1].lower and m.channel == channel
try:
msg = await client.wait_for('message', timeout = 20.0, check=check)
except asyncio.TimeoutError:
await channel.send("you lost")
else:
await channel.send("you won")```
discord makes it look disgusting so here is a pic too
it's .lower() not .lower
that would be your issue
everytime, everytime I make this mistake and still don't correct in future
thanks you are right
Hello there! Can You make like /upload In My bot that It Upload a File From My Pc?
Upload from your PC to where?
Like Make /upload it open file brower you choose from your pc then enter and then this photo/anything you choose will set to a var
im trying to make an offline command for my bot
it doesnt seem to work though and the bot remains online
I don't believe that's possible
You might be able to get the bot to download an attachment a user sent and use that, though
it should really just be a property
i don't thibk bots can go offline
oh, they cant? so i can only do shutdown?
Starting and stopping your bot really should not be managed from the bot itself
I guess you could but it's probably the job of whatever process manager you're using
but i see it in a dowload bot before
are you referring to changing its status?
not really, i would just like it to go offline so i can edit the code
so whats the best way of doing so, because as its just a py file i dont really want to constantly close and open it to take the bot offline
