#discord-bots
1 messages ยท Page 212 of 1
ohh
!d discord.Interaction.message
The message that sent this interaction.
This is only available for InteractionType.component interactions.
note that this is only available if the Interaction comes from a component
oh so like if i click a btn so whatever the button gives....as an output
wdym
when someone click a button your Bot receives a INTERACTION_CREATE event
this event payload contains a reference to the message which the button is part of
hence there's this attribute
like if the user clicks the btn then i want to bot to edit that btn to the text
you want to edit the button text?
wait
like
I clicked the btn now i want the bot to edit that msg with btn and write hello over there
get it??
it's the same thing but instead of passing just the view here you'll pass a string (or an embed or whatever) too
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
i did it but i doesnt remove the btn
it just adds the text to the msg
i want to remove the btn and add the text to the same msg
you need to pass view=self
async def on_click(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(content="You clicked me!")
await interaction.message.edit(view=self)```
im doing this
join my test server imma show u
you're not disabling the message also you can edit everything in the edit_message
no you're not, you're also using interaction.message.edit
Are you
button.disabled = True
await interaction.response.edit_message(content="some text", view=self)
I thought I was clear ๐
btw I need to study bye
Then set view to none
but also want some text instead of it
either im dumb or im not able to explain my issue
ITS DONEEEEEEE I DID IT
help again....
from discord.ext import commands
from discord import app_commands
class hbday(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@app_commands.command(name='mrhappybday', description="Happy Birthday")
@app_commands.describe(member="Member to wish (leave empty to with yourself).")
async def hbday(self, interaction: discord.Interaction, member: str = None):
view = View()
await interaction.response.send_message(view=view)
class View(discord.ui.View):
def __init__(self):
super().__init__(timeout=3)
@discord.ui.button(label="Click Me!", style=discord.ButtonStyle.blurple)
async def on_click(self, interaction: discord.Interaction, button: discord.ui.Button):
self.remove_item(button)
await interaction.response.edit_message(view=self, content=f"Happy Birthday {}")
async def setup(client):
await client.add_cog(hbday(client))```
here i want to access member (async def hbday(self, interaction: discord.Interaction, member: str = None):)
and use it in await interaction.response.edit_message(view=self, content=f"Happy Birthday {HERE}")
how do i do this
anyone??
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
Do you know how imports works
so you meant no
ButtonStyle is not in the ui
from discord.ui import Button, View
from discord import ButtonStyle
not working
how did you implement it?
๐
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py
check out this counter button implementation
whats the update method of using action_row 's ??
!paste
https://paste.pythondiscord.com/tohojodase - this is the source im trying to get working but im getting errors when running it
You just update view comps and msg.edit(view=view)
view comps and msg.edit(view=view) ??
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
Wait what are you trying to do?
What makes you think this is doable
anything is possible
That's not possible
I've always hated that sentence
Yes except you need to use modified discord client and that's against ToS
Since relative position of embeds and buttons is regulated by client
"Everything is possible"?
There are events that can occur with 0% probability which means they can't occur so that's invalid yeah
can i use a message sent by a followup as a variable ?
Yeah I think
what do I need to import to use discord slash commands
Itโs been ages since Iโve been here, lol
is it possible to create a slash command with python requests?
yes
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
the example here is using requests :)
why do you need to use external module for slash commands?
Seems more like a #databases question.
Also don't use sqlite3 with Discord bots as it's a blocking library. Use an async alternative such as aiosqlite.
what can you not understand there
whats corutine
let's say your message is issuing a slash command
Then my reply is like interaction.response.send_message()
and this reply is a interaction.followup.send()
huh!?
I mean, you can google it
i googled and then came here
Let's see
i can understand from tutorials better but cant find one
A coroutine is a method that can be paused when we have a potentially long-running task and then resumed when that task is finished.
what can you not understand here?
ok so like we have a very long task.....
so we paused it and did something else and then resumed the big task
There are lots of guides for asyncio pinned in #async-and-concurrency if you want
oh ook ok
Although I'd recommend making sure you understand basic python concepts like functions, classes, etc first
i do understand thoose
whats followup
yea and what are the attributes of defer
i mean there are 2
epheral and thinking
what they do
its not an attribute of defer, its a keyword argument of defer, thinking will showup a thinking message for your slash command response, which are edited after you send a followup
ephemeral keyword argument is to make your followup ephemeral
yea yea that key arg
how to check is_owner() in app_commands
class ChannelSlowmode(nextcord.ui.StringSelect):
def __init__(self):
@nextcord.ui.StringSelect(placeholder="Please select a slowmode delay", max_values=1, options=["30 secound", "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour", "2 hours", "4 hours", "6 hours", "8 hours", "16 hours", "24 hours"])
async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
option = select.values
match option:
case "30 secounds":
t = 30
case "1 minute":
t = 60
case "5 minutes":
t = 300
case "10 minutes":
t = 600
case "15 minutes":
t = 900
case "30 minutes":
t = 1800
case "1 hour":
t = 3600
case "2 hours":
t = 7200
case "4 hours":
t = 14400
case "6 hours":
t = 21600
case "8 hours":
t = 28800
case "16 hours":
t = 57600
case "24 hours":
t = 86400
await inter.channel.edit(slowmode_delay=t)
await self.message.edit(content="HI")```
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 296, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 121, in edit_channel
view = ChannelSlowmode()
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\view.py", line 46, in __init__
async def on_select(self, select: nextcord.ui.StringSelect, inter: nextcord.Interaction):
TypeError: 'StringSelect' object is not callable````
@app_commands.describe(count="Number of messages to delete")
@is_owner()
async def toggle(self, interaction: discord.Interaction, *, command):
command = self.client.get_command(command)
if command is None:
await interaction.response.send_message(f"{command} not found")
elif interaction.command == command:
await interaction.response.send_message("You can't disable this command")
else:
command.enabled = not command.enabled
ternary = "enabled" if command.enabled else "disabled"
await interaction.response.send_message(f"{command.name} {ternary}")```
error
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.modCommands' raised an error: TypeError: parameter 'command' is missing a type annotation in callback 'modCommands.toggle'
add annotation to command parameter
@nextcord.ui.StringSelect it should be string_select for a decorator
also pro tip instead od doing this big match case
you can do this:
@nextcord.ui.string_select(..., options={"30 seconds": 30, "1 minute": 60, "2 hours": 7200, ...})
directly when defining options
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 742, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\cog.py", line 11, in <module>
from modules.server_moderation.view import ChannelRename, ChannelSlowmode
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\server_moderation\view.py", line 42, in <module>
class ChannelSlowmode(nextcord.ui.string_select):
TypeError: function() argument 'code' must be code, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 369, in <module>
main()
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 58, in main
bot.load_extension(f"modules.{folder}.cog")
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 864, in load_extension
self._load_from_module_spec(spec, name, extras=extras)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 745, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.server_moderation.cog' raised an error: TypeError: function() argument 'code' must be code, not str```
change it for decorator not for Inheritance
How could I make this code:
@client.tree.command()
async def commandlist(interaction: discord.Interaction):
"""Lists all the available commands"""
await interaction.response.send_message("/add [cardname] @[target] (Can only be used by High Staff members and Developers)\n/cardlist\n/inventory @[target]\n/commandlist")``` result in a code block ```(like this)``` instead of being plain text? I've already tried looking it up, but I can't find anything about it
Right now, it just looks like this:
/add [cardname] @[target] (Can only be used by High Staff members and Developers
/cardlist
/inventory @[target]
/commandlist
Oh!
before and after
๐
anyone here experience with psql databases and on_voice_state_update events (before and after)
So I have added a sticky message in a channel. How do I make the bot check if there's a sticky message in the channel and deletes it after sending another sticky message?
You need to use db
If someone join a voice before is none also if someone leave then after is none
before, after both are discord.VoiceState object and you can get VoiceChannel object of after and before with channel attr
don't ask to ask
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
if message.channel.id == 1062309347239137320:
if message.content.startswith(''):
await asyncio.sleep(20)
await message.channel.send('This is the channel where you can post images and other contents. Do not send any explicit content here. Doing so will result in a punishment.')
return```
Its sending multiple messages
i'm working on voicemaster, but i need to do the event handler for it, no idea where to continue from where im from rn LOL
You need to save the pervious msg id then everytime a new message sended in sticky message channel check and delete pervious message then send new message
now the issue is multiple msgs
you probably need to check if a user joined the "create" vc, then make a new channel and move them to it
Why are you saying if message start with "nothing"
What's the point
its for sticky msgs dude
Okay what's your problem right now?
multiple msgs sending (spam)
Bot responding to its self
Hmm
wait I dont
Check if before is none ( someone joined voice)
Then if it's true create voice channel and move the member to that voice channel
yeah i know that, but since I'm using psql for my database it's a bit tougher lmfao
that's the part im stuck with rn, is using the database info and making it work like that
All you need is to save the id of join to create voice
That's why I've got this rn
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
data = await self.bot.db.fetch('SELECT voice FROM voicemaster WHERE guild_id = $1', member.guild.id)
if data:
what's not working
Okay that's looks okay
Alright that's good to know
But how would I make the vc then and move them to it with htis, cus im not 100% sure how that would go then
!d discord.Guild.create_voice_channel
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
Just add check and check if someone joined ( before is none) to that voice channel ( join to create)
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
Then also you need to save new voice channel where member moved to so when no one is in the voice channel you delete it
That's all ig
yeah ive been tryna figure it out but i cant get further
purely because of all the database work
Check If after is none ( someone leaved) then get new voice channel and with members attr you can get list of members that are in the voice check the len of it if 0 then delete voice
Hey everyone! I'm trying to implement a /give command to my card bot, but I'm having some trouble. Could someone point me in the right direction? Here's my entire code: https://pastebin.com/P03CB0FG
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.
do you have a specific problem?
you should probably remove the with statement and use client.db_conn instead since you already have it created
also don't forget to call await super().close() in your MyClient.close
hello
Why isnt this working?
just know that the .env is in the same directory and it has written in it "DISCORD_TOKEN = mybottoken"
do you have your environment variables loaded
i should ye
is there any set way to find other files with the same parent directory as main.py using the os package
import os
from dotenv import load_dotenv
do you call this method?
from dotenv import load_dotenv
from dotenv import dotenv_values
got these too
os.listdir()?
parent_dir = os.path.dirname(os.path.abspath(__file__)) may work
and then all_files = os.listdir(parent_dir)
import discord
from discord.ext import commands
from discord import app_commands
from main import get_server_data, set_server_data
class Setadmin(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(name="setadmin", description="Set the allowed roles to use moderation commands without any restrictions.")
@commands.has_permissions(administrator=True)
@app_commands.describe(name="roles",description='The admin role IDs.')
async def setadmin(self, interaction: discord.Interaction, roles: str):
guild = interaction.guild
admin_roles = [int(role.strip()) for role in roles.split(',')]
admin_n = [guild.get_role(role).name for role in admin_roles]
current_config = get_server_data(guild.id)
new_config = {
"admin_roles": admin_roles,
"confirm_roles": current_config.confirm_roles,
"confirm_channel": current_config.confirm_channel
}
set_server_data(guild.id, new_config)
await interaction.response.send_message(f'Admin roles have been updated to:\n {admin_n}', ephemeral=True)
print(f"Admin roles in {guild.name}({guild.id}) updated to: {admin_n}")
async def setup(client):
await client.add_cog(Setadmin(client))```
and
```py
@client.event
async def setup_hook():
print(f"Logged in as {client.user.name}")
for filename in os.listdir('./cmds'):
if filename.endswith('.py'):
print(f'cmds.{filename[:-3]} loaded')
await client.load_extension(f'cmds.{filename[:-3]}')
await client.tree.sync()
print('Extensions loaded successfully!')```
result in the error
https://paste.pythondiscord.com/rerutigafa
(I am not auto syncing all the time and I remove the sync line after I sync all of my new commands)
oh, yeah
and how you try to access the env varriable?
just TOKEN = os.getenv("DISCORD_TOKEN")
Seems like an internal issue
Try updating discord.py
do I use pip install --upgrade discord.py?
update
it should be yeah upgrade
or -U
yeah i use -U
dont import the main file in a cog
it's causing your bot to run twice
its supposed to be indexed
or add an ```py
if name == "main":
like how
nope
you can do it this way?
never seen this way
import os
os.environ["INDEXED"]
os.getenv("NOT-INDEXED")
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from 'fast-deps', 'truststore', 'no-binary-enable-wheel-cache')
wdym
from main import get_server_data, set_server_data
I am still confused
? it runs your main file again
even if you import a single function, whole file gets interpreted
just add the functions as botvars and use self.bot.function_name to acess them
?
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
like bot.test is being used here, you can attach the function as a variable bound to the bot
and then access it using self.bot.<the var> inside the cog
or just move the functions to some other file and import them
or this
that was for down :p
can you ref me to your original issue?
mk
I still dont quite get it can you give me some example related to my functions
til then
nvm all of that, just change your bot.run to ```py
if name == "main":
bot.run()
it should fix stuff
anyone here need help with anything? if so just ping me.
I just accidentally deleted pip
What
how do I reinstall it
Nice
reinstall python and select the pip option
how
just run python installer
it should install it
run the python installer and select uninstall
then run t again and press install
how do I do that through shell
@slate swan it was this one lol
I am using replit
Please don't use ableist language in this server.
Also, you're being unnecessarily rude, please read our #code-of-conduct .
stack overflow
๐
yes sir :(((
๐คฃ
bro uninstalled pip on replit 
its not my fault hes asking stupid questions when he doesnt know basic python why try programming something when u dont even know how to reinstall pip or create a new repl
people are wasting time on here instead of asking good legitimate questions
if you belive question is "stupid" no need to answer it
oh, make sure you did these
- the .env file should be in same dir as your main file
- the env should be in this format (usually)
TOKEN = "YOUR TOKEN"
- you should load the env using
python-dotenvlib before trying to access it ```py
import dotenv
dotenv.load_dotenv()
os.environ["TOKEN"]
#or
os.getenv("TOKEN")
if all these still don't work try setting the env on system level instead of env file and try
.load_dotenv() is important! Don't forget it
#discord-bots is not the best place to ask these questions, but these questions do belong to the server
alright ill be right back and let you know
He's trying to learn
bro hes asking how to reinstsall pip on repl
wtv dbi
just use poetry
replit's package management system is based on it
instead of pip install you'll be doing poetry add
k I reinstalled it through shell lol
i corrected the .env format file and thats that.
but what am i supposed to run on the client.run()
Then just don't answer( you don't have to do it)
you're supposed to pass os.getenv("DISCORD_TOKEN") into client.run()
uhhh where
well anywhere will be fine, let me see
also if you'd like to know what error i got it was TypeError: expected token to be a str, received NoneType instead
yeah it means the env file is not detected
do you have your project opened as folder in vs code?
aw man, it's there
how did you run the file btw?
on main.py i just clicked on vscode's run button
if you used that play button it might be the reason

alright then let's try like that
or whatever your python command is binded to (it could also be py or python3)
yeah
that's what i did
are you in the project's dir inside the vsc terminal
poetry add still does not work for installing discord
the package is called discord.py not discord
yes
weird error 
bro always me
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'truststore')
How am i gonna hide my bot's token on my github :waaa:
you could use a system environment variable but that will be like loaded in all your projects automatically
won't be exposed anywhere tho
.gitignore
I know man but i can't use a .env file
why not
cause it always gives an error
what does your full code look like
600+ lines
how does it looks like inside .env maybe your syntax is wrong
just paste it in https://paste.pythondiscord.com
@cinder tulip can you show the .env file structure with the token hidden ofc
remember to hide actual token
man i almost sent my token MAAN
File "/home/runner/Mod-Trainer/venv/bin/poetry", line 5, in <module>
from poetry.console import main
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/__init__.py", line 1, in <module>
from .application import Application
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/application.py", line 7, in <module>
from .commands.about import AboutCommand
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/commands/__init__.py", line 4, in <module>
from .check import CheckCommand
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/console/commands/check.py", line 2, in <module>
from poetry.factory import Factory
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/factory.py", line 18, in <module>
from .repositories.pypi_repository import PyPiRepository
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/poetry/repositories/pypi_repository.py", line 11, in <module>
from cachecontrol import CacheControl
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/__init__.py", line 13, in <module>
from .wrapper import CacheControl
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/wrapper.py", line 5, in <module>
from .adapter import CacheControlAdapter
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/adapter.py", line 11, in <module>
from .controller import CacheController, PERMANENT_REDIRECT_STATUSES
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/controller.py", line 17, in <module>
from .serialize import Serializer
File "/home/runner/Mod-Trainer/venv/lib/python3.10/site-packages/cachecontrol/serialize.py", line 10, in <module>
import msgpack
ModuleNotFoundError: No module named 'msgpack'```
results from poetry add
and the other error is from pip install discord.py
just like this
did you delete some files from your repl?
idk
try removing the space between =
just create a new repl then
ok let's see
can I duplicate this one
did you save the file tho
THERE'S NO WAY
it will copy same stuff including configs, you will get the same issue
ima fork it
BY REMOVING THE SPACES IT WORKED
no dont
Gg
oh
it works with spaces for me on linux but not on windows lol
I forked it btw and now pip is not installed again lol
I wanna thank you all for helping me with this issue
I just making a new replit
I migrated to a new repl and changed the end to py if __name__ == "__main__": client.run(token) and it still gets the error
do I still need to try botvars
@slate swan
whats the new error
what's your code
@app_commands.describe(name="roles",description='The admin role IDs.')
not how describe works
oh yeah
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
lol
I had that from so long ago
how did I miss that
I had it that way cuz someone told me to
lol no way that was the problem
I promise I knew that
@app_commands.describe(member = "The user to mute", reason = "The reason for the mute.")
async def mute(interaction: discord.Interaction, member: discord.Member, reason: str):
if admin_roles:
for role in interaction.user.roles:
if role.id in admin_roles:
if member.guild_permissions.administrator:
await interaction.response.send_message("You cannot mute an administrator.", ephemeral=True)
return
guild = interaction.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
await interaction.response.send_message("Mute was successfull", ephemeral=True)
if muteRole == None:
muteRole = await guild.create_role(name="Muted")
await interaction.user.send("No Muted role was found. One was created, and you may edit it to your liking.")
for channel in guild.channels:
await channel.set_permissions(muteRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(muteRole, reason=reason)
await member.send(f"You were muted by {interaction.user}.\n Reason: {reason}")
if confirm_channel:
await client.get_channel(int(confirm_channel)).send(f"**{interaction.user}** muted **{member}**. \n Reason: **{reason}**")
return
await interaction.response.send_message("You are not allowed to use this command.", ephemeral=True)
else:
await interaction.response.send_message("Admin roles have not been set. Please set atleast one before using any moderation commands.", ephemeral=True)
print("Moderation command was attempted before admin roles were set.")```
I have a separate question
"1111111111": {
"admin_roles": [],
"confirm_roles": [],
"confirm_channel": ""
},
"2222222222": {
"admin_roles": [],
"confirm_roles": [],
"confirm_channel": ""
},
"1081731158099894293": {
"admin_roles": [],
"confirm_roles": [],
"confirm_channel": ""
}
}``` I have a json for storing server data that looks like this
I also have a function for getting the whole batch of data from one section
using that function, how would I be able to get one specific property such as "confirm_channel"
@slate swan
someone create a discord.py bingo with "replit" and "json storage" on it
data["1081731158099894293"]["confirm_channel"]?
ok
YES IT WORKS
also
is there a way to ask for an input type that is a channel
and one that is a role
with slash commands?
ye
annotate parameter as Role
just annotate the argument as discord.TextChannel or discord.Role
or whatever you want
ok
how can I make it so you can input multiple roles
like as many as you want separated by commas
i dont think you can
oh ok
maybe use a roleselect instead
how does that work
like any other select menu
you just make a view class and put the role select decorator inside
ok
I think for now I will keep it as a string where you just enter the roles separated by commas
How can I subtract the first three and last two characters from a variable
You are not allowed to use that command here. Please use the #bot-commands channel instead.
it would be [3:][:-2]
Slicing is a way of accessing a part of a sequence by specifying a start, stop, and step. As with normal indexing, negative numbers can be used to count backwards.
Examples
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:] # from element 2 to the end
['c', 'd', 'e', 'f', 'g']
>>> letters[:4] # up to element 4
['a', 'b', 'c', 'd']
>>> letters[3:5] # elements 3 and 4 -- the right bound is not included
['d', 'e']
>>> letters[2:-1:2] # Every other element between 2 and the last
['c', 'e']
>>> letters[::-1] # The whole list in reverse
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> words = "Hello world!"
>>> words[2:7] # Strings are also sequences
"llo w"
how would I be able to do that to the "role" value in admin_roles = [int(role.strip()) for role in roles.split(',')]
oh slicing not splicing
yep slicing
i don't know why i thought it was named splicing
@smoky sinew ?
wdym
the "role" value has two unnecesary charaters at the start and end
why
cuz I changed it to mentioning the role instead of inputting the role id
why not just use role select though
just put role.strip()[3:][:-1]
are you sure it's 2 characters at the end
one
ok
k I got it working
also I just found you can do role.strip()[3:-1]
and it does the same thing
yeah
ty for your help
How might I go about creating a /give [card name] @[target] command for my bot? Here's the current code: https://pastebin.com/dtQn1C4p
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.
Nothing I've tried has worked
I'm using aiosqlite to manage the db
did you see what i sent above?
i already responded
Wdym?
remove all the async with parts in your code and reuse client.db_conn instead
Ok




How might I go about making the /pack commands able to put duplicates in the user's inventory? I got it working for /add, but it won't work for /pack1, /pack2, or /pack3.
/pack2:
@client.tree.command()
async def pack2(interaction: discord.Interaction):
"""Adds three random cards to the user's inventory"""
async with aiosqlite.connect('card_inventory.db') as db_conn:
cards = random.sample(cardList, 3)
for card in cards:
cursor = await db_conn.execute('SELECT * FROM inventory WHERE user_id = ? AND card_name = ?',
(interaction.user.id, card))
row = await cursor.fetchone()
if row is None:
await db_conn.execute('INSERT INTO inventory (user_id, card_name) VALUES (?, ?)',
(interaction.user.id, card))
await db_conn.commit()
card_names_str = "\n".join(cards)
embed = discord.Embed(title=f"You got a pack of cards!",
description=f"Added the following cards to your inventory:\n{card_names_str}",
color=0x00ff00)
await interaction.response.send_message(embed=embed)```
/add: ```py
@client.tree.command()
async def add(interaction: discord.Interaction, cardname: str, recipient: discord.Member):
"""Adds a card to a user's inventory"""
# permissions
allowed_roles = ["VBA | High Staff Team", "VBA | Developer Team"]
if not any(role.name in allowed_roles for role in interaction.user.roles):
await interaction.response.send_message("You are not authorized to use this command!")
return
# checks if card exists
cardname = cardname.capitalize()
if cardname not in cardList:
await interaction.response.send_message(f"Error: '{cardname}' is not a valid card!")
return
async with aiosqlite.connect('card_inventory.db') as db_conn:
# insert card into db
await db_conn.execute('INSERT INTO inventory (user_id, card_name) VALUES (?, ?)', (recipient.id, cardname))
await db_conn.commit()
# calls the proper file
file_path = cardFiles[cardname]
file = discord.File(file_path, filename=f"{cardname.lower()}.jpg")
# response to user
embed = discord.Embed(title=f"{cardname} added",
description=f"Added card '{cardname}' to {recipient.mention}'s inventory!", color=0x00ff00)
embed.set_image(url="attachment://card_image.jpg")
await interaction.response.send_message(embed=embed, file=file)```
The role is not given by the reaction of the person who wrote the messages
@client.event
async def on_raw_reaction_add(payload):
# Check that the reaction was added in the "report-increase" channel
if payload.channel_id == YOUR_CHANNEL_ID:
# Get the message to which the reaction was added
message = await client.get_channel(payload.channel_id).fetch_message(payload.message_id)
# Get the user who wrote this message
user = message.author
# Get the server on which the event occurred
guild = client.get_guild(payload.guild_id)
# Get the "member" role
role = discord.utils.get(guild.roles, name="member")
# Get the server member object
member = guild.get_member(user.id)
# Add the "member" role to the member who wrote the message
await member.add_roles(role)
There are no errors in the console
Also visited the other option did not work
async def on_reaction_add(reaction, user):
channel_id_otchet = client.get_channel(1084181490730025052)
role_id_otchet = discord.utils.get(reaction.guild.roles, name="member")
if reaction.message.channel.id == channel_id_otchet:
guild = await client.fetch_guild(user.guild.id)
member = await guild.fetch_member(user.id)
author = reaction.message.author
print('#1')
if author.id != user.id:
if discord.utils.get(member.roles, id=role_id_otchet) is None:
role = guild.get_role(role_id_otchet)
await author.add_roles(role)
print('on_reaction_add WORKED!')
Pls Help
Using a phone is cursed, Jesus fuck. Iโll try to read this
Just wondering, did you copy and paste this code? Because thatโs an awfully suspicious amount of comments.
Not that itโs anything bad, but you should understand the code before you paste it (I totally do that every time)
Please elaborate, my brain isnโt braining. Too much code, not enough explanation. I can read it, but I canโt read it, if you get what I mean.
Ik what you mean
So basically
/pack1 gives a user one random card, /pack2 gives 3, and /pack3 gives 5
/add directly adds a card to a user's inventory (Can only be done by an admin ofc)
I was able to get /add to allow for duplicates
So for example, If I were to do "/add jhett @flint heart" twice, when i did /inventory, both would be there
How to get bot id in application command
However, let's say I do /pack2 and get Jhett, Paris, and Radiant
It should be in the discord dev portal. Take a closer look. I may be mistaken itโs been a while since Iโve used it
I know my code. You can help me?
If I do it again, lets say I get Pup, Jhett, and Jant
If I did /inventory, there would only be Jhett, Paris, Radiant, Pup, and Jant
Even though there should be 2 jhetts
I mean the bot id at the server lol
Fuck
The guild id?
The Bot is! Like the User id
Ok so you want to allow duplicates, correct?
Then copy ID at the bottom
Haha lol
Yea
Inside of the discord server it's in
You need developer mode activated too
I want to get in in the command ๐คฆโโ๏ธ
Oh yea
So like /id?
Then it tells the user its ID?
You are lost?
My brain has deteriorated extremely terribly. You want to get the bot ID through a command, correct?
Iโll try.
Yes
That's exactly what I just said...
try this:
Ohhhhh
The ID of the user?
Holy shit I HATE USING A PHONE
Not the user id uff
@bot.tree.command()
async def id(interaction: discord.Interaction) -> None:
await interaction.response.send_message(bot.user.id)
Just pass the argument as the bot and it should still work
For noobs client id that is what i want lol
I really need to re educate myself with this
id = "[id of your bot]"
@client.tree.command()
async def id_finder(interaction: discord.Interaction):
await interaction.response.send_message(f"My ID is {id}")```
Sorry but u are Completely lost
Learning basics
Yeah ik but now in a cog and slash command
Dawg nobody here gets what you're asking for
I thought it is interaction.client.id but it isnt @velvet tinsel
no..
what if the bot id changes
True, true
Wait, is discord.py being continued?
because interaction.client is a Client object, not a User object
Nextcord
you probably meant interaction.client.application_id @white citrus
So but u know what i mean?
yes, for a while now
Ahh thanks i try
Oh. Iโve used those libs but itโs been months since Iโve used it. I used to be of help, but unfortunately, Iโve kind of forgotten some prime basics. Iโll just go and re-learn this stuff.
Got a quick question guys. So basically I wrote a code that checks for changes on a website and if it changes the bot sends a dm to a person. But how can I stop this loop with another slash command and so the loop is always up to date with the stop slash command. Basically i wanna stop a loop with a command but I donโt know how. Btw I am using interactions obv
what are you using to run that loop? @tasks.loop?
No, I use while
Since I only loop the Selenium code and not the task
mh? a bare while loop would block your code so you're running it in some way, are you using an asyncio task?
Yes asyncio
then you can cancel the task if you somehow have access to the task object
this won't be difficult, you just need a dict with ids as keys and tasks as values
Mhmmmmm will try tomorrow I was just curious since the asyncio tasks just loops without actually checking for another command
But I think I know how to solve it will check tomorrow
Thx for your help bro โค๏ธ
you're welcome
I don't know whether or not to put this in here but I will, I'm using a webhook to connect multiple roblox profiles to a server for example (If they join a game their instanceID gets sent to my server) but it's having strange errors which say "Error retrieving JoinInstanceID for Roblox ID: 76773338" I'll leave the code below help me if you can.
import json
profiles = [76773338]
roblox_api_endpoint = "https://api.roblox.com/users/{}/currently-playing"
# WEBHOOK HERE
discord_webhook_url = "MY WEBHOOK"
for profile_id in profiles:
response = requests.get(roblox_api_endpoint.format(profile_id))
if response.status_code == 200:
join_instance_id = response.json()["JoinInstanceID"]
else:
print("Error retrieving JoinInstanceID for profile ID: {}".format(profile_id))
continue
payload = {
"username": "Roblox Profiles",
"content": "JoinInstanceID for profile ID {}: {}".format(profile_id, join_instance_id)
}
response = requests.post(discord_webhook_url, data=json.dumps(payload), headers={"Content-Type": "application/json"})
if response.status_code != 204:
print("Error sending webhook for profile ID: {}".format(profile_id))```
what does this bot do?
Remove the if/else that checks for the status code and use response.raise_for_status() to get a better error message
I'm back again! This time, I'm trying to add a money system, and was wondering what the best approach would be. Rn, I'm thinking the only two choices would to make a new db, or add a section to my current db. Note that I'm new to managing databases, so preferably whichever would be easier. Not sure if it means anything, but the money would be used to buy packs (/pack1, /pack2, and /pack3). Here's my code: https://pastebin.com/Awgqhthp
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.
And sorry for the super inconsistent commenting, I've been trying to do better with them
just add a new table
that's what tables are for
why do you do self.db_conn = ... if you don't use it anyways @flint heart
How would I properly implement it?
I was recommended I use it, but I don't remember from where
I was reccomended it from someone in The Coding Den discord server (I think)
just remove all the with statements and replace db_conn with client.db_conn
Ok
hey I'm using openai api in my bot . Is it free to use ?
Yea
But there's a limit to how many queries you can have
Not sure the exact amount
I just want to make a chatbot just random talks
Im looking up how many you can have rn
ok thanks
Yea I can't find it
Ryoku
-s give me the link where I can buy openai api tokens
BOT
Openai does not sell api tokens.
see
Hello, i'm working on the Flask framework to build an http discord bot, everything working fine until i needed to upload file. Can someone explains me (or send me a guide) how to return a multipart form with Flask. Until now, I only returned json / dict to each interaction. I read the discord documentation but I didn't find it useful
thank you !
the #965291516031549500 thread would probably be more relevant
oh if its only about returning a multipart response then web dev is fine
u need to make an api token iirc u have like 18$ in ur account once u create it or something
ok ok
today i bought a new chair and im so happy ๐
How do I make my discordbot automatically reconnect to any buttons/interactions?
For example, in this image, if my bot goes offline, lets say due to internet outage or coz my cat eats my internet box, and I bring my bot online. Currently it doesnt recognize those buttons.
Today*
I*
I'm*
yup, a bot token to make the requests would be sufficient and then it would go through interactions endpoint / gateway as usual
in discord.py that would be known as a persistent view, and to simply describe it you use Client.add_view() with a correctly configured View instance to have dpy recognize interactions for it
example: https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
@hushed galleon i sent you the friend request
why? (i dont normally accept frs)
fr
fr man
Yeah that's what I thought about too
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.checks.bot_has_permissions(manage_guild=True)
@app_commands.describe(gI="Guild ID", wI="Welcome channel ID", bI="Bye Channel ID")
async def setup(interaction: discord.Interaction, gI: discord.Guild, wI: int, bI: int):
client.wlcm = wI
client.bye = bI
client.guildID = gI
info = {"sName": client.guildID.id, "wChannel": client.wlcm, "bChannel": client.bye}
client.col.insert_one(info)
await interaction.response.send_message(
f"Guild ID: {client.guildID.id}\nWelcome channel ID: {client.wlcm}\nBye channel ID: {client.bye}",
epeheral=True)
await interaction.followup.send("Setup Done", epeheral=True)```
code
File "/home/iam/Documents/Python Files/Discord Bot/MrWelcome/main.py", line 39, in <module>
@app_commands.command(name="mrsetup", description="Setups the guild for welcome and bye features.")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 2002, in decorator
return Command(
^^^^^^^^
File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 665, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 373, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 834, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/iam/.local/lib/python3.11/site-packages/discord/app_commands/transformers.py", line 793, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.guild.Guild'>
error
please help
im using mongodb to store the data
my command worked earlier but now i was shifting to slash command and got this error
Discord doesn't have support for guild selection
huh??
It's not a valid parameter type
but earlier it worked
Yeah works fine for prefix commands, since they're more flexible
oh so what should i do now
You will have to go for a workaround like having the user enter in the guild ID
i didnt get what u just said
You'd just accept an int which will be the guild ID
reply = f'this user is afk'
if not message.author.bot:
for user in message.mentions:
if user.id == my_id:
await message.channel.send(reply, reference=message)
how can i add cooldown for the reply?
like 123
You will have to parse that yourself
howw!!??
guild = bot.get_guild(user_input)
if guild:
# guild exists! use it
else:
# guild doesn't exist!
Logs = await ctx.guild.audit_logs(limit=limit).flatten()
How do I flatten this because .flatten() isnโt working
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guildโs audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
Read the docs
u have to unpack it asynchronously
bc i like you
In a weird way, orโฆ 
how to see the number of all member in the servers in which the bot is
anyone please tell this
im really confused
!d discord.Client.guilds
property guilds```
The guilds that the connected client is a member of.
it returns a list, so you can just run len(bot.guilds)
Probally this
async def membercount(ctx):
await ctx.send(len(guild.member_count))```
he asked for this
use from snipy
it's just an attribute, you can access it everywhere you have Bot object access
it's just that
technically it's a property
wdym? why should the Bot be banned
well thats the point of the discord bot to create commands that everyone can use
depends what the command is supposed to do
its supposed to send dms to all server members?
well if the discord server is 10 members then its fine but for bigger servers it will be spamming and could get you banned yes
hey snipy
import discord
from discord.ext import commands
import mysql.connector
import datetime
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = "-", intents = intents)
@bot.event
async def on_ready():
print(f"Bot is ready. Logged in as {bot.user}")
print("-------------------------------------")
@bot.command()
async def test(ctx):
print("Test command received")
await ctx.send('Testing, testing, 1, 2, 3...')
print("Test command received")
bot.run("Troll")```
Guys why this not working :(
hey
are you getting an error?
it returns a BIGGGGGGGG list
no errors at all. the command outright ain't responding when i use in server
yeah you need to call len() on it
but i need the sum of number of members in each server
property users```
Returns a list of all the users the bot can see.
ohhh
btw is there anything wrong with my code
client.user
do you have an on_message event somewhere?
nope
users*
ah maybe you don't have the message_content intent enabled
wait
you need to activate it both on your code and on the discord developer portal
THANKS A LOT SNIPY
ok but discord.Intents.default() classmethod have message_content set to False
you're welcome
so you need to do
intents.message_content = True
thanks yo
TypeError: __init__() missing 1 required keyword-only argument: 'intents' how can I fix this
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.
!main
Hi, I'm very much a noob at coding in general, but I am learning. What I am doing now is trying to make a custom bot for my 2 discord servers. I want the bot to send a different embed depending on what server is joined. The embed will mention different channels in the respective servers. This is the code I have so far:
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="h", intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
print("-------------")
@bot.event
async def on_member_join(member):
if member.guild.id == "1051109766002376805":
austin_channel = bot.get_channel(1051112385869521048)
austin_welcome_embed = discord.Embed(title="Welcome!" , description=" Read the rules\n  Grab some roles\n  Boost our server\n  Have fun!", color=0xCCCCCC )
austin_welcome_embed.set_image(url="https://cdn.discordapp.com/attachments/1044880051654635572/1044911108617678908/Welcome.gif")
print(f"{member.name} has joined the Austin server.")
await austin_channel.send(f"<@&1084444679921213520> {member.mention}")
await austin_channel.send(embed=austin_welcome_embed)
elif member.guild.id == "1052302588688748544":
central_channel = bot.get_channel(1052307098303741952)
central_welcome_embed = discord.Embed(title="Welcome", description=f"This is the official staffing server for **Malevolent** and **Sundown**, please find the respective categories of both servers to either appeal or apply for different positions within the servers. If you need any help, ping the <@&1052302821220942015> role")
print(f"{member.name} has joined the Central server.")
await central_channel.send(f"{member.mention}")
await central_channel.send(embed=central_welcome_embed)
bot.run("token will go here lol")```
The problem is that I don't get any messages sent at all - even the print output in the terminal. Any ideas? All help will be greatly appreciate 
why is 1/2 rounded 0?
same here
The bot sleeps and when someone interacts with the bottons it doesn't respond
So i want to autoban members with names matching using wildcard but i want to ban multiple banned names even tho i attempted to make it errors came into the way here's the code (only bans one name with wildcard on)
banned_name_pattern = r"Banned_name"
@bot.event
async def on_member_join(member):
# Check if the username matches the banned name pattern
if re.match(banned_name_pattern, member.name):
# Ban the user
await member.ban(reason="Banned name")
else:
# Send a welcome message
channel = member.guild.system_channel
if channel is not None:
await channel.send(f"Welcome to the server, {member.mention}!")
**```python
1>>@bot.tree.command(name="lock",description="locks the channel which you send the message on")
2>>@app_commands.checks.has_permissions(manage_channels=True)
3>>async def lock(interaction: discord.Interaction):
4>> await interaction.response.send_message("`lock")
how to check if the author of message has perm other than line 2 ?**
hey all, I want to make a sound dispatch command somewhat similar to Airhorn Solutions... This is what I made but I am having an error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'VoiceChannel' object has no attribute 'play'
Code:
@discord.slash_command(name='quack', description = 'Quack, Quack, Quack!')
async def quack(self, ctx):
vc = ctx.author.voice.channel
if vc == None:
ctx.respond("You must be connected to a voice channel!")
else:
vc.connect()
vc.play(discord.File('duck-quacking-37392.mp3'))
where am I going wrong?
-
the
connectmethod of aVoiceChannelobject is a coroutine, this mean that you need to await it -
you need to store the
VoiceClientreturned by theVoiceChannel.connectmethod; later you'll use thatVoiceClientobject to call theplaymethod
- the
VoiceClient.playmethod doesn't accept adiscord.Fileobject, you need to pass a source
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Changed in version 2.0: Instead of writing to `sys.stderr`, the libraryโs logger is used.
ctx.respond needs to be awaited as well
i am working on a discord economy bot. so like, how do i create an inventory function?
imo there are two ways to go about it. one is creating a separate table for every user (very tedious for me to categorise or something idek)
the second option idk if there is a second option honestly
you can make a single 'users' table that can store the IDs of every user and the items they have
oh and what database are you using
using a relational database every user could have associated to their ID a profile where they have an inventory and other things, you can imagine the inventory as a list that contains the objects that a user has
sorry I hadn't see this before
mysql
You explained it better than I did
Operation failed: There was an error while applying the SQL script to the database.
Executing:
CREATE TABLE bank.inventory (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
);
ERROR 1146: Table 'bank.inventory' doesn't exist
SQL Statement:
CREATE TABLE bank.inventory (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
)
That should work then
!code-block
Executing:
CREATE TABLE `bank`.`inventory` (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
);
ERROR 1146: Table 'bank.inventory' doesn't exist
SQL Statement:
CREATE TABLE `bank`.`inventory` (
id BIGINT UNSIGNED NOT NULL,
item_name VARCHAR(255) NOT NULL,
description VARCHAR(255),
price INT,
quantity INT NOT NULL,
PRIMARY KEY (id, item_name),
FOREIGN KEY (id) REFERENCES users(id),
CONSTRAINT max_items CHECK (id IN (SELECT id FROM inventory GROUP BY id HAVING COUNT(*) <= 20))
)```
btw this is off topic for this channel, you should head to #databases
Yeah it's a little in active but you'll probably get a better answer there
How do I make a link button
ok
bank.inventory is syntax for selecting a field from a table like table.field whats ur intent here
make a user table and have an inventory column
pgsql has a jsonb data type
perfect for an inventory

well,how'd i go on about it ๐ญ
wait lemme order my dinner I'll tell u
CREATE TABLE IF NOT EXISTS users (
user_id BIGINT PRIMARY KEY,
inventory JSONB,
money INT DEFAULT 0,
);
an example u can expand fields however u want
I can't figure out how to check if specified channel is in the same server as the command I used.
Like here's code and I want it to deny if channel id is from another server
async def setlogchannel(self, context: Context, channel_id): server_id = context.guild.id try: await self.bot.fetch_channel(channel_id) id = await db_manager.add_log_channel(channel_id, server_id) embed = discord.Embed(description=f"ะะฐะฝะฐะป ะดะปั ะธััะพัะธะธ ัะพะพะฑัะตะฝะธะน ัััะฐะฝะพะฒะปะตะฝ ะฝะฐ <#{id}>", color=0x9C84EF) await context.send(embed=embed) except: embed = discord.Embed(description=f"ะขะฐะบะพะณะพ ะบะฐะฝะฐะปะฐ ะฝะต ัััะตััะฒัะตั ะธะปะธ ั ะผะตะฝั ะฝะตั ะดะพัััะฟะฐ ะบ ะบะฐะฝะฐะปั.", color=0x9C84EF) await context.send(embed=embed)
hey! I'm having issues trying to do pip install discord.py
(Mac Version 10.13.6)
Says bash: pip: command not found
does using py works?
you mean the files etc?
just using py on the console
it should open python
because if that works you can use py -m pip install discord.py
looks like it doesn't work..
did you install python?
yes
ill try to reinstall python if it doesn't work
๐
looks like that worked
great
Toto do you know asnwer for my question?
need someone to make a fortniite discord bot w me i have no experience with post requests and stuff
!e
enemy_points = [1969, 1318, 1971, 1860, 2044, 2381, 1498, 3421, 1146, 1690, 2186, 1368, 1819, 1515, 2270, 2001, 1211]
med = sum(enemy_points) / len(enemy_points)
print(round(med))```
@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.
1863
Please use #bot-commands if it's not related to a conversation

You could use Guild.get_channel or Guild.fetch_channel
is it better to list the event listener once and have multiple guard clauses for functions or to have an event listener for each function?
someone can help me ? Contact me privately
can you explain again
so is it better to repeat each listener for the function. lets say..
async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Variable" is in after.channel.name:
#Do Something
async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Different Variable" is in after.channel.name:
#Do Something Else
or would it be better to do something like..
async def on_voice_state_update(self, member, before, after)
if after.channel is not None and "Variable" is in after.channel.name:
return False
#Do Something
return True
elif "Different Variable" is in after.channel.name:
return False
#Do Something Else
return True
the top one is not. i have them in a different file for each for dev testing.
overwritten?
ohhh cause its in chronological order
i got a weird warning. since i left it running for a couple days and wasn't sure if its because of this being in different files or something else
WARNING - discord.gateway : Can't keep up, shard ID None websocket is 25.7s behind.
so that's why i was questioning optimizations
It may happen when using synchronous modules
so convert synchronous to asynchronous ?
Yes just use async ones for example
dont use requests
use aiohttp instead
ohhhh ok. so some of the packages could be running synchronous modules as well....
Hi, is there a way to raise an exception without printing it to console?
I have an error handler, but my errors are getting printed before error handler is called
https://stackoverflow.com/questions/66374121/discord-py-error-handling-with-on-command-error check this out!
I need help with the error handling in discord.py. I want to send the server owner a private message if my bot doesn't have enough rights for a command or if my bots fail something (reason not enough
or just an example
yes, this is pretty much how i did it.
but it is still printing error to console
show me the code
we cannot help with boost bots here
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
issue isnt with error handler
like i said, exception is getting printed before going to error handler. so clearly it's not looking into the error handler first before printing
error handler still works as expected though.
i am using async def on_application_command_error(self, interaction:Interaction, error): instead though
oh
because on_command_error wasn't working
well... try @example.error and see if it works instead
how do u mean
one of my commands is
@nextcord.slash_command()
@cooldowns.cooldown(1, 5400, bucket=cooldowns.SlashBucket.author)
async def work(self, interaction:Interaction):
@example.error
async def example_error(self, ctx, error):
if isinstance(error, commands.WhateverYouWant):
await ctx.send("Error!")
something like this I suspect
Whatโs the problem
o i have my error handler as
@commands.Cog.listener()
async def on_application_command_error(self, interaction:Interaction, error):
error = getattr(error, 'original', error)
elif isinstance(error, commands.CommandOnCooldown) or isinstance(error, CallableOnCooldown):
Stuff1()
elif isinstance(error, commands.CheckFailure):
Stuff2()
elif isinstance(error, commands.BadArgument):
Stufff3()
oh
Are you getting errors currently?
well, I'm very good at taking the worst and longest way possible, so I say...
make one for every single thing ๐
Where is the if i only see elif s
im trying to not have the exceptions get printed to console
once again, zero errors.
the code edited
ok ye I'll just ๐ช ๐ถโโ๏ธ
The error is printed cause it wasnt caught in the handler i suppose
no, again, error is printed before looking at error handler
Hm
Can you send me the trace back
let me get example
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f1ea79257f0>:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "/home/ubuntu/economy-bot/cogs/bj.py", line 49, in blackjack
player_hand, player_num, embed = await self.player_turn(dFirstHand, dFirstNum, interaction)
File "/home/ubuntu/economy-bot/cogs/bj.py", line 151, in player_turn
raise Exception("timeoutError")
Exception: timeoutError
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: Exception: timeoutError
START OF ERROR HANDLER
So I know what the problem is
that's one
You added some prints i belive so you know that
wot
but deleting error handler will 100% guarantee a print to the console
And then send the full trace back
Why isn't icon_url not working
Donโt send screenshots
send code formatted messages along with the error
Cause add_field does not accept any icons
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
let's do this one instead:
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7ffb273a8280>:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown.py", line 104, in inner
async with _cooldown(*args, **kwargs):
File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown.py", line 249, in __aenter__
async with bucket:
File "/home/ubuntu/.local/lib/python3.9/site-packages/cooldowns/cooldown_times_per.py", line 50, in __aenter__
raise CallableOnCooldown(
cooldowns.exceptions.CallableOnCooldown: This function is being rate-limited. Please try again in 5398.027218 seconds.
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: CallableOnCooldown: This function is being rate-limited. Please try again in 5398.027218 seconds.
Mmmk
That is the problem
You are being rare limited by discord because you are sending way too many requests
Wait nvm
Its cause there is an cooldown on a command
correct
Remove the cooldown
Oh I just realized, this is the solution:
set_author(icon_url="url_of_the_image")
๐
then the error will go away lmao
cuz there wont be an issue
Exactly

Problem solved
Do you handle CallableOnCooldown in handler?
yes
"this function is being ratelimited, please try again in 5398 seconds"
but 3rd time, it is printed before it looks at the exception handler
i have a /work command.
don't want users using it every second, so hence, cooldown.
I have the if isinstance(error, CallableOnCooldown):
and it is handled correctly, tells user it is on cooldown.
but error still printed to console
damn, and now im late for work lol
thanks for trying y'all. but troll answers like this... lmao 
When you have time you should Ask at nextcord support server
The contributors should know what is causing this
tru, 'ppreciate that
You are trying to get errors?
The advice u give is similar to telling someone โdelete your entire code and run the program. You wonโt see any errors. Youโre welcomeโ
I donโt have enough context bro
The cooldown is the direct cause of the error
Are you trying to send the user a message when they canโt use the command because of the cooldown?
๐คฆ
Some commands should have cooldown so user can spam use it
(Or user can use it x times every y )
@blazing flint ^^
Issue isnโt that I didnโt give context, issue is u donโt read every message I send lol
You literally just said exactly what I said here lol
are you still making cogs for each command
why you're making it so much harder for yourself
i thought u said u werent doing that anymore
no im not
lol this is just temporary so it is easier to find errors while I am converting my commands to cogs
you know errors tell you the exact line and traceback right
putting everything in a separate file does not help you
Wondering how pseudo implementation helps catch Bugs in actual implementation
do you guys also get this or is it me?
(the commands does not work so it might have smt to do with it)
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
you have to enable the message content intent
all the intents is enabled
show your code
If you dont use prefixed commands or you dont need message contents its fine
they are though
for most bots, something like intents = discord.Intents.default() intents.members = True intents.message_content = True should work
or just intents = discord.Intents.all() if you have a multi-purpose bot
and even discord.Intents.default() is somewhat bad, because you don't need most of them anyway, (such as typing)
looks like it working now....
it works fine for me
it responds so
ok
lol I am for sure saving that to my computer
wait you use lunar client?
lmao
I hate that turtle
is this ugly green potato that climbed out of a toilet bowl even a turtle?
๐ญ
hi can someone help me my command is only returning the message if i reply to the original message otherwise it returns an empty string
@commands.hybrid_command(
name="trivia",
description="Get a trivia question on pokemon",
)
async def trivia(self, context: Context):
try:
with open(self.path, "r") as f:
data = json.load(f)
question = data[str(random.randint(1, 100))][str(random.randint(1, 20))]
if type(question[1]) == list:
print(True)
question[1] = ' '.join(question[1])
await context.send(f'{question[0]} {question[1]}')
def check(message: discord.Message):
return message.author.id == context.author.id and message.channel.id == context.channel.id
user_response = await self.bot.wait_for('message', check=check)
print(user_response.content.strip())
if user_response.content.lower() == question[1].lower():
await context.send("Correct!")
else:
await context.send(f"Sorry, the correct answer was {question[1]}")
except Exception as e:
print(e)
Do you have message content intents enabled?
that sadly was the issue i forgot to enable it, thanks
what about for running the bot?
all i do is:
def run():
bot.run(settings.DISCORD_API_TOKEN, root_logger=True)
run()
would that cause it too?
not exactly
bot.run does block so nothing after it will run
how can i make the autocomplete input optional?
so running the bot like this wouldn't be the culprit for this?
WARNING - discord.gateway : Can't keep up, shard ID None websocket is 25.7s behind.
Probably not
it's because of some blocking process
How might I go about allowing a user to have multiple of the same card? I got it working for the /add command, but I can't figure out how to do it for the /pack commands. Could anyone point me in the right direction? I've been stuck on this problem for awhile now. https://pastebin.com/6XWdXefA
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.
how do you write a discord.ext extension? are they the same concept as bot extensions?
or do they just use the same name?
Like commands?
Or other extensions
i don't even know tbh
discord.ext.commands is just a module but it's confusing that it uses the term "extension"
because you don't use bot.load_extension on it
So thereโs tasks and commands. You just put them in a class and use the decorator
in discord.py extensions are just files which can be loaded
# extension.py
async def setup(bot):
print("Loaded the extension!")
# main.py
await bot.load_extension("extension")
@tasks.loop(seconds=60)
@commands.command(name='hello')
i just make a for loop to load the extensions from every folder. in each py file i have a function at the end
class TestCog(commands.Cog):
def __init__(self, bot):
@tasks.loop(seconds=60)
#function
@commands.command(name='hello')
#function
async def setup(bot):
await bot.add_cog(TestCog(bot))
why would you do that...
reloading extensions every minute??
and the task is in an extension too
i know how extensions work
i've already said that
they are not related to extension files, no
but if you wanna create one you'll just have to create a new package with this tree ```
- discord
- ext
- your_package
- init.py
- your_package
- ext
i see
basically an empty discord/ext folder is needed
if you're wondering, discord.ext is more specifically known as a namespace package, where sub-packages can come from different distributions / locations on sys.path
spec: https://peps.python.org/pep-0420/
guide: https://packaging.python.org/en/latest/guides/packaging-namespace-packages/
danny's other discord.ext distribution: https://github.com/Rapptz/discord-ext-menus
interesting, i didn't know that had a name
and yeah discord.ext.menus was where i got the question from
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
data = await self.bot.db.fetchval('SELECT voice FROM voicemaster WHERE guild_id = $1', member.guild.id)
if data:
if after.channel.id and after.channel.id == data:
channel = await member.guild.create_voice_channel(name=f"{member.name}'s channel",
user_limit=0,
category=after.channel.category)
await member.move_to(channel)
await self.bot.db.execute('INSERT INTO voicemaster_data (voice, guild, owner) VALUES ($1, $2, $3)',
channel.id, channel.guild.id, member.id)
else:
data = await self.bot.db.fetch('SELECT * FROM voicemaster_data WHERE voice = $1', before.channel.id)
if data:
voice=before.channel.guild.get_channel(data)
if voice:
if len(voice.members) == 0:
await voice.delete()
await self.bot.db.execute('DELETE FROM voicemaster_data WHERE voice = $1', before.channel.id)
I'm trying to make it so that if the voice channel is empty it deletes it (it does properly create it and puts it into the database, just can't seem to make it delete it if there are no members in the voice channel)
No errors in console.
do you know if it gets to the if voice: part?
is there a short way of adding a guild_only check to a cog
or do i have to implement cog_check
just don't create the command in dms?
you can set dm_permissions to False
what does that mean
wait can slash commands even have checks
nvm i'm stupid
it just doesn't create the command in dms...
๐ข istg discord.py
i want it per-cog though
i'm making a tag cog and there is no command that can be used in dms since tags are specific to a guild
you can do ```py
for command in commands_in_that_cog:
app_commands.guild_only()(command)
i mean they could have just allowed a dm_permission argument in the @command decorator
they don't even add it as an attribute for Command object ( atleast not documented)
you can do command.guild_only = True instead
https://github.com/Rapptz/discord.py/blob/master/discord/app_commands/commands.py#L2447
discord/app_commands/commands.py line 2447
f.guild_only = True```
can't i just do something like
async def cog_check(self, ...):
return await commands.check(app_commands.guild_only(...))
that probably does not make sense
if your tag commands are all encompassed under one command group (or using GroupCog), you only need to apply the guild_only() decorator to that group
yeah i was about to say that lol
guild_only is not a check but simply a decorator that sets attributes, so this won't work
i see
oh yeah i forgot about the last time i tried migrating tags to slash commands, iirc it was infinitely worse at handling formatting
are there any examples of app_commands.Group
modals didnt give you the same syntax preview / autocomplete, and you cant write multi-line tags for a single command parameter
check Ash's gist ( in the pins)
funny that they dont have one in the repo, but there's like three different ways to make groups
oh yeah hmm
they should add a TextStyle.markdown tbh
wait, @app_commands.group() and tree.group() dont exist?
i think it's only a class
they don't ๐
maybe wait_for("message") could work
ah its still 3 options, creating Group, inheriting Group, or inheriting GroupCog
what's GroupCog
!d discord.ext.commands.GroupCog
class discord.ext.commands.GroupCog(*args, **kwargs)```
Represents a cog that also doubles as a parent [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") for the application commands defined within it.
This inherits from [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") and the options in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") also apply to this. See the [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") documentation for methods.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of the cog.
Hybrid commands will also be added to the Group, giving the ability to categorize slash commands into groups, while keeping the prefix-style command as a root-level command.
For example...
app_commands API feels very different than commands extension ๐
it is
if you have a bot user and access to message_content sure, but it kind of demonstrates the limitations of slash commands
oh shit what if you used a message context menu instead? that might work better
from discord import app_commands
from discord.ext import commands
@app_commands.guild_only()
class MyCog(commands.GroupCog, group_name='my-cog'):
pass
``` yeah~
yeah obviously it would work better because it's a message command you can literally make it work any way you like by not forcing yourself to use discord's horrible api
nah not prefix commands, message commands
what's the difference
as if the confusion wasnt enough
https://discord.com/developers/docs/interactions/application-commands#message-commands
how would you get the tag name~
i call those right-click commands
a modal? perhaps
yes but you have to type the tag out before hand, but i was thinking of that as a secondary option to create a tag
you can only have up to 5 context menu commands
dpy calls em context menus and distinguishes user/message menus with parameter typehints

