#discord-bots
1 messages · Page 288 of 1
How do I make a command run every 24hrs and where the time persists thru resets ?
@final iron
Thanks for not helping and waste time
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
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).
Oh
You have bigger issues with your code lmao
💀 sorry mate
Finally
If you want it to remain persistant through resets you'll have to setup a database
Ohh
Yea I got a database setup
But how will the bot keep the time before it restarts
It's cause the bot is still in the loop or you have another idea?
Is it going to be intentionally shut down or are you just worried about accidental shutdowns?
Well so far it's intentional shut downs but your right I'll just set it up when I'm done working on my bot 💀
Thanks tho
You could use on_disconnect, but that'll happen occasionally even while the bot is running
Darn
There might be a more elegant way to do it, give me a second
Whats the reconnect argument in tasks ?
Your helping alot, thanks a ton 😭
Nice ingro
I have no clue
You'll have to ask somebody smarter than me
There might be something like on_websocket_disconnect or on_heartbeat_disconnect but I can't find it right now
I'd ask some other people
You can do that ?
!d discord.ext.tasks.Loop.time
property time```
Read-only list for the exact times this loop runs at. `None` if relative times were passed instead.
New in version 2.0.
You can pass let's say 06:00 and it will run every day on 06:00 regardless of it having been shutdown.
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) subclass. The remaining arguments must be integers in the following ranges...
So could you give me a simple example of it ?
As a cog or just the loop function?
Just a loop function
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop.time There are already plenty of examples on the site. But specifically this will suit you the best most likely. ```py
import datetime
from discord.ext import commands, tasks
utc = datetime.timezone.utc
If no tzinfo is given then UTC is assumed.
times = [
datetime.time(hour=8, tzinfo=utc),
datetime.time(hour=12, minute=30, tzinfo=utc),
datetime.time(hour=16, minute=40, second=30, tzinfo=utc)
]
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
self.my_task.start()
def cog_unload(self):
self.my_task.cancel()
@tasks.loop(time=times)
async def my_task(self):
print("My task is running!")
Oh damn
For time you can also just pass a single item. Do notice that if you plan to use anything needing Discord information, guilds, members etc you would need to wait until the bot has been started.
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook) can lead to a deadlock.
Using this you can wait, I recommend doing that in the cog load and moving the start over there.
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
Right thanks a ton panda
Np, good luck.
question how to keep the bot runing
Get a VPS and run it there
doyou now a free one
There’s no "free" vps’s. I recommend hetzner, digital ocean, or vultr.
Hetzner is the cheapest, however imo digital ocean is the best.
You can also go for a containerised environment those are most of the time cheaper and run better & more reliable.
is it possible to add a fast forward feature to a music bot with the FFmpegPCMAudio module?
as i understand it, i probably would need to load the entire music first in its entirety for this to work. i was looking to PyAudio for some references but I didn't find anything useful for this
self.vc.play(
discord.FFmpegPCMAudio(m_music, **self.FFMPEG_OPTIONS),
after=lambda _: self.play_next(),
)
also one other thing,
if I were to write self.play_next() outside of the anonymous function, the bot just skips through the queue without letting any audio play. is it mandatory? I have read the docs and it said it would wait until the current stream ends but it didn't really specify how it "waits"
put it in a await ctx.send(embed=your_embed)
If you mean like speed up a track you can totally do that, you can seek as well. But we're not really allowed to help make music bots here since it's against Discord ToS. Since we're a Discord partner we have to follow those terms.
even if the music bot plays the music from my local pc?
then lets speak in terms of ffmpeg and pyaudio module
Well I can't help with this now that I know what you are doing 😅
touche
and also my goal is not to speed up, but to skip to a particular section of a music
You can always get approval from a mod then I'd be happy to help.
Like go forward 10 secs?
yeah
so maybe tell me if either ffmpeg or pyaudio can do that? i just need this information i guess then I can experiment on my own, let's say to create my own audio player
Yes you can do this.
strange error:
File "c:\Users\User\Documents\GitHub\RP-Utilities\cogs\CharactersCog.py", line 185, in _character_default_delete
response = discord.on_message(ctx)
^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'on_message'
what is the correct use of on_message?
The error is not strange at all 
hello i have a problem with my npm better-sqlite3
It's an event, so you either use the event/listener decorator or override the bot's on_message method
!paste
for whoever was trying to post codeblocks
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
i see
how i should use it then, like, is there any example of using it correctly?
🐈
@bot.event # (assuming that your bot's instance is named 'bot')
async def on_message(message: discord.Message):
... # do whatever you want with the message
!d discord.Client.event
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
```...
Oh nice, there's an example in the docs
oh, so i need to make a separated function then
this is the python discord 💀
??
help me
Well, this seems more like a npm thing, but judging by the errors; it looks like the program cannot find a Python executable
(and maybe try asking in a JavaScript server or something, this is a Python server so people here might not be able to help much)
#ot0-psvm’s-eternal-disapproval message
There's an invite link there
did you do after=self.play_next()? because that's pretty much gonna call that function before it even play
yes
yea, since after takes a callback
from the docs
The finalizer,
afteris called after the source has been exhausted or an error occurred.
yea, but you're calling it, you didnt give it a callback
tbh, that lambda function is fine, because after takes a callback that will gives you 1 argument, and your play_next doesn't seems to have it
oooh
so all i have to do is just pass the play_next() function into another function?
that then plays it
sure, or after=self.play_next, but you need to set play_next to have 1 argument
i see
ok thanks for the explanation, i think im starting to get how this module works
and the argument is error yes?
yes
do i have to do anything with that argument in the callback
no, thats up to you if you wanna read what error was raised during the play
it's None when there is no error when the audio finished
def play_next(self, error):
if error is None:
# continue the stream
else:
# do something
i guess in the end its going to be something like this?
ehh tbh i would rather log it to see what error raised and still continue the stream
since i wouldn't want errors to stop it
oh yea make sense
duhh
i guess the error itself won't stop the playback by design? it just tells us something's up
yeh
goot it
okok back to maintaining the bot
big thanks!
oke
There is any way for me to fix options with a slash command?
Like /warn user(discord tag), type(2w, 4w OPTION), reason
choices?
Yeah
How will I write a code that isn't formatted like that?
what?
async def atgard(ctx, spelare: discord.Member, åtgärd: discord.Option):
Like that ^^
There’s 3 ways to do it
wdym like that
Pick whatever one you’d like
discord.Option doesn't even exist
What exists then?

The Literal is what i like. Easy and short
Using a typing.Literal is the easiest imo
NameError: name 'app_commands' is not defined
Is it a slash command?
They expect you import it, like everything else in the library lol
from datetime import timedelta
from dis import disco
from email import message
from tkinter import N
from typing import Union
import discord
import json
from colorama import Fore
import os
import threading
import fade
import time
import timer
import base64
import emoji
import httpx
import ctypes
import json as jsond
import requests
import hashlib
from uuid import uuid4
import binascii
import subprocess
import sys
import discord, colorama, sys, os, json, pystyle
from discord import app_commands
from discord.ext import commands, tasks
from discord import Option
from pystyle import Add, Center, Anime, Colors, Colorate, Write, System
Docs are showing the example, you are not supposed just copy randomly lol
from discord import app_commands
you have that
Yep
alright should be fine now
File "C:\Users\blomo\Desktop\Unive Kriminell Bot\sourcecode.py", line 26, in <module>
from discord import app_commands
File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 50, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\enums.py)```
Show pip freeze output
what the fudge is that 
Looks like old/broken with some forks library
Does discord.Option exist?
This is just a complete shitshow
Ah lol
Don’t use requests, it causes blocking.
Good note
check out aiohttp
Then it's surely not discord.py
I am new to this
What library do you use?
As u could tell
hashlib?
For discord
ugh idk
💀
^
So do you want to use discord.py or py-cord?
discord.py i guess
You seem to have one or multiple forks of discord.py installed. These forks may interfere with official discord.py code causing possible errors. You can use the following script to uninstall any possible fork you may have installed and create a fresh install of discord.py:
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
pip uninstall discord
pip uninstall discord-ext-slash
pip uninstall discord-py-slash-command
pip uninstall discord.py
pip uninstall pycord
pip uninstall py-cord
pip install discord.py -U
oh, nice list
Just run this code in a separate file, in your venv(if any)
File "C:\Users\blomo\Desktop\Unive Kriminell Bot\sourcecode.py", line 30, in <module>
bot = discord.Bot(command_prefix='.')
AttributeError: module 'discord' has no attribute 'Bot```
Did this
You have some messy code from different libraries it seems
discord actually has no Bot attribute
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
The error is pretty self explanatory, a bot object is from the commands extension.
Also, are all these actually used?
I'd believe half of them are imported just for fun
regex is complicated asf but its a lifesaver
more like autoimports by IDE since variables weren't defined locally
till now i was storing my bots servers data like this, now when i think about it, its very dumb. like if you have something for only one guild, youre not gonna make a whole column for it
soo any suggestions how else can i save data?
i was thinking, maybe a table for each guild? will it work?
asking here because i wanna do the final this time, its not gonna be fun chaning again anf again
tables in SQL should generally never be dynamically defined, so storing each guild as a row is already correct
columns are usually a good idea for server settings because all guilds can take advantage of it, but if you're really sure you'll never use it in other guilds, i guess putting that setting in a new table with one row is fine (i would still structure it so it could scale to other guilds, for example a dedicated guild_welcome_message table with guild ID as primary+foreign key)
ah, i see, i need lil bit of thinking on it before i say anything
but yeah if youre saying this method is correct, okay i will find a way with this one
in short i was trying for a command which with its work can allow user to create a new colums, commands direct purpose wont be to create a column but yeah what ever it does it will require a column different in each server. but while typing it here i realised maybe that command is just useless
lmao
yeah okay, thanks man @hushed galleon
Thats a py-cord thingy
The moment py-cord made that change is when I knew it's gonna suck lol
How to disable help command?
And how to disable timeout in wait_for
by default, wait_for doesnt have a timeout unless specified
So how to make like if the command used 2 times the first wait break
what is this even for
For example:
The command !hi make the bot waiting from you to send hello but I used the command another time so now if you send hello the bot will make the action 2 times
Or this disabled by default?
just limit the command to be used only once concurrently for each person?
dont allow the command to be invoke if its not done yet
I don't want that
well, you can't achieve this with a wait_for, and its unnecessarily complicated if you want to implement that
I want if the command used another time so the first wait breake and another one starts
Ah
Can you explain to me how to do that
!d discord.ext.commands.max_concurrency
@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses.
This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.
New in version 1.3.
just use that
What about this?
instead of disabling it, i would assume you just wanna customize it
see the bot.help_command=... part, that's the part for help command implementation, you can remove it by setting it to None or make your own with subclassing
Ok Thx a ton
Or if you just want to disable it set help_command to None when creating bot instance
is there a way to add a sub command here
(like role add <user> <role>, role remove <user> <role>, role temp <user> <role>)
@bot.tree.command(name = 'addrole', description = 'Adds a specific role to a specific user.')
@app_commands.checks.has_permissions(administrator=True)
@app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
async def addrole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
await user.add_roles(discord.Object(id=role.id))
await interaction.response.send_message(f'Added {role} to {user.mention}.', ephemeral = True)
@addrole.error
async def on_addrole_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)```
No, you need an app commands group to do something like that
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
thx
AttributeError: module 'discord.app_commands.tree' has no attribute 'command'. Did you mean: 'Command'?
class Roles(app_commands.Group):
@app_commands.tree.command(name = 'add', description = 'Adds a specific role to a specific user.')
@app_commands.checks.has_permissions(administrator=True)
@app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
async def addrole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
await user.add_roles(discord.Object(id=role.id))
await interaction.response.send_message(f'Added {role} to {user.mention}.', ephemeral = True)
@app_commands.tree.command(name = 'removerole', description = 'Removes a specific role to a specific user.')
@app_commands.checks.has_permissions(administrator=True)
@app_commands.describe(user = 'Who will this role be given to?', role = 'What role should they get?')
async def removerole(interaction: discord.Interaction, user: discord.User, role: discord.Role):
await user.remove_roles(discord.Object(id=role.id))
await interaction.response.send_message(f'Removed {role} to {user.mention}.', ephemeral = True)
i can try
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
You are missing ()
In function definition
should be py async def on_ready(): ...
Its discord.ext
You never imported Intents?
!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.
No you read the embed i sent
And look at the example
Look at the imports..
no? it comes with discord
Python is case-sensitive
o yeah
discord.intents is not the same as discord.Intents
Hello How to Juat one role can use command?
refresh
from discord import intents -> from discord import Intents 🤷
can you answer me?
lmaofrom discord.intents import Intents
what's your question
Hello How to Juat one role can use command?
juat?
just\
use has_role check
example?
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
item role id?
good example
from disnake work?
what to expext more
this?
A working one
💀from discord.flags import Intents as Intents
way better
How can I get someone to tell me something when I don't have the role?
implicit imports
import import
Make an error handler
expect?
from docs
Raise MissingRole or NoPrivateMessage
NoPrivateMessage is obviously when the command is ran in dms since there are no roles in dms
so the error that is being raised is MissingRole
add that to your error handler
and handle it way you want
i can fix this easy
but error how to add?
A hands-on guide to Discord.py
...
yea ..
: )
You? wow
(no way)
He is fake 
code:
await interaction.message.delete(delay=5)```
error:
File "main.py", line 51, in dont_use_this
await interaction.message.delete(delay=5)
AttributeError: 'NoneType' object has no attribute 'delete'
why doesn't this code work
add await ctx.send("U", delete_after=10)
wdym
Just use the delete_after argument in send_message
interaction.message is None
I guess that attribute is not updated.
do
message = await send(...)
await message.delete()
Also there is delete_after attribute
ok
await inter.send("........", delete_after=10)
ok
this is easy
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
k it works
wich one good?
If you want to make sure that the message is deleted then the variable method
I am just sending both options. Deleting the message is not what you always want. With such method you can't for example add reactions to message. But here it is good, yes.
👍
\
How I can use max_concurrency in my command
Same as other checks :p
I was asking because it's turned error when I did this but it was because I didn't put a number
Anyway
Thx you
What the name if the handler?
Error
Yup
It's in the docs 

MaxConcurrencyReached
Ok
My command have wait_for and when someone use it tow times and send the same message the bot do the action 2 times so should I use before_invoke or what?
If you didn't understand my question please just tell me to explain and don't ingro me
Why want you separate it? It's logically to make 2 actions if you did call the command 2 times
For example:
When I type the command !hi now you should reply with hello to make the bot make an action but I used the command 2 times and you send hello only one time but the bot make the action 2 times
Looks absolutely correct to me
You called the command two times, made needed action, got two results. One from each command
I want make that you can't use the command another time before the first time was finshed
I know that's correct but I don't want it to happen
You'd add current command calls counter. And do like
if count == 1:
do_action
else:
count -= 1
There are no check from discord.py?
not in else tho
if count == 1:
do_action
count -= 1
I believe no
can someone tell me how to make my bot asign roles to a member with a command
ded chat
py import module from module import *
what does * mean
Import all names from the module
can u tell me how to make my bot asign roles to a member with a command
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
what does atomic mean?
Open the link
atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
Still not very clear tho
I guess it means that sometimes cache can break something but with this setting it won't
no
?
you only need to supply the role ids
the rest of the args you can leave alone because they are defaults
that what the = denotes in the docs
await add_roles(roleid)
perfect
TY
They probably need to be snowflakes though, not just bare integers
snowflakes?
tldr everytime you create a user or a message
an id gets generated with that
and it's called a snowflake
so see this is my user id 670802831678373908
this is an example of a snowflake id
@client.command()
async def verylongcommandthatwillgiveyouaadminroleig(ctx):
await add_roles(1142768251751903312)
doesnt do
or i need to remove the (ctx)
does you bot have the mannage_roles flag
it has admin
no ctx is where all of your command data gets passed to
might have to be a snowflake then
no, bare int doesnt work, you would need to use discord.Object
lemme see if I can find an example unless you had one @naive briar
discord/member.py lines 1043 to 1051
if not atomic:
new_roles = utils._unique(Object(id=r.id) for s in (self.roles[1:], roles) for r in s)
await self.edit(roles=new_roles, reason=reason)
else:
req = self._state.http.add_role
guild_id = self.guild.id
user_id = self.id
for role in roles:
await req(guild_id, user_id, role.id, reason=reason)```
so you would import the discord object class
It'd try to get the id attributes from the roles, so bare integers don't work 
then instatiate it like this discord.Object(role_id)
discord.Object(your id)
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
role id?
yes
snowflake ids are for everything on discord though
users, channels, messages
no
discord.Object(your_role_id)
but you would pass that as the role in the add_roles function
is that the right thing?
the chat dies for no reason
Object is what you need to pass to add_roles
what does that mean cuhhhh
await ?.add_roles(discord.Object(1142768251751903312))
? = your user idk what it is
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
Thought id is keyword 🗿
i want to change the status of the bot
await client.change_pressence(status.....)
i know only that
i forgot it
There is only one s
what
change_presence
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
status is "online, idle, do not desturb and offline" right?
info = s.get('https://api.bloxflip.com/games/crash').json()['history'][num]['crashPoint']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/requests/models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1378, in process_application_commands
await app_command.invoke(interaction)
File "/home/container/.local/lib/python3.11/site-packages/disnake/ext/commands/slash_core.py", line 737, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
What why?
Evry correct
yes
Your request returned empty page
?
!d discord.Status
class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) ‘s status.
gives syntax error
You didn't get any text from the website
^
enum?
class enum.Enum```
*Enum* is the base class for all *enum* enumerations.
from discord import status?
from discord import status?
from discord import status?
ITS NOT OMG
^
i typed it
thought you already know python is case sensitive
is it "from discord import status"?
lmao
from discord import Status it is indeed case sensitive
i think its best that you should start with more basic projects first before discord.py since its pretty difficult to teach you from ground zero
i know like the basic basics
well, the library uses several advance concepts like OOP, concurrency
you need more advanced basics 
thats chinese for me
you need to know topics like OOP, async await syntax, decorators and more
so if you have no idea what im talking about its prolly not time to start discord bot project
wtf is OOP
i know "if, lists, strings, some pygame, veriables, print, else"
and other useless things
!res you can find resources here
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
THERE IS BEGINNER AND HACKER NOTHING IN BEETWEN
xdd
nah, OOP is like, intermediate for python
strings and crypto finding keys and blocking a army of hackers
concurrency is advance
Blocking has nothing to do with hacking duh
wrong reply
idk what im talking abt sorry
blud talking bout the !blocking command (dont send long ass embed response)
I once "hacked" my educational service and could see every student's mark for every work
That's funny
bro can steal my house 🙂
bro stole my house, pls help me
we can't
we don't know "blocking a army of hackers" yet
depends on you tbh
Im making something will it turn out good?
CUH HOW DO I KNOW xd
How to type it
typing intent cmd wrong im good now
!d discord.Interaction
!discord discord.intents
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
thats not what i want
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
What do you mean?
and type what?
im good
now
how to make my terminal more clear?
i dont want to see that useless stuff
hey guys, using discord.py. i am using wait_for to get a response from the user, and im checking if that message contains a mention with if msg.mentions: but i cant seem to find a way to grab the mentioned user's ID. the msg.mention returns a list. which contains the ID. but its all one item so i cant grab just the ID
title CHOOSE UR OWN
cls
echo.
echo.
echo.
echo.
python FILE.py
pause```
Set logging level to higher
how?
Well where do you setup logging
WHAT IS LOGGING
Windows 6 
It is already on when you use commands.Bot
how to clear that stuff in the terminal cuhhh 😭
That for dpy?
ye
You need to set it up don't you
You do, yes
It shouldn't be enabled automatically then
But the bot.run automatically setup it up for you
Oh heck wtf dpy doin
@slow escarp pass log_handler=None to bot.run() it seems
.
Do you need specific ID
i need the mentioned member's ID
Just take value from list by index?
Cause if user mentions several just give them invalid input error or take the first
its all one value
What?
@mighty pilot
It's a list of member objects
It's single Member object in a list
so why doesnt msg.mentions.id work
Because it's a list
It's a list
oh i need to specify the position in the list. thanks
Hello, i'm still here to ask for your help.
I got this Error, don't know what i can do.
[2023-08-20 17:03:26] [ERROR ] discord.ext.commands.bot: Ignoring exception in command test
Traceback (most recent call last):
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simoc\OneDrive\Desktop\Comune di Roveto\DiscordBot\Comune di Roveto, Regione Toscana V2\bot.py", line 99, in test
await channel.send(f'')
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message```
a photo of the command done on discord
https://cdn.discordapp.com/attachments/1140941151193546782/1142836472832086216/image.png
Here's the code:
@bot.command()
async def test(ctx):
view = Votazione()
role = discord.utils.get(ctx.guild.roles, name="Owner")
if role in ctx.author.roles:
channel_id = 783597627316895744
channel = bot.get_channel(channel_id)
await ctx.send("What do you want to ask to the Community? _(Ricorda è una domanda Si o No)_")
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
response = await bot.wait_for('message', check=check)
embed = discord.Embed(
title = f'**Votazione!**',
description = f'``{response.content}`` \n\n *Si:* :thumbsup: - *No:* :thumbsdown:',
color = discord.Color.green()
)
await channel.send(f'')
msg = await channel.send(embed=embed)
await ctx.send(embed=embed, view=view)
ok so, the code work, but the part of sending the message in a specific channel, doesn't work
await channel.send(f'')
msg = await channel.send(embed=embed)
Read the error
HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
error 404 indicates in channel.send() that you cannot send an empty string
basically what this guy said
it happened the same with a different code and in the string was an response.content()
content is a property
you don't call it
response.content
Who have vps?come pv

Done, it works, thank you. (i'll probably come back later lol)
last thing, you can't ping in a Embed, right?
No
You can only just mention user
But you can send it as a message near the embed (embed will be highlighted too)
like
await ctx.send(mention, embed=discord.Embed(...))
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
can someone help me
i fixed it
what to type for the status of the bot to be on do not desturb?
how can i check if, for example, both user1 and user2 have both clicked to a button?
!d discord.Status.dnd
The member is “Do Not Disturb”.
Store clicked users list in its callback
howd i do that?
Get the user id and append
What's the problem
self.clicked.append(interaction.user.id)
This is true and there is no chance, but why doesn't it work? I want him to be able to use those two roles
premium_role = [1113010068712063057,1113010067940327456]
mean two role can use one command
@commands.has_any_role(premium_role)
@buoyant quail sy
I think you have to unpack the list of roles into arguments when you pass it in
@commands.has_any_role(*premium_role)
mean add *?
Yes
alr
What about this @commands.has_any_role(*+premium_role)
Post the rest of the code and your traceback then.
For all we know it could be something else causing it to "not work"
if ctx.channel_id == premium_channel:
await ctx.send(embed=em)
print(f"\n{ctx.author}: Used premium_mines Command")
else:
response = await ctx.send("You can't use this command in this channel.", delete_after=3)
# Delete the bot's message
@pre_mines.error
async def pre_mines_error(ctx: commands.Context, error: commands.CommandError):
await ctx.send("You have not purchased premium so you cannot use this command", delete_after=7)```
Hello anyone here????????/
@buoyant quail
🗿
Are you sure, that you aren't getting any other errors here?
Remove the handler and check the actual error
@pre_mines.error
async def pre_mines_error(ctx: commands.Context, error: commands.CommandError):
await ctx.send("You have not purchased premium so you cannot use this command", delete_after=7)
raise MissingAnyRole(list(items)) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
disnake.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '[1113010068712063057, 1113010067940327456]'
Look error
Check role ids ¯_(ツ)_/¯
premium_role = [1113010068712063057,1113010067940327456]
Yes. Check that you have them. Should work
Send
<@&1113010068712063057> <@&1113010067940327456>
in your chat and show screenshot
(these are pings, don't send it on public)
and you have one of them?
It's the same as doing it like this (when it was a list of ids)
how to mention user in this
You can't
?
somehow there wasnt client.run()
..

!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
If you want to search something use search field on the docs page
@client.command()
async def afk(ctx, *, message="AFK"):
afk_data[ctx.author.id] = message
await ctx.send(f"{ctx.author.mention} is now AFK: {message}")
#(theres the on message part but im not including that since theres other shit)
if(message.author.id not in owners):
if message.author.id in afk_data:
afk_message = afk_data[message.author.id]
await message.channel.send(f"Welcome back, {message.author.mention}! Your AFK message: {afk_message}")
del afk_data[message.author.id]
# Check if any mentioned users are AFK
for user in message.mentions:
if user.id in afk_data:
afk_message = afk_data[user.id]
await message.channel.send(f"{user.mention} is AFK: {afk_message}")
await client.process_commands(message) ```
the bot for some reason sends the message 3 times, why
as in, youre afk, welcome back, youre afk
?
no idea the if(message.author.id not in owners): is on indent level 0 is it still part of the command?
It's not in the command at all as i understood
It's in on_message event
That's what confused me too
ya
So it is inside the command?
it is, indeed
so why are you processing commands, .. , inside a command?
Then why are you calling process_commands there?
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message) event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message) event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context) followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke).
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context) or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke) if so.
Changed in version 2.0: `message` parameter is now positional-only.
Are there others process_commands in that on_message?
on_message is called on each message sent
no sir
print out message.content and see what messages are invoking it
then work out why its 3 times and not once
maybe you are missing some simple check
? no its not
maybe im an idiot hollon
It is
surprise me then
cause i know it is
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#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) does not have this problem.
no as in
Man edited the source code :p
blud using his own fork
the mssage owner part is the bots id. so it shouldnt be called no?
thats why i want you to print message.content
to see which messages invoke it
This part of the code shouldn't then.
But yeah, always easier to just debug instead of guessing. Especially when we have only part of code /
".afk"
Actually how did even got to the command..
I just understood that commands are processed only after checking if id is inside afk_data.. And i guess it's empty in the beginning
Even more - commands sent by owners shouldn't be executed
!paste the code, that will be easier
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
"Even more - commands sent by owners shouldn't be executed" wdym by this part
if message.author.id not in owners:
await client.process_commands(message)
If your id is inside the owners, this condition will give False
And you wan't reach the command processing part
huh
you want me to process it twice? 😭
Of course not
I can't understand how is it even running commands by you
Your process commands function is in an if statement, thus if the statement returns False the bot won’t process commands. You should really always process commands no matter what.
just use @bot.listen() decorator and no need to worry about processing commands
i am
i tried that just now
You are doing process_commands inside bot.listen?
@buoyant quail read again
I’m not sure this would work here, considering he named his bot client, one would assume he’s using discord.Client and listen is apart of the commands extension only.
Yes, i see. Do you have process_commands there? Or you deleted it?
blud .proces_commands is only for Bot
i did delete it
it does the same exact thing idk why
so it is bot instance
just naming issues
yep
I suggest you name your bot object bot instead of client because its extremely misleading
client = commands.Bot(...) is the same as import numpy as pandas
Command is executed before the on_message in the bot.listen()
So you are setting user afk, then it goes to listen and saying it's not afk more
But i am still wondering how are you joining if message.author.id not in owners condition
how do you know what owners is
I am hoping...
name doesnt really matter as we can see already
mhm yeah
okay, but why did it give the same result with different call order (command-on_message / on_message-command)
though we don't know what actually happens :p
What are the exact messages that you get after calling .afk?
bro what are you saying, idk if youre trying to help or talk shit
owners is the bot id in case you were wondering
...
why bot id is named owners
told ya
why do you care is the question, youre not helpin anyway
I am believing in people too much
you typed "lmao" 3 times while saying bs
what else could it be chief
your id?
no as in the error
no idea im not really listening for long 5 mins
@spring summit Specially for you I copied and runned your code. I don't see "sends the message 3 times" with the parts of code you decided to give us
About bot.listen() - that will give 2 messages here - "...is now AFK", "Welcome back ...". But also not 3.
Not documentation
Yes
uhmm
Is it possible to view a members server list and compare it to a list in json? And if it matches the server id kick or ban him? I've seen some bots that do that but i dont know how...
try moving from discord.ext import commands below import discord
blud don't know what he talking about
fr
I just started discord.py
I have a moderation bot template
And I just wanna use it
Sorry if I am dumb
check your python interpreter
whats that
still
idk I haven't done this in a while
yeah you have to install discord for the right python version
How do I do that?
pip install discord
Oh yeah forgot ab pip
How do I find it out
should say it at the bottom
it is 3.11
then do pip3.11 install discord
i kinda have the same problem,i tried installing the discord module using pip install discord/pip install discord.py,and i stii got the error called "no module named 'discord'"
any suggestions?
what python version does it say at the bottom of vsc
i m using pycharm
it s 3.10
it does this when i m trying
damn
no that's not the problem
well what could it be,bcs i already tried a lot of tutorials and it still does the same thing
someone on stackoverflow said he just updated pip
pip3.10 install --upgrade pip
then pip3.10 install discord again
ahahah it does the same thing
the error still pops up
I dunno I think something's wrong with your python installation
does it have something to do with the venv?
yea
It could
Did you install it in the venv of your file?
Did you try restarting pycharm or your pc?
@heady locust what's your OS
How I can get the id of the channel from a message id?
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
Actually looks impossible.. Discord.py has only Messageable.fetch_message, so you should already have the channel
Except if you will iterate over channels, but it's very bad option.. + If there are not global fetch_message it looks like message id can be the same in different places
Message IDs are unique but yeah you cannot get the channel ID through message ID as the only data present
@buoyant quail Bro I did what you said but didn't work
About you can't use the command another time after the first time end
Literally a time stamp
I think
Can you explain it more
I know this is irrelevant but it may be of use to someone
That just gives you the message creation time, not the channel it was created in
Yeah that's why I said it was irrelevant
is this how we group application commands??
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#file-06-extension_with_group-py
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
like this (you can use anything you want as key, i guessed you want the user)
active = defaultdict(int)
@bot.command()
async def foo(ctx):
active[ctx.author.id] += 1
await bot.wait_for("message", check=lambda m: m.content == "hello")
if active[ctx.author.id] == 1:
await ctx.send("hi!")
active[ctx.author.id] -= 1
If you want it for all commands in the cog ¯_(ツ)_/¯
There are another examples without GroupCog
which??
for example 8
10 too
but actually i don't like how they are made in dpy
If 2 people used the command in same time the both will work cause this spisfy the user right?
depends on what will you use as key
But if i used 6th example it would be helpful for organizing
btw i am not able to see the command
What should I import to use this?
I have decided to make my new bot in python since npm is having a stroke and cannot download discord.js
small problem I have no idea of how python works so this'll be fun
sooo uhm, do I actually just not need semicolons?
from collections import defaultdict
you can use a standart one, but i's one line more :p
(to .Hadi.)
and I don't have to specify the data type
ah right; I mostly use c# so that's that. although I am rather incompetent
sooo, dotenv wasn't installed correctly
@tree.command(name="Warn",description="Warn A Member")
@bot.command()
@commands.has_role(872416856940642344)
async def warn(ctx, member: discord.Member, reason= "Not Defined"):
await member.send("You Have Been Warned! From The FedxD Server.\n"
f"Reason: {reason}")
await ctx.reply(f"{member.mention} Has Been Warned")
it doesnt work because i have tree.command and bot.command both init but i have seen some bots with both can you guys tell me how to do it
You seen them as code?
from discord import app_commands, Interaction
from discord.ext import commands
@app_commands.guild_only()
class Chat(app_commands.Group, name="chat"):
@app_commands.command(name="start", description="start chat...")
async def start(self, interaction: Interaction):
print("Launching chat session")
await interaction.response.send_message("start chat...", ephemeral=True)
async def setup(bot: commands.Bot):
bot.tree.add_command(Chat())
you can use hybrid commands if it discord.py
how
alright, I am not able to import anything
idk about some page about them, so just the example
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#file-09-hybrid_commands-py
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
!d discord.ext.commands.hybrid_command
and the docs ofc
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand).
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command).
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer) with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string) type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context) as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction).
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
Here when someone use the command he get 1 so if he used it another time will also get 1 and the command will work I think it should when he start the command -1 and when it ends it get 1
Is that right?
is there any practicle example rthe docs doesnt show any practicle example on how to use it
well, onto discord.net it is
Each time the commands starts it adds 1
Each time it ends it removes 1
So it stores how much times this command is running now by that user
the first link i sent
^
I tried the hybrid cmd, The text based command is working but / not wokring
will the command.has_role() work with hybrid commands
It should
ok
The easiest way to check is to try it
If he used it 2 times a row without end the wait_for it will work
and is using command.guild important for hybrid cause i dont want to just allow commands on one server
app_command.guild**
You need to sync slash commands
There is some text about it on that page above
Shortly just calling await bot.tree.sync() is enough
Cause everytime he use it he get point and if he have point the command will work
I didn't understand
?
Where is it
what is a python interpreter?
If someone use the command he get point (active) and if he have a point the command will work so this didn't solve my problem
so many mixed things man i searched on youtube and the guy made a class for Bot and it the github its dont diffrent what should i go with
He can use it 2 times and work so he should get point after finish the command
cuz vsc wants it and i cant run programs that way
Program that executes python code
The GitHub example
There are a lot of different ways of doing something
Yt tutorials are old
so i need to find where my python.exe is at and link it with vsc?
It seems so
@bot.command(name="sync")
async def sync(ctx: commands.Context):
print("invoked!!")
await bot.tree.sync(guild=ctx.guild)
await bot.tree.copy_global_to(ctx.guild)
await ctx.send("Synced!")
..
Doesn't vsc automatically detect it?
worked!!!!!! thanks D:
I have no idea, i am not using it
Just make this command owner only don't want ppl spamming it
Afaik it automatically detects it
All you have to do is just install python extension and you are good to go
Show example of what must happen
Like
You send:
!work
!work
What's going on then?
do i have to write the guild
class Bot(commands.bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix='!', intents=intents)
async def setup_hook(self):
await self.tree.sync(guide = discord.Object(id=872416856940642344))
its some thing like this
guide
guild

oh
User sends the command !hello now he get a point in active var and the bot waiting from you to send hi so he used the command another time before you send hi so the command will work cause when he type it he get point and when he get point the command will work
lol
i dont get it
The command will work twice
Without the wait_for ends
somethings happenng with my discord bot
when i type !test it should say "bot is good." once but it says it like 4-5 times
WHAT SHOULD I WRITE IN GUILD
ur server id
what if i want multiple servers
Just don't pass guild arg then
multiple server ids
Just sync globally
kok
nah i don't undestand
Read the second message
when i type !test it should say "bot is good." once but it says it like 4-5 times. how to fix it?
So you want not just skip the actions and second command, but wait for the end of first?
who?
.Hadi.
I don't want any wait_for starts if another one is waiting
What?
You are running multiple processes maybe
Also show that command
If someone use the command twice the bot will wait for 2 messages I want make him can't use it another time before the first wait ends
Maybe just allow calling only one command at once ?
bruh can some one like link me a project with hybrid commands in use i cant get it github one is just so confusing he didnt even have the prefix defined
But if 2 people use it in the same time it will work
If this possible so how
class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.
If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.get).
Unlike the standard library threading [`queue`](https://docs.python.org/3/library/queue.html#module-queue), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.qsize) method.
Changed in version 3.10: Removed the *loop* parameter.
This class is [not thread safe](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading).
!d discord.ext.commands.max_concurrency
@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses.
This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.
New in version 1.3.
This contradicts what I said
Is this in docs?
Explained in docs?
second argument
per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.guild would allow it to be used up to number times per guild.
I will try that
TOKEN = ""
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(".", intents=intents)
@bot.hybrid_command()
async def foo(ctx):
await ctx.send("hello")
bot.run(TOKEN)
Note: the command is already synced by me here, make your sync as you need
well i made it work somehow
vs code is worse then pycharm pychamr is easier for python but i uninstalled it because visual code can run many lanugages and i am currently working on python java and cpp so i needed it i wished i didnt switch
i prob didnt need a externet website for the developer badge lol it was easy pretty much
how to fix it?
and restart vsc?
no
just type in terminal
pip install discord
and after like a few secounds it will be fixed
it wll take time to download
did you pip install discord in the terminal?
yes
in the correct folder??
i still have this
You missed the BucketType
I import them but IDK how to use this
discord.ext.commands....
=
from discord.ext import commands
commands...
ok result is that discord package is not instaled corectly in the folder
Bro I mean how to set user
commands.BucketType.user
Ok
can i like copy paste the package files in to my python folder? manually
yea
where can i download the discord package?
you dont have discord downloaded on another python file?
idk
cause i dont think you can download it manually like that
both of them not work?
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
but it's not the best way of installing library :p
it isnt supoosed to do that
Hello, I'm OpenAI's AI. How can I assist you today?
