#discord-bots
1 messages · Page 226 of 1
why does passing arguments to a MinimalHelpCommand subclass not work
class HelpCommand(commands.MinimalHelpCommand):
def __init__(self, bot: Bot) -> None:
self.bot = bot
HelpCommand(bot)
I think you need to call super().__init__()
that's not the problem
How come
class Context(commands.Context):
async def reply(self, *args, **kwargs) -> discord.Message:
allowed_mentions = kwargs.get("allowed_mentions", self.bot.allowed_mentions)
allowed_mentions.replied_user = False
kwargs["allowed_mentions"] = allowed_mentions
return await self.reply(*args, **kwargs)
also on an unrelated note - how come this raises a recursive error on line 3
Can you show the error
[2023-04-09 04:41:28] [INFO ] discord.client: logging in using static token
[2023-04-09 04:41:28] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID
: 2d5fffac85a99584cd050bf4cdefa14c).
[2023-04-09 04:41:30] [ERROR ] discord.ext.commands.bot: Ignoring exception in command status
Traceback (most recent call last):
File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\utilities.py", line 18, in status
await ctx.reply(embed=embed)
File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
return await self.reply(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
return await self.reply(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 16, in reply
return await self.reply(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[Previous line repeated 974 more times]
File "C:\Users\wfsov\Documents\Coding\beta-server-bot\bot\bot.py", line 13, in reply
allowed_mentions = kwargs.get("allowed_mentions", self.bot.allowed_mentions)
^^^^^^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wfsov\AppData\Local\pypoetry\Cache\virtualenvs\beta-server-bot-nGsIpVzJ-py3.11\Lib\
site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RecursionError: maximum
recursion depth exceeded
not sure how this would help @naive briar
anyone wanta make a discord bot together :) just slide a dm
you can work on mine if you'd like
whats it do?
mostly aimed towards server moderation and utility
check out the moderation and image-manipulation branch too
You are calling self.reply instead of super().reply
Iirc yes
Keep your custom context it will be useful later
Well your choice but doesn't harm using a custom one
How can i delete message after button click?
if you want the message of the view holding the button, it will be interaction.message.delete()
there is also interactiondelete_original_response()
!d discord.Role.mention
property mention```
Returns a string that allows you to mention a role.
anyone?
What lib are you using
discord.ext, its imported in the file
Yes but it doesnt look Like discord.py
What part?
from discord import Option
py cord i think
You dont know what your code is written in?
is there a better way to integrate both slash commands and a normal prefix instead of creating for every command 2 versions
can you help me please?
https://pastebin.com/A7vjW0zR
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "e:\SSD\Python\Code\Projets\DevBot\FishBot\main.py", line 67, in pecher
xp= int(Poisson.poids*1.6/2)
AttributeError: type object 'Poisson' has no attribute 'poids'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\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 'pecher' raised an exception: AttributeError: type object 'Poisson' has no attribute 'poids'
The above exception was the direct cause of the following exception:
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'pecher' raised an exception: AttributeError: type object 'Poisson' has no attribute 'poids'```
In discord.py there is something Like hybrid command
im using nextcord i forgot that to mention
dont worry i use nextcord too 
W, so its available there too?
Im aware its not
Let me double check
Nope its not
But they should add it too
yeah
so i need to do every command twice
or just do slash command only
anyone?
show the code
Any what
oh mb
its not a static attribute, you declared gardon as Poisson.. then you should use: gardon.poids bla bla bal
ok but I would like it to choose a random element on its own between "gardon" and "perche"
i cant use gardon only....
you already have random import so? you can just randomize it
i dont uderstand
you can but both variables in a list, then with random.choice you can randomize the selection of 1 variable
there you go you have your randomized thingy
in the xp value of the database, I would like to add the xp value of the fish and add it to the xp already obtained previously
i dont understand you, what do you mean?
my fish have 2 attribute: Nom and poids.
Now i define the xp by poids*1.6/2
how to code the correct formule?
i dont find the correct code ^^'
@slate swan
formula for what?
first off what do you want to do?
I want to define the xp of my fish with the formula I gave:
xp= poids*1.6/2
yes, and whats wrong?
I just added to my class the xp:
def init(self,name,weight,xp):
def init(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = poids*1.6/2
why do you have 2 inits?
where?
here
ho its a mistake lol
I just added to my class the xp:
def init(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = poids*1.6/2
now look the code
on line 65
you get any error?
xp += random.randint(1, 5)
i want change the
xp += random.randint(1, 5)
by poids*1.6/2
and i have a error
then you just need to do Poission.poids
Why is there a missing argument
try:
xp = xp[0]
level = level[0]
except TypeError:
xp= 0
level= 1
if level < 4:
xp += Poisson.poids*16/2
await cursor.execute("UPDATE peche SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp += Poisson.poids*1.6/2
await cursor.execute("UPDATE peche SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))```
hmmmmm
ok!
You did not initialize an instance
The poids attribute will only be available after you init the class
this:
@bot.hybrid_command(name="pecher", description="pêcher un poisson")
async def pecher(ctx):
class Poisson:
def __init__(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = poids*1.6/2
gardon = Poisson("un gardon", random.randint(15,1250), Poisson.poids*1.6/2)
perche = Poisson("une perche",random.randint(30,2123), Poisson.poids*1.6/2)```
no, not like that
!e 🫠
class Meow:
def __init__(self):
self.attr = 0
a = Meow() # init an instance
print(a.attr)
b = Meow # just a bare class type
print(b.attr)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | 0
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 9, in <module>
004 | print(b.attr)
005 | ^^^^^^
006 | AttributeError: type object 'Meow' has no attribute 'attr'
sorry i'm new with class... ^^
def __init__(self,nom, poids, xp):
self.nom=nom
self.poids=poids
self.xp = xp
gardon = Poisson("un gardon", random.randint(15,1250), Poisson.poids*1.6/2)
perche = Poisson("une perche",random.randint(30,2123), Poisson.poids*1.6/2)```
Why?
the attribute is no random.randint(15,1250)?
What
You have only defined the poids attribute in the __init__ magic method, so it would only be available after initializing an instance of the class
Or if you do something like this then I guess
class A:
b = 0
def __init__(self, b):
self.b = b
Moving from Disnake to dpy2 - what's the equivalent for disnake.ext.commands.slash_command() decorator in dpy2? Looking at documentation and not seeing anything just yet, perhaps someone could bump me in the right direction 🙂
PS C:\Users\$USER\Documents\workspaces\Snephex> python app.py
Traceback (most recent call last):
File "C:\Users\$USER\Documents\workspaces\Snephex\app.py", line 5, in <module>
from discord.ext import commands
File "C:\Users\$USER\Documents\workspaces\Snephex\discord.py", line 2, in <module>
from discord.ext import commands
ModuleNotFoundError: No module named 'discord.ext'; 'discord' is not a package
make sure you have discord installed in the environment your code is executing
I did
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
TL;DR @app_commands.command()
i need libtk8.6.so , how do i get it
can someone help me with my code? im using nextcord and i want to @ a user but cant figure out how to@bot.event async def on_message(member, interaction=nextcord.Interaction): guild = member.guild if guild.system_channel is not None: msg = f"Welcome user to {guild.name}" await guild.system_channel.send(msg)
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
i currently have it set as a on_message command to test it
ok if i change the on_message to an on_member_join can i @ someone then?
you always can do that im just saying that on_message gives you only message
Who do you want to ping?
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
since its originally an on_member_join command i want to ping the person that joined
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
You'd just do member.mention then
From within an on_member_join, not sure why you have an on_message or why it has discord.Interaction class set as the default
its currently a on_message command so i can easily see what it looks like by just typing smt in the chat
create a command then
and i actually dont even know why i have a nextcord.Interaction class set as the default lol
A Python wrapper for the Discord API forked from discord.py - nextcord/new_member.py at master · nextcord/nextcord
here event is defined inside commands.Bot subclass so it doesnt have to be decorated with @bot.event
thanks
how do you get the custom id of a selected option in a select menu?
I don't think the options themselves have a custom id, the whole select menu has
i mean value
values yes
what does it return
just the label of the selected option?
in an example its just self.values[0] so that must return the name of the colour right?
meaning the label
try printing it and see
!d discord.ui.Select.values or check in docs
property values```
A list of values that have been selected by the user.
it just says list
A list of values that have been selected by the user.
i was expecting List[discord.SelectOption]
oh
OH
values in the sense values
man its just normal english 😭 didnt know they meant that
when creating a SlashOption you can pass value as parameter and this will be the value inside values but if you dont pass the value then it will be default to label name
!d discord.SelectOption.value
The value of the option. This is not displayed to users. If not provided when constructed then it defaults to the label. Can only be up to 100 characters.
hmmm yeah
how do i pass interaction into a dropdown?
i need interaction to get a botvar
class PartyShowDropdown(discord.ui.Select):
async def __init__(self, interaction):
self.interaction=interaction
options = [
discord.SelectOption(
label = party["name"],
description = party["description"] if len(party["description"]) <= 100 else (party["description"][:97] + "..."),
value = party["owner"]
)
async for party in (await self.interaction.client.database["parties"].find())
]
super().__init__(
placeholder="Select a party",
min_values=1,
max_values=1,
options=options
)
```is this right
i need interaction before using super().__inint__()
List of the values, not the label
However if a value wasn't provided then the label is the value
👍
Also would not recommend passing interaction down
this returns this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 336, in show
await interaction.response.send_message(view=PartyShowView(interaction))
File "/home/runner/MathBot-1/cogs/parties.py", line 58, in init
self.add_item(PartyShowDropdown(self.interaction))
TypeError: init() should return None, not 'coroutine'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: init() should return None, not 'coroutine'
__init__ can't be async yeah
so how do i access a botvar?
don't do it in the dropdown
Pass in bot
class PartyShowDropdown(discord.ui.Select):
def __init__(self, bot: commands.Bot):
...
do the logic elsewhere, then pass it down to the select menu
(logic is generally done in the command)
then can i add the logic to the view?
(im passing interaction to the view at least, hope thats safe at least?)
Since it seems like the options of your select menu depends on data that comes from an external source
oh
class MySelectMenu(discord.ui.Select):
def __init__(self, options: list[str], ...) -> None:
super().__init__(options=options, ...)
async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
...
class MyView(discord.ui.View):
def __init__(self, options: list[str]) -> None:
super().__init__()
self.add_item(MySelectMenu(options))
@bot.command()
async def my_command(self, ctx: commands.Context) -> None:
data = await fetch_data() # this can come from anywhere, like a database
view = MyView(data)
await ctx.send(..., view=view)
@stone palm this is a suitable example for your usecase
Keep track of how data gets passed down from the command handler (my_command) all the way down to MySelectMenu
yep i understood that, thanks
also how am i supposed to use async for
i get this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 334, in show
async for party in (await interaction.client.database["parties"].find())
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
i don't think you await it
it's either async for party in find() or for party in await find() i'm pretty sure
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 334, in show
for party in (await interaction.client.database["parties"].find())
TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: object AsyncIOMotorCursor can't be used in 'await' expression
Use mudkip's former recommendation instead
I think that's how you're supposed to use it
ah right
but another problem here:```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 337, in show
await interaction.response.send_message(view=PartyShowView(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 51, in init
self.add_item(PartyShowDropdown(options))
TypeError: init() should return None, not 'coroutine'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: TypeError: init() should return None, not 'coroutine'
it's not async def __init__ remember
.....oh yeah
is this correct?```py
class PartyShowDropdown(discord.ui.Select):
def init(self, options):
# self.options=options
super().init(
placeholder="Select a party",
min_values=1,
max_values=1
)
for option in options[:25]:
self.append_option(option)
or should i use options = options?
min_values=1 and max_values=1 are the default options actually
im getting this error```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 841, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/home/runner/MathBot-1/cogs/parties.py", line 336, in show
await interaction.response.send_message(view=PartyShowView(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 50, in init
self.add_item(PartyShowDropdown(options))
File "/home/runner/MathBot-1/cogs/parties.py", line 10, in init
placeholder="Select a party",
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/select.py", line 382, in append_option
if len(self._underlying.options) > 25:
AttributeError: _underlying
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show' raised an exception: AttributeError: _underlying
!d discord.ui.Select.append_option
append_option(option)```
Appends an option to the select menu.
AttributeError: _underlying would suggest the parent init wasnt called, and given the traceback unusually points to placeholder="Select a party", rather than super().__init__(, that likely means your source code doesnt match what's running on the bot
ah yes, did some refreshing and fixed it
btw you can pass the options= kwarg to super init too
guys can you have a dropdown menu and a button in the same message?
sure, you're allowed 5 rows of components
ight ty
whats the difference?
its convenient
er if you removed it from your init, you dont have a way to pass your options anymroe
if you want a more technical difference you can look at the source code, but curiously the 25 max options check doesnt occur when using the kwargs form
https://github.com/Rapptz/discord.py/blob/master/discord/ui/select.py
can someone help me i wanna make a discord bot and im lost idk what to do at all
it will do a very simple thing
Hey everyone,
I'm having some trouble getting my Discord bot to work with slash commands. When I try to import the SlashCommand class from the interactions module, I get the following error:
"ImportError: cannot import name 'SlashCommand' from 'interactions' (C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions_init_.py)"
I've tried reinstalling the interactions library, checking that the SlashCommand class is defined in the __init__.py file, and ensuring that I'm importing the class correctly. However, I'm still getting this error.
Does anyone have any suggestions on how to resolve this issue? Any help would be greatly appreciated!
looking at their docs, SlashCommand is only in the legacy version 3 of their library and has since become a standalone Client class
new (v4): https://interactionspy.readthedocs.io/en/latest/quickstart.html
old: https://interactionspy.readthedocs.io/en/legacy-v3/quickstart.html
if you still want to use discord.py, you can upgrade to dpy 2.0 and use their implementation of slash commands
guide: https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
reference: https://discordpy.readthedocs.io/en/stable/interactions/api.html
hi, i need help please here:
https://discord.com/channels/267624335836053506/1094771936531320842
how do you get view object from select menu callback interaction?
how are you making the callback?
If you have access to the Select object, you can use the view attribute
!d discord.ui.Select.view
property view```
The underlying view for this item.
wait is there a decorator for select menus?
or is there a way to directly add a select menu in a view class without making a selectmenu class?
@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
where I can find a person the charge for coding?
Pardon?
Are you looking to hire developers?
yes
!rule paid
Np
\001b[{32};{0}m hello
\u001b[{32};{0}m hello
\u001b[{32};{0}m hello
\u001b[{32};{0}m
hello

Hmm
is there a built in way to only display certain users in discord.ui.UserSelect?
i belive its not
#965291480992321536 see pinned messages here

are you on mobile?
Shows it as deleted-channel for me as well, and I'm on PC
but i'm guessing you mean the thread
I'm using the latest version of python and have uninstalled pycord and reinstalled.
error:
Traceback (most recent call last):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/script/main/v3/aww pika discord bot v3.py", line 2, in <module>
from pycord.ext import commands
ModuleNotFoundError: No module named 'pycord.ext'
import pycord
from pycord.ext import commands
from pycord.ui import Select, SelectOption
from pycord.ext.commands import cooldown, BucketType, has_permissions, Option
import sys, traceback
import os
import time
import random
import asyncio
import json
import os
import aiohttp
import sqlite3
import numpy as np
intents = pycord.Intents.default()
intents.members = True
bot = pycord.Client(intents=intents)
#amount of guilds bot is in
@tasks.loop(minutes=1)
async def bot_servers():
await bot.wait_until_ready()
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!")
await bot.change_presence(status=discord.Status.online, activity=version)
bot_servers.start()
@bot.event
async def on_ready():
print(f"{bot.user} has connected to Discord!")
bot.run("mytokenhere")
pycord version:
Name: pycord
Version: 0.1.1
Summary: Convenient wrapper on top of FFmpeg
Home-page:
Author:
Author-email: Alessio Sanfratello sanfra90@gmail.com
License:
Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
Requires: ffmpeg-python, imageio-ffmpeg, numpy
Required-by:
import discord
from discord.ext import tasks, commands
from discord.ext.commands import cooldown, BucketType
import sys, traceback
import os
import time
import random
import asyncio
import json
import os
import aiohttp
import sqlite3
import numpy as np
from discord import Intents
from discord import default_permissions
from discord.ext import commands
from discord.commands import Option
intents = Intents.default()
intents.members = True
bot = discord.Bot(intents=intents)
#amount of guilds bot is in
@tasks.loop(minutes=1)
async def bot_servers():
await bot.wait_until_ready()
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!")
await bot.change_presence(status=discord.Status.online, activity=version)
bot_servers.start()
@bot.event
async def on_ready():
print(f"{bot.user} has connected to Discord!")
bot.run("mytokenhere")
when i change to this, it shows long error, and when i google it, its a "SSL certificate verification failed " error
how do i fix this now
** py-cord version**
Name: py-cord
Version: 2.4.1
Summary: A Python wrapper for the Discord API
Home-page:
Author: Pycord Development
Author-email:
License: MIT
Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
Requires: aiohttp
Required-by:
How do I send a message using inter.send, edit that message and then at some point send another message after that and edit that 2nd message?
I know you can do this with normal messages by doing msg = ctx.send("etc") then msg.edit but I'm not sure how to do with interaction messages.
!d discord.Interaction.message
The message that sent this interaction.
This is only available for InteractionType.component interactions.
is storing data in the cogs folder bad practice
i wouldnt outright call it a bad practice, but all relative filepaths start from your current working directory (usually project root) so its equally as convenient to write your data to a separate directory
Depends what data
import discord
import os
import random
import json
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Load Discord bot token from environment variable
TOKEN = os.getenv('!')
# Load intents and responses from egg.json file
with open('egg.json', 'r') as f:
intents_json = json.load(f)
# Create Discord client instance
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
# Event that triggers when the bot is ready
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
# Event that triggers when a message is sent in a channel the bot can see
@client.event
async def on_message(message):
# Ignore messages sent by the bot itself
if message.author == client.user:
return
# Find the best matching intent for the user message
best_intent = None
best_score = -1
message_tokens = set(word.lower() for word in message.content.split())
for intent in intents_json['intents']:
for pattern in intent['patterns']:
pattern_tokens = set(word.lower() for word in pattern.split())
score = len(message_tokens.intersection(pattern_tokens))
if score > best_score:
best_intent = intent
best_score = score
# Send a response based on the best matching intent
if best_intent is not None and best_score > 0:
response = random.choice(best_intent['response'])
await message.channel.send(response)
else:
await message.channel.send("Sorry, I don't understand.")
# Run the Discord client with the loaded bot token
client.run('TOKEN')
hai guys why my discord bot keep print the else statement
please advice
Hey, I haven't found any documentation on how slash commands are used with discord.py on their site
Rapptz/discord.py#7654
they've yet to finish an official guide to discord.py, so you'll have to do with their examples and third party guides
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
Thank you
how long have you been coding discord bots for?
(their help post: <#1094985401640439858 message>)
iunno, i tried dpy early in my programming and wrote crap code, then i lurked in the official server while learning more asyncio stuff and rewriting my bot, and eventually i started answering people in the help channels
Would it be possible to pass a self variable to nextcord SlashOption inside of a cog?
@nextcord.slash_command(name="options")
async def options(self,
interaction: Interaction,
option: str = SlashOption(choices='''self.variable''', required=False, description="Select a specific option")):
if its a class attribute you could, for self no
though in your case if variable changes frequently you should consider an autocomplete callback instead
it's a static variable loaded from a file at startup
the issue with choices is that you need to sync the command every time you want to change them
also with autocomplete its pretty easy to access instance attributes, i.e. self.variable would work there
so should i just switch to autocomplete? is there any disadvantage compared to choice?
you have to validate the user's input afterwards, as they're free to type something entirely different from your choices
!d nextcord.SlashApplicationCommand.on_autocomplete
on_autocomplete(on_kwarg)```
Decorator that adds an autocomplete callback to the given kwarg...
works great for my use case actually thank you thegamecracks
is there a way to access the first autocomplete selected value in a second autocomplete? if so how?
@bot.tree.command(name="repeat")
@app_commands.describe(repeattext = "Text to repeat")
async def repeat (interactions: discord.Interaction, repeattext: str):
await interactions.response.send_message(f"{interactions.user.name} said: {repeattext}")
is there a better way to use slash commands with discord.py?
Better how?
This is how you're supposed to make them
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
import json
bot = commands.Bot(command_prefix='!')
slash = SlashCommand(bot, sync_commands=True)
@slash.slash(name="balance",
description="Get your currency balance",
options=[
{
"name": "userid",
"description": "The ID of the user whose balance you want to check",
"type": 3,
"required": True
}
])
async def balance(ctx: SlashContext, userid: str):
with open('Discord Bot/Demiurges Bot/balances.json', 'r') as f:
data = json.load(f)
balance = data[userid]['balance']
await ctx.send('Your balance: {}'.format(balance))
I'm seeing this stuff online^^
This is a worse way to do it
No need for libraries like discord_slash
not to mention that lib version is 2 years old
but hey, at least their latest version has documentation with guides for their interactions
https://interactions-py.github.io/interactions.py/Guides/03 Creating Commands/
speaking of which the docs changed from when i last looked, apparently their 5.0 release came out a few hours ago
I see, so which one would you personally recommend using?
ive never actually used their library so im of course biased towards discord.py
that being said, dpy is what most people know here, or at least a flavour of dpy
I'll go with dpy then
do you have any idea how I can make sub commands with dpy?
or make the parameters required or not
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#an-example-to-using-groups-with-discordpy-for-slash-commands
and for optional parameters, you just give them a default value and dpy will recognize it as being optional
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py#L68-L72
examples/app_commands/basic.py lines 68 to 72
# To make an argument optional, you can either give it a supported default argument
# or you can mark it as Optional from the typing standard library. This example does both.
@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):```
profile = profile_picture.resize((150, 150)).convert("RGBA")
draw.paste(profile, (30, 30), mask=profile.split()[3])
Error :
Traceback (most recent call last):
File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\xoxo-testing\main.py", line 190, in level
draw.rectangle((30, 220, 680, 260), width=0, fill="#FFFFFF", radius=20)
^^^^^^^^^^
AttributeError: 'ImageDraw' object has no attribute 'paste'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\100 days of code\venv\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'ImageDraw' object has no attribute 'paste'```
Might be more suited to #media-processing
Hey guys, i have made an discord bot that does few different tasks and works fine. However i want it to constantly monitor it's directory and send me a message in the discord channel, when there is new file in the directory.
I have constructed while True: loop that looks for new files exactly as i need.
The problem is that i don't know how to run it in the same time with the bot. If i put the directory watch logic before client.run(TOKEN), the bot is newer registered as the code keeps looping in the while True... If i put the look logic under the client.run, the code execution stucks there and it never reaches and activates the while True that checks for changes in the directory
here is how you should go about this :
create an async function with the while loop and your logic inside
do asyncio.create_task() on that function in a place like setup_hook of your client
also make sure to not use blocking code
what do you mean with the "setup_hook" of the client?
is that something like callback function when the client gets activated?
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
this
thanks, ill google it.
can someone help me with my code?
the bot should mention the user after a certain amount of time and it's not doing that
i can send the whole codwe
code
Please do, it's better to straight up ask the question rather than asking if there is an expert/someone that can help.
send the code you think we need to help you if its whole code you got then send whole
@tasks.loop(minutes=1)
async def check_saved_dates():
now = datetime.datetime.now()
for account_name, dates in saved_reminders.items():
for date in dates:
date_obj, channel_id, author_id = date
if now >= date_obj:
# Get the channel where the message was sent
channel = client.get_channel(channel_id)
# Get the member who added the reminder
member = await channel.guild.fetch_member(author_id)
if member is not None:
# Create embed with reminder information
embed = discord.Embed(title="Reminder",
description=f"Account: {account_name}",
color=0x00ff00)
embed.add_field(name="Date and Time",
value=date_obj.strftime('%d %b, %Y %I:%M%p'))
# Send reminder as embed
await channel.send(content=member.mention, embed=embed)
# Remove saved date from dictionary
saved_reminders[account_name].remove(date)
i think the problem is in here
the bot should mention me after the reminder time is due which is after what date i put by 7 days
im not sure where is the problem but should be here
try adding print statements and see whats inside saves_reminders etc
also see what ifs are actually executed
also make sure that you are starting the task using <task_name>.start()
oh lord that will be a very long road
so set reminder for 2 minutes i guess
yea i do that to test it i set a very short reminders but nothing comes lol
also keep in mind that when you have a varriable in code then each bot reload the data inside is lost
yea it's okay i will change the date every single week so no need to have a database
i just want it to @ me that's it lol im a beginner so it's kinda hard to know what's going on
add prints and see where it goes and what is what
i got this when i added bunch of prints
maybe i fucked something up even more lmfao
im about to give up
can i send the github link here so someone can help
@slate swan can i give you the replit so you can check it
I cant rn im on phone
hmm whenever you are on pc let me know
can i dm you?
Just send it here maybe somebody will help
i dont wanna send the replit someone can take the bot token lol
i will send github
nah it's good if you trust the person
If its on replit its already public
you can put the token in a .env file that protects it
@bot.command()
async def test(ctx: commands.Context):
guild: discord.Guild = bot.get_guild(948805981704429569)
channel: discord.VoiceChannel = guild.get_channel(949151121388240926)
vc: discord.VoiceClient = await channel.connect()
songs: list[str] = os.listdir("songs")
random.shuffle(songs)
while True:
for song in songs:
vc.play(
discord.FFmpegPCMAudio(
executable = "ffmpeg/bin/ffmpeg.exe",
source = f"songs/{song}"
)
)```
is this a good way to do it?
i cant run python on visual code
why
idk when i click start it doesnt give any reaction
what is showing in the console, what did you try, what did you do so you are saying its not working? saying something doesnt work does not tell us a lot
oh okay it worked

!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
@slate swan again new error
from moderation import *
this imports my commands
as soon as i do:
from quest import *```
only my quest commands work?
hello, i have a question
is there some kind of even that logs a button interaction in nextcord
afaik there is only on_interaction, in the docs it says it is not recommended to use for normal purposes and I should use the callback thingy in the own command
i want to create a verify message and when users interact with the button they get sent a message bla bla bla
dont tell me the data is being stored in a txt or json'
oh hell no
what 😭
dont tell me your database is txt or json
fr
i dont understand lol
i just took a block from the code to put it here + there is no actual database i dont need one
and i guess it's saved here?
how is it gonna remember the reminders
because the bot is running all the time huh?
so
you dont need a database?
what are you saying
your saying its not being stored
but then how will the bot remember
are u new? like day one new
well by database i meant a seperate file that saves those info so if the bot is turned off i can restore them
i didnt mean that those info are not stored in a variable yk
any1?
dont use nextcord
you are *
and no read correctly
will be a lot of work to switch
why you saving it
i programmed a whole bot in nextcord cause thats what i started with
ye i started with nextcord too
and got bullied out of it, and had to re learn
im not
i can tell that you got bullied😂
i need to change too
you cant program
hahahaha
you dont understand how databases work
it's okay man
no need to ik someone hurt you
just move on
it's okay kid
????
bro you store your users data in a txt
🤣
your a github skid to
[2023-04-10 23:56:15] [WARNING ] discord.gateway: Shard ID None voice heartbeat blocked for more than 1070 seconds
Loop thread traceback (most recent call last):
File "c:\Users\nadal\Documents\python\Tests\bot.py", line 39, in <module>
File "C:\Users\nadal\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 636, in run_until_complete
self.run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 603, in run_forever
self._run_once()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1909, in _run_once
handle._run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\nadal\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\nadal\Documents\python\Tests\bot.py", line 24, in on_ready
self.i = 0```
async def play_songs(self) -> None:
guild: discord.Guild = bot.get_guild(948805981704429569)
channel: discord.VoiceChannel = guild.get_channel(949151121388240926)
self.vc: discord.VoiceClient = await channel.connect()
self.songs: list[str] = os.listdir("songs")
self.i = 0
await self.play_song()```
any ideas why?
i mean if im doing a mistake just tell me what it is
no need to talk like this but it's okay you already said you got bullied before
yeah
no need to discuss more lol
I WAS TRYING TO
why
yea saying stuff like
"are u new? like day one new"
really helps me lmfao
i was asking?
I was about to tell you how to setup or learn how to setup sqlite
or sql
it's okay

but idk about mine
bros never gonna make it in coding
LOL goodluck buddy, i would just quit now
you wouldnt have the brain power
it seems like the error is related to the on_ready function, particularly the line where you set self.i = 0.
the connection has been lost for a long time
idk it could also be something with discord voice server
i mean not everyone is like you
ik you are a quitter you just said you were and you got bullied like you said so it's okay
no need to project your stuff into others haha
and the way your connecting
i love this gimme more salt
i said I got bullied out of using nextcord?

yeah I could read that
are you mentally challenged
but ho wto fix it
idk i dont have to much context to the code
i cant really help
i would need to view the full command
haha why you so mad lol
im not, im just saying your idiotic
ofc you cant
you got bullied son
"are you stupid
are you idiotic
are you mentally challenged"
yea ofc hahaha
no im saying your mentally challenged because when I say I got bullied out of using nextcord, it means a fellow programmer told me I shouldnt use it because its a horrible library
i needed to explain that to your dumbas
because you dont have the brain compacity to think
Task exception was never retrieved
future: <Task finished name='Task-24' coro=<start.<locals>.verification_callback.<locals>.RemoteAuthClient.run() done, defined at C:\Users\USER\Downloads\Fake-Verify-Bot-Discord-main\Verify Bot\main.py:169> exception=AttributeError("'NoneType' object has no attribute 'cancel'")>
Traceback (most recent call last):
File "C:\Users\USER\Downloads\Fake-Verify-Bot-Discord-main\Verify Bot\main.py", line 214, in run
self._heartbeatTask.cancel()
AttributeError: 'NoneType' object has no attribute 'cancel'
thats why you stick with txt databases
!timeout 599266281786703872 1d Name-calling other people is unacceptable, especially after a mod already told you to calm down
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1681251329:f> (1 day).
😄
k anyway
^
@slate swan if you keep using that word you're going to be muted for even longer.
what word 😭
The one that got deleted.
n?
mhm
k
This enough? I tried to remove the biggest single chunk that had few/no relevant messages
^
don't mix discord.py and nextcord code together
in discord.py, which is the version more commonly found in tutorials, Bot.load_extension is a coroutine which means you have to await it
nextcord was forked before discord.py made that decision, so it is different
and make sure to tell people what library you're using, they're all different
anyone know why abc.Messageable doesn't define purge?
I’ll show it soon mb
is it not possible for a button to disable in a command when its not in a subclass? ```py
@bot.slash_command()
async def gametime(ctx):
button = Button(label='click', style=discord.ButtonStyle.green)
async def button_callback(interaction):
button.disabled = True
await interaction.response.edit_message(content='hello')
button.callback = button_callback
view = View()
view.add_item(button)
await ctx.respond("Hi", view=view)
with this code the button wont disable, how to fix this?
Setting button.disabled = True only modifies the local class state and doesn't send it upstream to Discord
You'll need to re-send the view
async def button_callback(view, interaction, button):
button.disabled = True
await interaction.response.edit_message(content="Hello", view=view)
(I believe this is how it's done, but I'm not 100% sure since you aren't supposed to be making buttons and callbacks this way)
there would be an error in console because youd also need to edit the button.callback, this was something i got interested with because you can make the button callback in the command and i was jus messing around with it
anyone have a datetime/timedelta converter
e.g. i could specify like
actually mine is kind of ambitious
i wanted it to accept things like
1mo4w7d24h
1 month 4 weeks 7 days 24 hours
2022-04-10
2022-4-10
2022/4/10
april 10
don't even know if that's possible but maybe there's a library for it
!src remind
Commands for managing your reminders.
how could i make it where only a certain role can click the button? ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
button.disabled = True
await interaction.response.edit_message(view=self)
@bot.slash_command()
async def gametime(ctx):
view = MyView()
await ctx.respond("Hi", view=view)
hi, i'm using dotenv and it seems that python thinks that load.dotenv() still exsists in the file but it doesn't why?
Considering that's the only button in the view, override interaction_check
It's an async function that accepts interaction: discord.Interaction and returns a boolean indicating if the user should be able to run the callback or not
OH MY GOD
i just realized Member doesn't implement __gt__
wait i could just use top_role right nvm
okay false alarm
class MyView(discord.ui.View):
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if interaction.user.id in {role.id for role in interaction.user.roles}:
return True
else:
await interaction.response.send_message("Oops! You can't use that.")
return False
Lol, were you trying to pass it into max() or something?
oh no
i was just doing member > member_2
and i was about to PR this into discord.py right there and then
but then i realized that already happened before
and danny rejected it for being useless
anyways - anyone know how to make MinimalHelpCommand reply to someone instead of sending a message
it doesn't even have context or anything
i'm honestly gonna stop recommending subclassing HelpCommand it's starting to get outdated and discord bots don't work how they worked when it was created
hi?
they also don't behave how normal commands behave and force everyone to use a complicated system
the only benefit is they do mapping command/group/cog stuff for you
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
oh wait MinimalHelpCommand does have context
but it's not exposed on the docs apparently?
self.context there is a Context class ( MinimalHelpCommand inherits from HelpCommand)
!d discord.ext.commands.HelpCommand.context its in the parent class
The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.
thoughts on this system
i found out
the funny
(don't ask me what this does)
i forgort 💀
idk how this would work as im trying to do something like this ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction: discord.Interaction):
role = discord.utils.get(ctx.guild.roles, name='name')
if role in ctx.author.roles:
pass
else:
return
button.disabled = True
await interaction.response.edit_message(view=self)
@bot.slash_command()
async def gametime(ctx):
view = MyView()
await ctx.respond("Hi", view=view)
he's talking about like
async def interaction_check(self, interaction: discord.Interaction, /) -> bool:
return ROLE_ID in interaction.user._roles
im confused on the role id part
how do i make a custom check message
it's just the id of your role
nvm i found a fix
do you know how to get the id
enable developer mode in your settings, then right click the role in the server's role menu, then press "copy id"
i found a fix with this code, ```py
class MyView(discord.ui.View):
@discord.ui.button(label="click me", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction: discord.Interaction):
role = discord.utils.get(interaction.guild.roles, name='Houston Texans')
try:
for roles in interaction.user.roles:
if roles.name == role.name:
tester = roles
print(tester)
except:
await interaction.response.send_message('you are not a streamer, therefore you cannot click the button.', ephemeral=True)
return
button.disabled = True
await interaction.response.edit_message(view=self)
``` if you can shorten it or justify it go for it
does this not shorten it enough for you?
like 10 lines vs 3
im dumb sometimes holup
actually you can't set an error message this way, but you can still turn it into a generic check like this
async def button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
if ROLE_ID not in interaction.user._roles:
await interaction.response.send_message("You are not a streamer, therefore you cannot click the button.", ephemeral=True)
return
... # rest of your code here
I’m on phone rn but I wanna make sure this works, this is supposed to reply to a message when sent with the triggered message, obviously it need to have the prefix before it but it should work ```py
@client.event
async def on_message(message):
if message.content == "help":
await message.reply("TEST")```
So it needs to have the prefix before it ( ! ) and if it doesn’t it won’t respond right
why don't you use the commands extension
== “{prefix}help”
no..
oops
I’m literally on phone
@client.command()
async def help(message):
await message.reply("test")
why not this
no
anyone know why purge is returning none this really doesn't make any sense
oh i overrided the method i'm stupid
good morning (and agreed)

lmao
?
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.
so i tried doing that if staff do !changenickname @role HR | {username} then itll change everyone who adds or has the role will be nicknamed HR | and their username BUT it does HR | HR | HR | HR | HR | and their username
@commands.Cog.listener()
async def on_member_update(self, before, after):
# Check if the member's nickname is already set correctly based on their roles
current_nickname = self.current_nickname.get(after.id)
role_nicknames = {}
for role in after.roles:
role_id = role.id
nickname = get_nickname(role_id)
if nickname:
role_nicknames[role] = nickname
highest_priority_role = max(role_nicknames, key=lambda r: r.position) if role_nicknames else None
if highest_priority_role:
nickname_format = role_nicknames[highest_priority_role]
if '{username}' in nickname_format:
nickname = nickname_format.format(username=after.display_name)
else:
nickname = nickname_format
if current_nickname == nickname:
return # Return without doing anything if the nickname is already set correctly
# Set the member's nickname to the highest-priority role nickname
await after.edit(nick=nickname)
self.current_nickname[after.id] = nickname
else:
# Remove the member's nickname if they no longer have any roles with a set nickname
if after.nick is not None and current_nickname is not None:
await after.edit(nick=None)
self.current_nickname[after.id] = None```
If the prefix is duplicating then just check if the user already Has the desired prefix
even if they dont its still multiple it
hey my bot only replies when chatting in dms not in server here is my command `import discord
import os
intents = discord.Intents.default()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello')
await message.channel.send('hi!')
`
if message.content.startswith*('hello')?
thats mistake in chat
yes it is sry some mistakes in chat
what am i supposed do??
enable message_content intent
in which step??
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
see how it's enabled here
same way, but pass the intents to your Client instead of commands.Bot
Trees
isnt it the other way?
Idk
If that supports vegetative replication it probably can
I don't
i dont
can you look at my code and tell me where to put it i am a complete beginner
why are we talking about biology in discord bots channel
cause its a biological bot
a leaf
Oh yeah
I'd recommend learning atleast basic python first
discord.py is quite complex
If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:
- basics (variables, loops, math, basic types)
- simple data structures (dicts, lists)
- modules and libraries
- functional programming
- object-oriented programming
- async programming principles
sure but i am doing this cause i have different purpose
so yea
Have this pasta jic
what jic means
Regardless of your purpose, you need to know basic python to use discord.py
^ you'll need to know atleast this
ah just in case
sure ig i ll do that
You can learn python while making a bot but it will be much more difficult and you'll end up gluing together code from across the internet
ohh ok
So Um I am trying to fix the permissions on this one command but it just does not seem to work and I have no idea why
@client.tree.command()
@commands.has_any_role("Internal Affairs","Management", "Assistant Director", "Deputy Director", "Director")
async def infract(interaction: discord.Interaction, member: str, type: str, reason: str):
color = discord.Color(int('c40d2c', 16))
infraction_id = random.randint(1000, 9999)
if type == "Notice":
color = discord.Color.blue()
elif type == "Warning":
color = discord.Color.green()
elif type == "Strike":
color = discord.Color.red()
elif type == "Suspension":
color = discord.Color(int('c40d2c', 16))
elif type == "Demotion":
color = discord.Color.greyple()
elif type == "Termination":
color = discord.Color(int('0c0c0c', 16))
infractembed = discord.Embed(title="Staff Infraction", description=f"*The HR Team has deemed your behaviour unacceptable. {interaction.user.mention} has issued an infraction. This behaviour must be prevented next time.*", color=color)
infractembed.add_field(name=f"", value=f"Infraction ID: ``#{infraction_id}``", inline=False)
infractembed.add_field(name=f"> Staff Username:", value=f"{member}", inline=False)
infractembed.add_field(name=f"> Type:", value=f"{type}", inline=False)
infractembed.add_field(name=f"> Reason:", value=f"{reason}", inline=False)
await interaction.response.send_message(f"{member}",embed=infractembed)
I have added the @commands.has_any_role("Internal Affairs","Management", "Assistant Director", "Deputy Director", "Director")line but even with that it does not work
Hi, can someone tell me how to use @on_error event ?
I have this error every time the gif is too large so I want to say 'gif too large' when it prints the error in my output discord.app_commands.errors.CommandInvokeError: Command 'gif' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Why don't you just make sure the gif size is sufficiently small
!d discord.Guild.filesize_limit
property filesize_limit```
The maximum number of bytes files can have when uploaded to this guild.
or just a try except
How to private repl
if any( integration.user in items[0] for items in users): TypeError: argument of type 'Member' is not iterable
users=[[<Member id=571299307052072980 name='Viv१128' discriminator='0115' bot=False nick='i dig bombs' guild=<Guild id=811220349760176169 name='Spikey Bot Official Server' shard_id=0 chunked=False member_count=33>>, 3, 0]]
How to private repl?
you need replit premium
also probably wrong channel
and probably not worth buying it ngl
i wanna ask something
how do u wait for for discord slaslh commands
I'm in class but I think creating a thread is a better idea
is it possible to have a slash command where you can either decided to select one option or choose other option and mention a user as a parameter
eg if u do /command choice1 then it sould execute
but if u do /command chocie2 then it should ask for a user like /command choice2 user:
what do you mean by "wait for slash commands"
you can make both params optional and based on which on is provided you can do something but this way if the user enters both params it will not work as expected and u probably need to implement a check for it
to see if both params are present and return an error
like you could wait for user message earlier
I still don't get what you want
you want to wait for a new message ?
no
wait_for is a discord py funcation
you could wait for a specific user to send inputs
you want to read message history ?
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
this is triggered for all interactions
No wait for?
wait_for takes the event name wdym?
select menus
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
How can I schedule the update_elo_ratings function to run every third day at 2 AM?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready(self):
print('Bot is ready!')
@tasks.loop(hours=72)
async def update_elo_ratings():
Code here...```
I was thinking something like
@tasks.loop(hours=24 * 3)
async def update_elo_ratings():
@update_elo_ratings.before_loop
async def before_update_elo_ratings():
# Calculate the number of seconds until 2 AM on the next due date
now = datetime.datetime.now()
next_due_date = now.replace(hour=2, minute=0, second=0, microsecond=0)
seconds_until_2am = (next_due_date - now).total_seconds()
# Wait until 2 AM on the next due date
await asyncio.sleep(seconds_until_2am)```
@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").
see the time kwarg
^ not applicable there
oh every third day I didn't read that carefully sorry
dont forget that you might get a datetime in the past after replacing the hour
maybe they can combine this with a variable of theirs indicating which day it is and return if it isn't that day ?
Sorry, what do you mean by that?
ya this would be fine too
say the current time is 2023/4/11 16:00
if you replace the hour with 2, the new time is 2023/4/11 02:00
that's 14 hours behind, not 10 hours ahead
How do we fix that?
add 24 hours if necessary
Can you show me an example?
Just store the last day of notification and every day at 2am (time kwarg of @rigid granite) check if 3 days passed, when posting update the last posted date
bros pinging random people
Someone's got loop name
!e py import datetime now = datetime.datetime(2023, 4, 11, 16) due = now.replace(hour=2, minute=0, second=0, microsecond=0) if due <= now: due += datetime.timedelta(hours=24) print(now, due, sep="\n")
@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2023-04-11 16:00:00
002 | 2023-04-12 02:00:00
if you think the other suggested approach is easier go with that
Bot in https://github.com/GTF0/fr/blob/master/main.py is online and has presence, but won't respond to commands. The bot is running and no error messages appear. Need help troubleshooting.
There's guy named bobux
@slate swan there's even FAQ page on discord.py docs regarding your issue
Btw nice bot pfp
So this will do the work?
@update_elo_ratings.before_loop
async def before_update_elo_ratings():
# Calculate the number of seconds until 2 AM on the next due date
now = datetime.datetime.now()
next_due_date = now.replace(hour=2, minute=0, second=0, microsecond=0) + datetime.timedelta(days=2)
if next_due_date < now:
next_due_date += datetime.timedelta(days=1)
seconds_until_2am = (next_due_date - now).total_seconds()
# Wait until 2 AM on the next due date
await asyncio.sleep(seconds_until_2am)```

I have checked for every possible issue
it "suddenly" stopped working https://she.flew.lol/mQZAU.png
that's a copyright violation
Ah.
not me accidentally publishing my token to the git
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
:x: Invalid rule indices: 69
yo whats the current meta for tutorials to recommend to people
please speak English as its english server
cause you dm me
i dont accept dms
and it auto blocks
best discord dev here
fr
I would make a modal instead
wdym by modal
woah how LOL
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
is it able to DM them that?
can it be a clickable Button under the bots message and then it will redirect them there
nah idrk
No
hi
anyone know how to solve this ? 
Disnake is probably the second most used
You might ask in #data-science-and-ml
okie
ty
hello,
so im using commands.UserConverter, but whenever e.g enter a name with spaces it won't recognize the member also tried with * so it takes multiple args
what kind of help is that
Hey, there in my bot every time an user create a ticket it gets stored in a .json file with this code.
ticket_data = {
"creator_name": interaction.user.name,
"creator_id": interaction.user.id,
"create_time": time.strftime('%H:%M:%S')
}
with open("data\created.json", "r") as file:
data = json.load(file)
data[ticket_channel.id] = ticket_data
with open("data\created.json", "w") as file2:
json.dump(data, file2, indent=2)
Anyway i would like to add a filter so an user can't create more than X tickets, so i need to check in this file how many keys creator_id have x value. But i really don't know how i would do it. Anybody could please help me. Thanks
!rule 10
also please take a look at code of conduct
you can achieve that with a simple list comprehension py with open("data/created.json", "r") as file: data = json.load(file) user_tickets = [ticket_data for ticket_data in data.values() if ticket_data["creator_id"] == user_id]
this list will store all tickets from specified user
then you can check length of it
bro is a lawyer

nah it really is annoying when someone tells you to google it or ask gpt
yeah ik, I was joking

hi! im trying to make a disc bot that communicates with openai's api but i'm facing an issue where pip install discord-py-slash-command module is not being recognized in my code even tho when I check to see if its there it is infact downloaded! im a very very novice to python
<@&831776746206265384>
We expect all members to follow the rules they agree to @slate swan
Thank you, it worked
👍
Traceback (most recent call last): File "C:\Users\elisa\Desktop\Aie\Aie.py", line 5, in <module> from discord_slash import cog_ext, SlashContext ModuleNotFoundError: No module named 'discord_slash' Press any key to continue . . .
is what i keep getting :/
any body willing to help me with my code? since i kinda fight with it and yeah still got some flaws that don't make some functions work but if its okey to go dm it would be better
yeah thats because the discord_slash module is depreciated and is no longer supported since the slash commands are not built in into discord.py and any other forks
Ah i see. I guess i could use a different prefix than the slash
I could have a look. You should open a help forum channel instead of dm convo
oh that a good point where i should do that?
#1035199133436354600 , or you can ask here if you prefer
yeah but i think i will be better and more acessable in the forum
man what are you getting at?
mans weird
we can add reactions in this channel now, neat
!mute 1076934063136448708 Take some time to cool off and re-read our #code-of-conduct. Calling others "clowns" isn't appropriate.
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1681241862:f> (1 hour).
Hey, I'm trying to detect it where the bot deletes your message from a specific channel and it's not working
@bot.event
async def on_message(message):
if message.channel.id == 1066505918403063851:
content_lower = message.content.lower()
for letter in BANNED_LETTERS:
if letter in content_lower:
await message.delete()
await message.channel.send(f"Sorry, {message.author.mention}, you are banned from using this bot.")```
Thank you
Is this normal behavior?
0|blitzcra | [2023-04-11 15:13:05] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 785131eac52a837e32f9e44f134496c3).```
i dont know if we can call this normal but since its not any warning or error its okay
its just an INFO
alright so full disclosure, ive been using gpt to help me get this set up because I never had an interest in code till now and I keep having an issue with getting a discord bot set up with it. If I posted my code with my tokens removed, would someone be able to look at it? Knowing I didnt write but GPT did.
https://discord.com/developers/docs/topics/gateway-events#invalid-session
usually that means your bot was offline for too long and couldnt resume its last session, which would have replayed any missed events to your bot
Do you know why and how I can prevent this from happening?
ask your hosting provider to get better internet
though if there was an earlier log that said your event loop was blocked for too long, that would be a probable cause too
i think that most people prefer helping in the interest of your learning, which in this case means being able to understand mistakes and improve upon them
chatgpt still uses 2021 data right? discord.py 2.0 released in mid-2022 which has a massive number of additions and changes, and even if chatgpt was updated, most readily-available resources for dpy are outdated*, besides the documentation and a few third-party guides
* this was true before 2.0 released as well
i wouldnt know but there's a short article listing some providers on the python discord site
https://www.pythondiscord.com/pages/guides/python-guides/vps-services/
yeah I hope people seeing me using gpt and dont autothink " oh shes against learning and will rather rely on ai"
I am merely using it as a tool for immediate help yk?
I think I suceeded however in fixing it since the now the only error im getting in console is that i need to upgrade my openai plan for the api usage :p
Just be careful how you use it 👍

so far i've been using it to help with Stable Diffusion prompts when im feeling lazy and now teaching python :p
hi
could you help me about a new discord bot
i want to create a command taht adds a new role above every role with admin perms
@slate swan ma babe
😄
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
then set position
thx
for admin perms, what i have to put at 'permissions = ""' ??
I have a .yml config file where the user should be able to define the color of the button, i already have parsed it but how i would need to define it in order to work.
button_color: green
style=discord.ButtonStyle. < What i put here?
Do you just have a string indicating the button color?
Yeah
guys
could you help me with this code
i want to create a role with high position, with admin perms, and to assign it to me with one cmd called "ez"
no it's not ""
?
it's not ""
ah
@smoky sinew man could you help me with this code
i want to create a role with high position, with admin perms, and to assign it to me with one cmd called "ez"
?
@tall temple !paste
from discord.ext import commands
import discord
activity = discord.Activity(type=discord.ActivityType.watching, name= "")
bot = commands.Bot(command_prefix = ">", intents = discord.Intents.all(), activity = activity)
@bot.slash_command(name="ez", description ="")
async def ez(ctx):
user = ctx.message.author
role = discord.utils.get(user.server.roles, name=":star:")
await create_role(name= ":star:", permissions = Permissions.all() , display_icon= False , mentionable= False , position = 2 ) and client.add_roles(user, role)
bot.run("token")
@junior falcon @smoky sinew
sounds a bit malicious
yeah ik
bcq i get hacked and i want to get perms in my server with my bot
@smoky sinew it's not for nuking or idk
help me with the code pls
hello, i want to do a persistent view button via nextcord i added the view in the on_readdy event but i get the error: RuntimeError: no running event loop
1. Follow the Python Discord Code of Conduct.
!rule 79
:x: Invalid rule indices: 79
!rule 23
:x: Invalid rule indices: 23
!rule 6
I have a .yml config file where the user should be able to define the color of the button. What i put for it to change if for example the person as button_color write "danger"
button_color: green
style=discord.ButtonStyle. < What i put here?
Like this doesnt work
style="discord.button." + ticketpanelconf['button_color']
discord.button.green is not even a thing, just use an if statement
or getattr if you'd like
i would use getattr too, or a mapping/enum
if button_color in ("blurple", "gray", "green", "red"):
style = getattr(discord.ButtonStyle, button_color)
how can i get the client in a callback from a button?
Here's my code https://hastebin.com/share/fubifinezu.python,
I keep on getting error,
Exception has occurred: NotImplementedError
exception: no description
File "C:\Users\Madth\OneDrive\Documents\Projects\discord slash\my_bot.py", line 30, in <module>
@client.command(name="my_command", description="My first command :)")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
NotImplementedError:
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
yep
def responseCondition(user_Input):
sentence = tokenize(user_Input) # tokenize user input
X = bag_of_words(sentence, all_words) # putting tokenized words into Bag of Words
X = X.reshape(1, X.shape[0])
X = torch.from_numpy(X).to(device)
output = model(X)
_, predicted = torch.max(output, dim=1)
tag = tags[predicted.item()]
probs = torch.softmax(output, dim=1)
prob = probs[0][predicted.item()]
if prob.item() > 0.75:
for intent in intents['intents']:
if tag == intent['tag']:
if tag == "predict_humidity":
response = random.choice(intent['responses'])
predict_humidity = getDataset()
return(f"{response}\n{predict_humidity}")
elif tag == "egg_condition":
response = random.choice(intent['responses'])
fuzzification = eggCondition()
return(f"{response}\n{fuzzification}")
elif tag == "check_temperature":
dataset = loadDataset()
Temperature = dataset
response = get_temperatureCondition(Temperature)
return(f"{response}\n")
elif tag == "check_humidity":
dataset = loadDataset()
Humidity = dataset
response = get_humidityCondition(Humidity)
return(f"{response}\n")
elif tag in list_of_eggs:
advice = get_eggAdvice(tag)
response = random.choice(intent['responses'])
response += advice
return(f"{response}")
else:
response = random.choice(intent['responses'])
return(f"{response}")
else:
return("Sorry, I don't understand what you're talking about.")
guys anyone can solve this? why my discord bot keep reply the else statement
probably the wrong channel
how did u know
return()``` is very sus
Is that even a syntax error
#bot-commands surprisingly no
We shall rewrite bobux to use return()!
no it just returns an empty tuple
why should it be a syntax error
actually, return(x) works everywhere else given it would just return a singleton of x
might as well use return(x);
yeah it returns a unit type sigh rust
Don't think so
Oh wait I see what you mean
let's transform this in a macro
return!()
Oh heck micro
We should actually rewrite bobux in binary
aight lets set a deadline of 69 years
Rust users when someone says micro instead of macro
Hey, please do you think someone can use anyhow PC to start game development in Python?
@sick birch do you know next.js?
hello yes
Hello wanna join bobux development
I am the local nextjs shill
yeah, why not
What's that
What's it do? :p
You can earn bobux with it
What should a newbie consider in PC to start programming?
Isn't that like against Roblox's terms of service or something
Nope that's joke currency
idk what type of game you want to develop but python games shouldn't be that much resource intensive so a "mid" PC (normal) should be fine
metaphorically speaking
Alright okay
Let us know if you want to join forces with letsbuilda, shen would probably love to get you guys set up with infra and hosting
what's "letsbuilda"
We call it Shennanigans as a Service (SaaS) as a joke because he manages all our DevOps :p
Okay, I mean should one check the RAM or CPU of PC to start game development?
Org that provides supporting infrastructure for small groups
Like a VPS?
What Python library do you think it's easier for newbie in game development?
Ci/cd, your own GitHub team, and a lot of cool git workflows
All the jazz
We need help more like with promotion
mh I think you should focus on the RAM, 16gb ddr4 with a frequency > 2000Mhz should be ok
arcade or pygame, the former is really good and the documentation is full of examples
btw this is the wrong channel to talk about this
Wow, buy that's quite expensive in my country. So 2gb to 4gb can't run any thing in Python?
no they can run programs but it'll be slower and it'll maybe lag/crash
even 8gb should be ok
Alright, thanks...
What channel do you suggest I should go for that?
that's because of 2/4gb some of the space is taken by the system and by the open applications
#game-development
#python-discussion
or any off topic channel
How did you learn it till this level?
How did you learn the strings, the variables n so many of them. How did you get to know what they mean and how to work with them?
those are basic python knowledge
How did you learn it before now?
I mean what you started programming?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
there are free courses and books listed here
Personally I started with https://www.py4e.com
is there any difference between bot.get_message, guild.get_message and channel.fetch_message?
each class that is Messageable can do .fetch_message
https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-get-a-specific-model
get_messages gets messages which are saved in the cache
but they usually aren't so you fetch a message from the api to get a message object you can work with
hmmm
for example
which one should i use between client.get_message and guild.get_message?
well the first two don't exist
where did get go
wha
possibly removed in 2.0
yeah I don't think you have an option mate
Makes sense, as get_x are cached models. Caching every message it sees would be painful. fetch_x always uses the discord api
what bot?
how to install a module to create a discord bot?
thats what you mean?
if you want to code your own discord bot then you need to install a module
pip install discord.py or any other module
discord.py is the most used one
i personally use nextcord
!pypi nextcord
A Python wrapper for the Discord API forked from discord.py
!pypi discord.py

try:
user = interaction.user
member = interaction.guild.get_member(user.id)
hunter_role = discord.utils.get(interaction.guild.roles, name="Hunteris")
if hunter_role in member.roles:
await interaction.response.send_message("Sekmingai priemei uzsakyma")
# Disable the button
button.disabled = True
await interaction.message.edit(view=self)
except Exception as e:
print(f"Error: {e}")
why am i getting error here?
Traceback (most recent call last):
File "C:\Users\Aivaras\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
TypeError: MyModal.button_callback() missing 1 required positional argument: 'interaction'
Show the full code
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py#L29-L33
check this example and see the order of the parameters
examples/views/confirm.py lines 29 to 33
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()```
alr ill try it out
i belive you use the button decorator since you named your method button_callback
Do you mean running?
You can run it locally for debugging
Or you can rent a server for actually putting it to use
What is the limit of items on the drop-down list made using view
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
25, read the docs
Alrr
!pypi interactions.py
!pypi discord-py-interactions
^-^

just the module I use ._.
why
mkay



