#discord-bots
1 messages · Page 251 of 1
Eh, yeah, probably just the posts
How i can make ping command when the client do not accept commands and bot Dont accept Latency
?
why does the client not accept commands
I will send screenshot
And also someone in this server told me that
but you're not using a client
you're using a bot

!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
I tried this
use a bot
nothing to do with latency

!d discord.ext.commands.Bot.latency
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
.latency how you see here
`` import discord
from discord.ext import commands
import os
import random
intents=discord.Intents.all()
bot = discord.ext.commands.Bot("?", intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send(f"the ping is {round(bot.latency * 1000)} ms ")
@bot.command(aliases=["8ball"])
async def _8ball(ctx, *, question):
responses = ["dumb", "nope", "uveu", "Bronze", "shit", "hit", "lana rhoades", "riely reid"]
ctx.send(f"Question: {question}\nanswe: {random.choice(responses)}")
@bot.event
async def on_ready():
print("Online !!")
token = os.environ['Token']
bot.run(token) ``
How I'm missing question
looks like you ran command without passing question argument
Look at the code
what does that have to do with code
I used question
question has no default value so if you run command without passing question it will raise exception
!8ball question
With aliases I need use this?
do you know what alias is?
I also did this
and did it work?
Nope
error?
Yes
show it then
Enable tracemalloc to get the object allocation traceback
I miss await
Anyway, it's probably just a warning
Because you made it do so
okay guys
how do i make a request for response?
like how i do in scanf from C language
but by discord text input?
i'm planning to it request an input
in a button to press
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
but if you're using a view you should open a modal instead, it's a better UX
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
@unkempt canyon
•
» args-kwargs
» async-await
» blocking
» botvar
» class
» classmethod
» codeblock
» comparison
» contribute
» customchecks
» customcooldown
» customhelp
» dashmpip
» decorators
okay, i thijnk i will need an example of how to use it
from discord import ui
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
Docs : https://discordpy.readthedocs.io/en/latest/interactions/api.html?#discord.ui.Modal
Detailed example : https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py
How can I prevent this from happening?
There is a race condition in my code, even though I'm using queue.Queue
if users_queue.qsize() <= 9:
embed = discord.Embed(title=f"1 player is currently in the queue" if users_queue.qsize() == 1 else f'{users_queue.qsize()} players are currently in the queue', description=f'{member.mention} has joined the queue.', timestamp=datetime.datetime.now(), color=discord.Color.blue())
await ctx.send(embed=embed)
return```
what about the use of a db?
that'll lock the db when writing to it, so that fixes that problem I'd say..
you might want to look at max_concurrency
!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 "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.
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I tried storing my bot token through a .env file but it gave me this error
https://paste.pythondiscord.com/nuwimasuqa
I still want people to be able to queue up at the same time. Is that possible with max_concurrency?
Well you can make it wait until person before command finishes
What docs do I read for discord.py
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Something like this?
@commands.max_concurrency(1, per=commands.BucketType.guild, wait=True)```
Yeah should be good
How can I add the same logic for this code?
@client.event
async def on_voice_state_update(member, before, after):
if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):
# Check if the member is in the users_queue
for user in users_queue.queue:
if user['member'] == member:
users_queue.queue.remove(user)
channel = client.get_channel(712074759453671494)
embed = discord.Embed(title=f"1 player is currently in the queue" if users_queue.qsize() == 1 else f'{users_queue.qsize()} players are currently in the queue',
description=f'{member.mention} has left the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.red())
await channel.send(embed=embed)
return```
Events cant be limited
Right, so what's your suggestion?
Either limit it by yourself by storing data who and when to limit
You mean with db?
Db or just dictionary in python?
If its data that you need only for small amount of time then can be dictionary
Can you please show me an example?
I'm not sure what you mean
I dont really know what you are trying to do exactly
How do I give another user's balance, I can't extract the member's id @
class solde(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot=bot
@app_commands.command(name='solde', description="voir le solde")
async def csolde(self, interaction: discord.Interaction, user: str = None):
# Load the balance data from the file
with open("balances.json", "r") as f:
balances = json.load(f)
if user:
user_id = #####HERE
user_balance = balances.get(user_id, 0)
embed = discord.Embed(title="Solde", description=f"Solde de {user.id}: **{user_balance}**€",
color=0x46a9f0)
else:
user_id = str(interaction.user.id)
user_balance = balances.get(user_id, 0)
embed = discord.Embed(title="Solde", description=f"Votre solde: **{user_balance}**€",
color=0x46a9f0)
await interaction.response.send_message(embed=embed, ephemeral=True)
When two users join or leave the queue simultaneously, it can result in the same number being shown twice
As you can see here
"3 players are currently in the queue"
But it should be 3 and 4, right
Is it possibly to sync commands to only be in guilds not dms
I don't want a specific guild just don't want commands in dms
this is called a global check, you should check it out in the docs
🙏 Thank you
do mind that you don't have to add this decorator on top of every command, you can just use
https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#global-checks
instead
A lot better. Cool thanks for all the information
wait it is possibe to make a discord bot in python?
I dont know
it was more of a statement of disbelief
You can make a discord bot in every language pretty much lol..
C++, C, JS, TS, Rust, Golang, C#, etc
very cool, I did not know that, thanks
To make a discord bot, you're interacting with Discord's HTTP API which doesn't care what language you use
All you need to do is send HTTP requests
But the Discord API is huge so there are wrappers (like discord.py) that abstract away a lot of that work
But fundamentally, at the core, you're still making HTTP requests over the internet
very cool, thank you
what are HTTP requests and how do you do them or use them
HTTP requests are the language of the web - when you visit google.com, your browser makes an HTTP request to Google. Pretty much everything you do on the web is an HTTP request
gotcha
Your browser has the capability to make HTTP requests. There are command line utilities like cURL that ship with most Windows and Linux distributions, there are also libraries in all sorts of languages to make HTTP requests (requests in Python, reqwest in Rust, axios in Node.js, etc..)
The only caveat is that at a large scale (like Discord) HTTP requests can be tricky and annoying to work with. Libraries like discord.py aim to simplify that by providing an interface native to your language
Writing your own discord API wrapper can be quite fun and educational, however is more of an advanced project
Making a bot using the raw Discord API can be a fun challenge as opposed to using a library such as discord.py
Can discord bot record voice in voice channel?
Yeah, but I don't think discord.py supports that functionality
send code
of which part
how did u declare bot is it using client?
if so it will be @client.command
Can u send your code??
what exactly does this want me to do
not this? ["694482209096204308", "694482209096204308"]
(insert as int, not string)
so then this? [694482209096204308, 694482209096204308]
probably
it didn't work though
it says Command raised an exception: AttributeError: 'Bot' object has no attribute 'owners'
Well maybe it just doesn't have that attribute then
have you checked the documentation to see if the attribute is correct
that's the same as 694482209096204308
well it's giving me a different response so I guess it worked?
Traceback (most recent call last):
File "/home/filledwithnothing/Downloads/cheeseburger-bot-master/index.py", line 30, in <module>
if json.load(meow)["debug"] == "no":
^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 8 column 17 (char 349)
gave me this
looks like your json is malformed
your first key as no value too if I'm looking at that right
I moved it
because no share bot token
oh right
no .env?
forgot this was json not python 😭
no
How do I use MemberConverter().convert in interaction?
It requires me to pass in ctx as a argument, but I assume that you can't use ctx in interaction.
Here's what I tried so far:
# I tried using "interaction" as ctx, but it didn't worked out
await commands.MemberConverter().convert(ctx=interaction, argument=user.name)
you can create Context from Interaction
Wait, how?
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
Ahh thx
whole main.py?
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
async def backup(self, ctx, include_all_channels=False):
try:
permissions = {}
categories = ctx.guild.categories
channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels
for category in categories:
permissions[category.name] = {
'id': category.id,
'type': 'category',
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in category.overwrites.items()
]
}
for channel in channels:
permissions[channel.name] = {
'id': channel.id,
'category': channel.category.name if channel.category else None,
'type': str(channel.type),
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in channel.overwrites.items()
]
}
```
Error:
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
I have no idea what is causing "Command raised an exception: AttributeError: 'Bot' object has no attribute 'owners'"
I don't know if it's in the index file
Cause it only has these attributes?
Please Someone
It doesn't exist
I have no idea how their bot is working it's someone else's bot and it's running right now
Yes it will run but the part which errors will not
Different libraries perhaps?
possibly this
I'm using Pycord so that's the only attributes that show up for me
Dpy also has the same attrs
their whole bot is this
We only need the part where the error is happening
yeah it doesn't say
And what is it that you're attempting?
Use owner_ids instead of owners lmao
It'll work
async def backup(self, ctx, include_all_channels=False):
try:
permissions = {}
categories = ctx.guild.categories
channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels
for category in categories:
permissions[category.name] = {
'id': category.id,
'type': 'category',
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in category.overwrites.items()
]
}
for channel in channels:
permissions[channel.name] = {
'id': channel.id,
'category': channel.category.name if channel.category else None,
'type': str(channel.type),
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in channel.overwrites.items()
]
}
```
Error:
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
in the json?
'PermissionOverwrite' object has no attribute 'to_dict'
it does not have that attribute
Huh?
so you cannot call permission_pair.to_dict()
this was answered above, no attribute
You have to use IDs for storing owners right
You cannot put User objects into the json
change the logging and make it log the whole traceback next time
change bot.owners to bot.owner_ids wherever the command is being called
bot.owner_ids or bot.owner-ids?
_
underscore
I literally said the same thing 5 minutes ago
can you even use '-' in function names? 
I know but like the same bot is running like it is right now
I meant in a "is it possible" way xD
if you don't mind getting a Syntax error, sure
And how would that change anything?
they are running the same code no?
Just restart it?
what do you mean, I went thru the code 5 times and didnt catch anything
I was being sarcastic too lmao
it's not my bot
permission_pair.to_dict()
Just tell the person to join the server and ask for help
It's easier that way
permission_pair is a PermissionOverwrite object which doesn't have a to_dict method
no it works for them
@WOLF 07#0007
This must be a bot that you found on github to use then?
no
@turbid condor
I'm so confused then lmao
they gave me the bot's code to host it myself
because of past events between us so we parted ways
code needed
of any specific line?
the whole file
i don't know your code..
Line 340-350
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
or can u tell me what ur gonna do with the code so that i can do it
paste it here and share the link
We can't help with what we can't see
we are not wizards
no one is trying to steal your stuff
remove the brackets from the bot.command decorator 
i am going to steal it 👿
we need to see what you are doing
Shhhh
thought I was a magic electric rock wizard :(
What is happening
no unfortunately you are just delusional 😢
At least you can make computers go beep boop beep
is all that matters
Also I finally got my slash commands working for my lil test package!
One step further to world domination
btw any one knows how to import a command from another file inside a cog?
Why not move the command into the cog
Or add the other command into a cog and load it from there
Did you already break up all the commands into individual cogs?
All!?
Or do you just have one big cog

not yet
Yeah it might be time to consider refactoring
if this is the case, you might as well have a single main.py file-
Ah, the days before I knew python and was copying from github
have 1 command per cog like me 
cogs and extensions are not the same btw
Though they're often used in conjunction
files are loaded with extensions
i find it's useful to have multiple cogs per extension
Yeah the "one cog per extension" is maybe a bit too Java-ish for my liking
I have commands in different cogs but they all belong to same category so I was thinking if there is a way to somehow import the command inside a single heading like when I use help command it should show like
Fun Commads:
command1
command2
Moderation:
command3
command4
that's weird considering you're a Java nerd
I never understood the difference from:
bot.add_cog
bot.load_exstention
I always used the first-
An extension is a collection of cogs pretty much
And a cog is a collection of commands and listeners and state
extensions can be used without any cogs involved though
So it's mostly for displaying in a help embed?
yeah
Mmm
each command has a Cog attribute
i am thinking of making a select menu with the help command
Yeah you should just break it down more
There shouldn't be any need for sub-sub-categories
I've always hated that default help embed-
every new bot instance
bot(help_command=None)
and just make my own-
there was no bot.owners in the code
and I subclass that
In any commands?
nope
This seemed like the common factor to when it had an error
doesn't necessarily need to be bot.owners; it was trying to access .owners on a Bot object which could have been called anything
What's the code for that command?
also when did discord start having tags like that? lmao
Do you have a full error traceback?
no
their code sets that attribute manually
Was the code like this already, no edits or such?
If so I'll just go look at the github
yes it's all on the github
the only thing you change is the config json
I believe they are using the same exact code?
so it works I guess
You should add an else statement to this
it's like a bit against tos
to print error
welp then how would we know why are you getting the error
if we can't see the code
what's against tos?
@turbid condor check dm onc
zzz just share it here
https://github.com/REDPANDAUwU/cheeseburger-bot/blob/master/cogs/moderator.py#LL122C52-L122C52 is throwing the error because client.owners doesn't exist
code
Sharing your code is not against tos 
Bro, literally no one wants it that bad. Either you need help or not
the code is against
Ahh, understood
?
@slate swan
oh
so why is it working for the owner
I am confused
@lethal drift @buoyant quail so could anyone of u help me?
Your bot is a GroupMixin object, is that expected? It's usually a client or a bot
@slate swan
can I make client.owners exist in this?
Not if what you're doing is against the ToS
changed that
client
okay I see
You redefined it somewhere it seems
you can define it yourself or just use owner_ids
Disaster
their client is a Bot object, it's just poorly-named
It would say Client.command in the error then, or i am mistaken?
how do I use owner_ids
I am just trying to use the fwtarchive command
just replace owners with owner_ids
there is no owners in fwtarchive command

oh nevermind
so like this
I did not work 😢
okay I will try to define client.owners
async def backup(self, ctx, include_all_channels=False):
try:
permissions = {}
categories = ctx.guild.categories
channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels
for category in categories:
permissions[category.name] = {
'id': category.id,
'type': 'category',
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in category.overwrites.items()
]
}
for channel in channels:
permissions[channel.name] = {
'id': channel.id,
'category': channel.category.name if channel.category else None,
'type': str(channel.type),
'overwrites': [
{
'id': str(target.id),
'name': str(target),
'type': str(type(target)),
'role_name': str(target.name) if isinstance(target, discord.Role) else None,
'permissions': permission_pair.to_dict()
} for target, permission_pair in channel.overwrites.items()
]
}
```
Error:
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
It was already answered here.
You are doing permission_pair.to_dict()
But there is no such method, we don't know what you expect it to be
I don't know how to define it 😭
i helped you with your issue a few days ago #discord-bots message
I don't think that's how I was supposed to define owners
I changed client.owners to owner_id and it didn't respond when I said the command
what do you need owners for at all
just do @commands.is_owner()
and override is_owner or something
you don't even need this part because the owner of the bot application is detected automatically
I don't even care about the owner function either
I just want to execute the command that's it
can I just delete that whole section?
then why'd you include that part in the first place
I said it's not my bot
I am just trying to use a specfic command of this bot
and I was given this code by the owner
it's not their code
Open a pull request or learn Python @slate swan
I'm just going to delete that section I guess
it's evil
not even responding to me now
that isn't valid python
why was this in the code 😭
literally one line after that it says self.client
they're two different things
yes
the __init__ function has a scope function so you cannot use variables defined in that function outside of it
hmm
what's confusing about it, the bot already uses self.client
@commands.command(hidden=True)
async def update(self, ctx, key, *, value):
with open("prices.json", "r") as f:
data = json.load(f)
data[str(key)] = str(value)
with open("prices.json", "r+") as f:
json.dump(data, f, indent=1)
await ctx.reply(f"New data:\n{data[str(key)]}")
shorter example of prices.py
{
"book": "3,000",
"pen": "2,000"
}
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: JSONDecodeError: Extra data: line 49 column 3 (char 1372)
i want to update an item price in different json files, first execution always making the json files a mess, so the second execution not gonna work, how i solve it?
that it wasn't giving that error only until after I defined owners
probably because you defined it wrong
just remove the entire line and use @commands.is_owner()
I defined it the same way in other parts of the code
^
again that's a different part of the code
ah okay
this is all you need to fix it
and delete the other owner lines in the command
no there isn't
I just like reset it and did what you said and it still gives the error
show your code and the error
the error is in a different part of the code
oh well
where did you get this code
someone made it and gave me the code
they not good at this so it hs errors
there's a github link
are you only trying to use one feature?
ah
the thing is their bot is up right now
but for some reason their code isn't working for me
one sec
async def rps(interaction: discord.Interaction, rps: str):``` how can i make an if statement so if rps isn't a certain word
e.g if rps is gun i want the bot to say you can only chose rock paper and scissors
use a literal
rps: Literal["rock", "paper", "scissors"]
imported from typing
how can i make the bot say something using Literal
oh ok
I don't think the archive command could work on itself right
it could
oh okay
what do I change that to since discord limit is 25mb
what is this based on
it's in bytes
oh okay
@slate swan check your dms
does anyone know how I can turn this off
that this pops up in my screen the whole time
bot_answers = ["rock", "paper", "scissors"]
user_answers= rps
await interaction.send_message(random.choice(bot_answers))
if bot_answers == "rock":
if user_answers == "rock":
await interaction.channel.send(f"{interaction.user.mention} we both used rock so it is a draw")``` what should the bot_answers be?
is it client?
its trying to help you lol
I want it disabled
pycharm i suppose?
its annoying, comes in my screen the whole time can't even see what I write as it stays on my screen
yes
go to ide settings
and select editor | inspection
locate the inspection you want to disable
and clear the check mark
apply changes and boom ur done
i dont use pycharm telling you from past experience
got it
there is inspection right under code style
Still got it while I disabled python, hmm w8
ok wait ill tell you
go to file > settings
editor
smart keys
insert self or something i think
but i think
smart keys is in general now
search for it
uncheck what you want to disable
happy to help :)
@commands.command(hidden=True)
async def update(self, ctx, key, *, value):
with open("prices.json", "r") as f:
data = json.load(f)
data[str(key)] = str(value)
with open("prices.json", "r+") as f:
json.dump(data, f, indent=1)
await ctx.reply(f"New data:\n{data[str(key)]}")
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: JSONDecodeError: Extra data: line 49 column 3 (char 1372)
i want to update an item price in different json files, first execution will add an extra curly or existed key value pairs copy, so the second execution not gonna work, how i solve it?
We don't need the shorter example, we need the line 49 column 3 as the error says
{ "power_relic": "5,000 ~ 6,000", "nature_relic": "5,000 ~ 6,000", "fire_relic": "7,000 ~ 8,000", "damage_relic": "7,000 ~ 8,000", "leeching_relic": "4,000 ~ 5,000", "ice_relic": "3,000 ~ 4,000", "magic_ore": "3,5000 ~ 4,000", "crim_bar": "15,000 ~ 20,000", "mythan_bar": "60,000 ~ 80,000", "gold_bar": "600,000", "cobalt_bar": "80,000 ~ 90,000", "varax_bar": "120,000 ~ 140,000", "magic_bar": "50,000 ~ 55,000", "dclaw": "14m ~ 18m", "dhorn": "500,000 ~ 700,000", "deye": "18m ~ 20m", "rage_sliver": "8m", "disdain_sliver": "12m", "corrupt_sliver": "13m", "torment_sliver": "14", "nleg": "50m ~ 55m", "neye": "2m" } "disdain_sliver": "12m", "corrupt_sliver": "13m", "torment_sliver": "14", "nleg": "50m ~ 55m", "neye": "2m" }
before the first execution, there is no multiple "disdain"
is nextcord-ext-ipc fast and good for a discord dashboard, or should i use another one?
There you go, now you see your JSON is invalid
yeah, and that's because the command
there is something wrong in the command, i just doing !update dhorn 1m ~ 2m
!pypi nextcord-ext-ipc
No way you want to disable intellisense
I think we just encountered real notepad user
Hello, how to retrieve the id of a person with his @?
why channel.connect never return?
vc = ctx.voice_client
if vc:
if vc.channel.id == channel.id:
return
try:
await vc.move_to(channel)
except asyncio.TimeoutError:
raise VoiceConnectionError(f"Moving to channel: <{channel}> timed out.")
else:
try:
await channel.connect(self_mute=True)
except asyncio.TimeoutError:
raise VoiceConnectionError("f'Connecting to channel: <{channel}> timed out.")
await ctx.send(f'**Joined `{channel}`**')
``` (discord.py)
from discord.ext import commands
@commands.command(name='get_id_by_mention')
async def get_id_by_mention(ctx: commands.Context):
mentions: List[User | Member] = ctx.message.mentions
mentions[0].id
async def get_id_by_mention(ctx: commands.Context, member: discord.Member):
@keen moat You've already got a job running - please wait for it to finish!
You destroyed it
bruh
That's a wrong channel btw #bot-commands
oh my bad
its not gonna stop
yeah

actually i wanted to search for discord.Client but then commands.Bot popped up in my head and i kinda mixed it 
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
Sorry, an unexpected error occurred. Please let us know!
TimeoutError:
<@&831776746206265384>
some error happened here
seems like it timed out while trying to add the
reaction
i dont have that emoji
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
we'll chalk it up to cosmic rays
how to delete messagez
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Hi is there a rule somewhere that says the bot has to be running24-7-365?
a rule?
yes, i have been told (not sure how true it is) that a bot can not be down and has to be running that time period.
or else what?
was told that we could get in trouble with discord devs if its not running and that they can shut our accounts down ( not sure if the person was saying this as a scare tactic, not sure how much truth if any this holds)
obviously completely wrong
check your sources I'd say
glad I asked here, thank you for letting me know they were not being truthful.
but yeah, this is blatantly false and doesn't even make sense
as when you're updating commands or whatever, your bot has to restart 🤷♂️
guys what is a role select menu
Well it's a select menu where users can select roles
ive never heard of it, how do i pass in the roles there?
Fascinating
!d discord.ui.RoleSelect
class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.
Please note that if you use this in a private message with a user, no roles will be displayed to the user.
New in version 2.1.
You don't
no i fucked up 😞
yeah, that isnt my problem, i just created a role select, but it saays AttributeError: 'RR_Selection' object has no attribute 'to_dict'
this is my code:
https://paste.pythondiscord.com/gakumijogo
couldnt find anything in the docs
view as modal*
I think most people use a regular select menu and just pass in role IDs themselves
how can i space out stuff in an embed
What do you mean by space stuff out
like paragraphs
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.
embed = discord.Embed(title="Here is some information about the bot", description="This bot can generate numbers. I have some of commands. Made by zagzag990#0482", color=discord.Color.random())
embed.add_field(name= "member count:", value = f"```{len(client.users)}```")
embed.add_field(name= "server count:", value = f"```{len(client.guilds)}```")
embed.add_field(name="", value="This bot can send random numbers using the random-number command you choose a from number to number e.g 1 10 would send a random number from 1 to 10")
embed.add_field(name="", value="This bot has some moderation commands like kick and clear. kick kicks a member the command only shows for people with the kick member permission. Clear purges messages only shows for people with manage messages. mute and unmute which mutes/timeout users only shows for people with the manage messages permission")
``` on moblile theres no paragraphs
can't you just use \n
thats what /n does
how could i use it?
\n or /n
just use it in your string
does someone know how this emoji is called
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
any clue on how you may scrap the message content from an embed
not an emoji
and you cannot change it
embeds do not have content, maybe you meant description
!d discord.Embed.description
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
yeah ik, i found it on some emoji website, i want it too look similar to the role select
thats why i needed it as an emoji
i know i'm considering an embed that went sent and let's say for example you have an on_message event where you want to get the already sent embed's content (it is impossible with message.content or whatever your context is)
@client.tree.command(name="avatar", description="shows someone's avatar")
async def avatar(interaction: discord.Interaction, user: discord.Member=None):
if user == None:
user = interaction.author
embed = discord.Embed(title=f"{user}'s avatar", url=user.avatar_url)
await interaction.response.send_message(embed=embed)```
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'avatar' raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'```
how can i fix this
embeds do not have content
like i just said
use Member.avatar.url instead
ok
display_avatar ideally
is there a possible way to scrap its description or its fields
fuck the nitro users lol
!d discord.Embed.to_dict
to_dict()```
Converts this embed object into a dict.
just use embed.description or embed.fields
you can use message.embeds to get a list of embeds on the message
there can be up to 10 embeds i think
how can i get the image to show on the embed?
that would have been the solution but here my case is listening to an on_message event where i can't even get the embed's variables
how does that affect nitro users 
message.embeds
I'll try the dict way
gives a list of embed objects if present
you can though
let's see
you need to get an embed object either way
yeah bruh
how can i get the image to show on the embed?
which part of the embed
!d discord.Embed.set_image for a larger image at the bottom of the embed and `discord.Embed.set_thumbnail for a smaller image in the upper corner of the embed
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.

Which one should I use the first or second one?
member = ctx.author
users_queue.append({"member": member})```
1. ```python
staff_ids = [710241598348329080, 710242627089596459, 727152007009271822, 849018401300938832]
staff_members = [user['member'] for user in users_queue if
any(role.id in staff_ids for role in user['member'].roles)]
if staff_members:
lobby_creator = random.choice(staff_members).mention
else:
random_user = random.choice(users_queue)
lobby_creator = random_user['member'].mention```
2. ```python
staff_ids = [710241598348329080, 710242627089596459, 727152007009271822, 849018401300938832]
staff_members = [member for member in users_queue if any(role.id in staff_ids for role in member['member'].roles)]
if staff_members:
lobby_creator = random.choice(staff_members)['member'].mention
else:
random_user = random.choice(users_queue)
lobby_creator = random_user['member'].mention```
staff_members = [user['member'] for user in users_queue if any(role.id in staff_ids for role in user['member'].roles)] or staff_members = [member for member in users_queue if any(role.id in staff_ids for role in member['member'].roles)]
are you sure you need the whole member object in your queue? isn't an ID enough?
It should only choose a lobby creator, prioritize staff members
I'd use the first option
also, make sure it's lobby_creator_mention
also
any(role.id in staff_ids for role in user['member'].roles)
might be a bit more readable with a utils function
What do you mean by this?
a better variable name
you'd have no idea what a lobby_creator is without looking at its initialization
So when I set a global variable in a form so it can appear in message that will be called later for person A, if Person B uses the bot at the same time they can change that global variable by filling out their form so person A accidentally receives person B results, how do I work around this so nothing gets mixed up
- Don't use global variables as they are shit
- Use
max_concurrency - Make some sort of dictionary global variable that maps user ID -> data
What about locks around the function?
And that's what max_concurrency does, ggs
Either way don't use global variables, doesn't seem necessary for their use case either. And if you do, then choose a proper type for that global variable e.g. a dictionary which maps ID with data as you won't overwrite the data of the other users
What about events?
What about events?
Sometimes it saying "3 players are currently in the queue" (x2) twice, when in reality there is 2 players in the queue
@client.event
async def on_voice_state_update(member, before, after):
if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):
# Check if the member is in the users_queue
for user in users_queue:
if user['member'] == member:
users_queue.remove(user)
channel = client.get_channel(712074759453671494)
embed = discord.Embed(title=f"1 player is currently in the queue" if len(
users_queue) == 1 else f'{len(users_queue)} players are currently in the queue',
description=f'{member.mention} has left the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.red())
await channel.send(embed=embed)
return```
When two users leave the queue simultaneously
Sounds completely unrelated to their questions
basically the logic is to transfer the audio from the website to the discord bot in the app's voice channel using selenium, ffmpeg and pydub in real time 24/7. most of the time i tried to run the code i got this error message:[WARNING ] discord.gateway: Shard ID None heartbeat blocked for more than 10 seconds.
Because whatever you're doing is blocking the entire bot and not being run asynchronously
(For quite some time as it doesn't respond to heartbeat requests from Discord)
im a beginner, do you have any tips?
!d asyncio.loop.run_in_executor you can use this to run blocking code
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
can someone help me fix thispy @bot.command(name="blacklist_bots", description="Blacklists bots in a certain channel") async def blacklist_bots(ctx, channel: discord.TextChannel): if ctx.author.guild_permissions.administrator: bots = [member for member in channel.members if member.bot] default_role = ctx.guild.default_role for bot_member in bots: await bot_member.add_roles(default_role) await ctx.send(f"{len(bots)} bots have been blacklisted in {channel.mention}.") else: await ctx.send("You must be an administrator to use this command.")
@slate swan Is it recommended to use asyncio.Lock on voice events?
Don't know, don't use Python
Tell us the error
Why do you add the default role though, everyone already has it..
so when i type out the command like ```!blacklist_bots #chat````it doesnt blacklist them
Well what you're doing doesn't make sense in the first place
You're adding the role @everyone to all bots
Although that role is already in fact given to everyone and can't be removed
Then change your code to use a custom role, then come back with that code and potential errors, also add logging
@bot.command(name="blacklist_bots", description="Blacklists bots in a certain channel")
async def blacklist_bots(ctx, channel: discord.TextChannel, role: discord.Role):
if ctx.author.guild_permissions.administrator:
bots = [member for member in channel.members if member.bot]
for bot_member in bots:
await bot_member.add_roles(role)
await ctx.send(f"{len(bots)} bots have been blacklisted in {channel.mention}.")
else:
await ctx.send("You must be an administrator to use this command.")
!codeblocks
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 118, in warn
await open_account(user)
File "main.py", line 177, in open_account
db[str(user.id)]["warns"] = 0
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/replit/database/database.py", line 479, in get_raw
raise KeyError(key)
KeyError: '852572272711303248'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'warn' raised an exception: KeyError: '852572272711303248'
async def open_account(user):
if str(user.id) in db:
return False
else:
db[str(user.id)]["warns"] = 0
return True```
idk why it is raising this error
seems like your user id isn't in the db
but i have an if statement there
so it checks
which you think does what exactly?
what?
it's english though
in short, I don't think you can add nested dicts in that db
maybe try
db[str(user.id)] = {"warns":0}```
instead
not sure, I don't work with (bad) hosts like replit
ok
oh wait i fixed it
gl hf
what does that slang mean?
good luck have fun
how do i use this, i tried it in different ways and i keep getting the same error
Why am I getting this error and how do I fix it?
RuntimeError: Task <Task pending name='discord.py: on_voice_state_update' coro=<Client._run_event() running at C:\Users\Gamer\Downloads\blitzcrank\venv\lib\site-packages\discord\client.py:441>> got Future <Future pending> attached to a different loop
@client.event
async def on_voice_state_update(member, before, after):
if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):
# Check if the member is in the users_queue
for user in users_queue:
if user['member'] == member:
await queue_lock.acquire() # waits until the lock is unlocked, and locks it
users_queue.remove(user)
channel = client.get_channel(712074759453671494)
embed = discord.Embed(title=f"1 player is currently in the queue" if len(users_queue) == 1 else f'{len(users_queue)} players are currently in the queue',
description=f'{member.mention} has left the queue.',
timestamp=datetime.datetime.now(), color=discord.Color.red())
await channel.send(embed=embed)
queue_lock.release() # unlocks the lock
return```
It's something with the lock
what is users_queue?
List
so its not a variable
Oh yeah you are right
yeah i noticed it and i see it not defined
so maybe why
It actually is
oh
where tho
its not in your code
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
await open_account(user)
warns_amt = db[str(user.id)]
warns = 1
db[str(user.id)] += warns
await interaction.response.send_message(f"{user.mention} has been warned.")
duration2 = datetime.timedelta(hours=2)
duration = datetime.timedelta(hours=1)
embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed.add_field(name = "Mute duration",value = "1 hour")
embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed2.add_field(name = "Mute duration",value = "2 hours")
serverlog = client.get_channel(993925329901068391)
if warns_amt == 3:
await user.timeout(duration)
await serverlog.send(embed=embed)
if warns_amt == 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)
if warns_amt > 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)
``` the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3
what are we looking at here?
fixed?
Hi, im having an issue where my bot connects to the voice channel, but then hangs immediately..
@commands.slash_command(description="Join a voice channel and speak the text")
async def speak(self, inter, voice:Voices, text: str):
await inter.response.defer(ephemeral=False)
voice_channel = inter.author.voice.channel
if voice_channel is None:
await inter.response.send_message("You are not connected to any voice channel.")
return
print(f'user is in voice channel {voice_channel.name}')
print(f"Connecting to voice channel: {voice_channel.name}")
vc = await voice_channel.connect()
print(f"Connected to voice channel: {voice_channel.name}")
print(f"Setting voice to: {voice}")
self.speech_config.speech_synthesis_voice_name = voice
print(f"Voice set to: {voice}")
The console prints user is in voice channel General and Connecting to voice channel: General, but then doesnt print anything else, im super stumped as to why, the bot has all permissions (I even granted administrator just in case) the application has the connect and speak scopes enabled, and the bot successfully connects to the voice channel, but doesnt do anything else..
i have PyNaCl installed, as well as FFmpeg
does it at least time out?
no, all other commands still function
i also put a try except block around the connection, but it doesnt raise anything
sorry, I can't really answer if it's about forked libraries of dpy
as I'm not using any of those
hmm ok, been meaning to migrate to dpy, will do that and see if the issue still persists
the bot is not playing the audio from the radio, selenium fulfills its role and plays the audio only for me, there is some problem when the audio stream must be sent to the discord server
i tried pydub and ytbdl
yes i have found my people, except im very new to this since the last bot i coded was 2018
so im making a bot with commands and the commands ran fine before i implemented cogs to keep my code looking cleaner
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
okay let me rerun my command in my server rq
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import asyncio
from keep_alive import keep_alive
keep_alive()
client = commands.Bot(command_prefix=",", intents=discord.Intents.all(), help_command=None)
bot_status = cycle(["mercy", "and", "lucki", "run", "this", "shit"])
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[: -3]}")
async def main():
async with client:
await load()
await client.start("your_token")
@client.event
async def on_ready():
print("/SwatSec is ready.")
change_status.start()
@tasks.loop(seconds=2)
async def change_status():
await client.change_presence(activity=discord.Game(next(bot_status)), status=discord.Status.dnd)
@client.event
async def on_member_join(member):
print(f"Member joined: {member}")
welcome_channel_id = 1116923452918607894 # Replace with your welcome channel ID
welcome_channel = client.get_channel(welcome_channel_id)
embed = discord.Embed(title="+1", description=f"welcome to comm {member.mention}")
embed.set_thumbnail(url=member.avatar_url)
embed.add_field(name="", value=":emoji1:")
embed.add_field(name="", value=":emoji2:")
await welcome_channel.send(embed=embed)```
i broke it @quaint epoch
You will get rate limited if you change your status every 2 seconds
Instead change it after 5 or 10 min
oh oki
but any idea as to why it isnt running, and yes my token is in the spot it should be
are you calling your main function? in the code it doesn't seem you are
and also, its client.run, i dont know 100% if .start exists, never used it or seen it before but i may be wrong
Been a while since ive made a bot
Running this code and I get this error
bot = commands.Bot(command_prefix="!")
TypeError: init() missing 1 required keyword-only argument: 'intents'
i think so
is that your entire code in the code block
yes aside from my cogs
then you aren't running your main function, use asyncio to run your main function
how would i go about that
use the asyncio module which you've already imported
U need to setup intents too along with prefix
!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 "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 "discord.Client").
New in version 1.5.
im not able to transmit the audio stream from the radio website to the bot to play on discord, I've already tried using pydub and youtube_dl, I'm tired of trying with chatgpt/google/stackoverflow I can't take it anymore, anyone heeeeelp meeeeeeeeeeee
yes right, how does asyncio fully work im new to this whole new thing
!d asyncio.run
asyncio.run(coro, *, debug=None)```
Execute the [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) *coro* and return the result.
This function runs the passed coroutine, taking care of managing the asyncio event loop, *finalizing asynchronous generators*, and closing the threadpool.
This function cannot be called when another asyncio event loop is running in the same thread.
If *debug* is `True`, the event loop will be run in debug mode. `False` disables debug mode explicitly. `None` is used to respect the global [Debug Mode](https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode) settings.
This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.
Example...
thank u
thank u as well
yep
What is the rate limit of changing the channel name??
I know for messages it's 50 per second
2 per 10 minutes i think
Hmm
RuntimeWarning: coroutine 'sleep' was never awaited
asyncio.sleep(3)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
FGIX?
you need to await your sleep lmao
Im so slow i just noticed 😭
Why won't they document ratelimits 🧐

Uh that's global ratelimit
Was gonna say, 50 messages per second seems way too high
Youtubers when they make everyone ping in general chat of 100k+ server and accidentally cause API latency jump to 60 seconds
after 3 hours can help currently a bit occupied
no
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
await open_account(user)
warns_amt = db[str(user.id)]
warns = 1
db[str(user.id)] += warns
await interaction.response.send_message(f"{user.mention} has been warned.")
duration2 = datetime.timedelta(hours=2)
duration = datetime.timedelta(hours=1)
embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed.add_field(name = "Mute duration",value = "1 hour")
embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed2.add_field(name = "Mute duration",value = "2 hours")
serverlog = client.get_channel(993925329901068391)
if warns_amt == 3:
await user.timeout(duration)
await serverlog.send(embed=embed)
if warns_amt == 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)
if warns_amt > 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)```
the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3
Can anyone help ? When I click in the button it edited message but it doesn't play music.
send your code pls\
I used discord.ui.button function
is vc a variable]
yes
can someone help me please
Would be nice if you could remove those unnecessary blank lines, makes it harder to read
Tried but does nothing
Doesn't help much if you don't share anything besides "not working"
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
await open_account(user)
warns_amt = db[str(user.id)]
warns = 1
db[str(user.id)] += warns
await interaction.response.send_message(f"{user.mention} has been warned.")
duration2 = datetime.timedelta(hours=2)
duration = datetime.timedelta(hours=1)
embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed.add_field(name = "Mute duration",value = "1 hour")
embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
embed2.add_field(name = "Mute duration",value = "2 hours")
serverlog = client.get_channel(993925329901068391)
if warns_amt == 3:
await user.timeout(duration)
await serverlog.send(embed=embed)
if warns_amt == 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)
if warns_amt > 6:
await user.timeout(duration2)
await serverlog.send(embed=embed2)```
the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3
async def open_account(user):
if str(user.id) in db:
return False
else:
db[str(user.id)] = 0
return True
thats the open account thing
@commands.command(hidden=True)
async def insert(self, ctx, tabel, kolom, value):
self.cursor.execute(f"INSERT INTO {tabel} ({kolom}) VALUES ('{value}')")
self.con.commit()
self.con.close()
await ctx.reply("Ok")
@commands.command(hidden=True)
async def select(self, ctx, table, column):
data = self.cursor.execute(f"SELECT {column} FROM {table}")
self.con.commit()
for i in data:
d = i
await ctx.reply(d)
self.con.close()
help? after i use the insert command then i use the select command
sqlite3.ProgrammingError: Cannot operate on a closed database.
is the close() method needed?
If you are closing connection, then you need to create a new one
Tell me you lock these commands to be owner-only and not just "hidden", especially whenever they're prone to SQLi
- use context manager
- use parameters instead f-strings in sql queries
- if you want a command to be used only by owner for example create a
check - you should use asynchronous library in a discord bot to operate on a database (for sqlite it could be
aiosqlite)
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Python sqlite3 docs - How to use placeholders to bind values in SQL queries
• PEP-249 - A specification of how database libraries in Python should work
Hey guys !
So currently I’m having issues with trying to have my bot hosted through NovoNode. In my Main.Py file Import Interactions is tossing an error along with a few other things.
Have any of you used NovoNode in the past ? Do you recommend any other hosts ? Any information would be appreciated dearly !
did you install interactions on the host via pip?
@slate swan I haven’t no, I’m still learning python / was given bot files from a friend to tinker around with.
But that friend didn’t make them nor knows anything about Python/Bots
well to make it work you need packages that are required and you need to install them on machine you want to run it on
try to locate terminal or command line on your host and install needed dependencies
how i get url of person's avatar with id with bot?
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
like this?
avatar = discord.User.avatar(1046837060557873182)
print(avatar)
no
you need to get the user with first method
and then his avatar.url attribute
how?
bot.get_user(1046837060557873182).avatar.url
that could raise errors
either NoneType has no attr url or NoneType has not attr avatar
since get_user and avatar atrrs can return None

anybody know how can i install ffmpeg on replit
U can check in packages if it's available there
You can't even use voice on replit
You'd find like 10 premade things if you just googled "rss to discord"
Thank you
just run poetry add ffmpeg in the shell?
oh nvm 💀
python -m pip install -U discord.py[voice]
Anyone could help me with my bot?
It will come to vc when i enter command
Other also all worked fine
But it can't play music
Would you be able to send the code?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Check DM
Does anyone know if I can get on python users connections info (for example my twitch name account shown in the image)
No
hi
I had a bot made time ago, and now i had to update the constructor with something called intents. Idk what are the exactly, but i had to do weird things.
intents.members = True
intents.typing = True
intents.presences = True
intents.message_content = True```
Idk exactly what are they for
If i untick these options, my bot stops working
tho my bot is only on my server, so idk why
sudo apt install ffmpeg ?
https://discordpy.readthedocs.io/en/stable/intents.html#do-i-need-privileged-intents
An intent basically allows a bot to subscribe to specific buckets of events. The events that correspond to each intent is documented in the individual attribute of the Intents documentation.
for example if your bot tells discord that it wants to use theinvitesintent, discord will send an event anytime an invite is created/deleted
see also discord API's docs:
https://discord.com/developers/docs/topics/gateway#gateway-intents
how can stop errors from happineng in an event
nothing else
if you're using prefix commands (i.e. !hello-world or similar), then you typically need messages + message_content in order for it to work
i wouldnt bother setting members and presences in your case
idk, i copied from stack XD
an error message would be much more preferable, but im assuming you only unticked it in discord and didnt disable it in your code?
but why do i need the options on the discord portal? they are meant for "big" bots
mine isnt
sec, ill show
they're not meant for big bots at all
any bot that needs the events/data provided by those privileged intents will need to enable them
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
can you show the entire traceback(s)?
that error message is a common bug with windows, but the real error is somewhere above that
maybe this
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002B1CDF0FD30>
Traceback (most recent call last):```
and now its explained in the error message what you have to do
you disabled it in the dev portal, but your code is still asking for members/presences/message content intents: py intents.members = True intents.presences = True intents.message_content = True
intents.typing = True
intents.message_content = True```
typing is part of the default intents btw
I removed the ones i sayed, but, why do i need this intents? cuz my bot wants to write? and embed = msg_content?
oh i think i remember sending embed on previous version was still something special, perhaps?
its needed for your bot to see the content of most messages
if my bot cant read the content and i type !hello-world, it wont know that i tried using a command
(although discord will still provide content if you're DMing the bot or mentioning it)
okey, so why isnt message_content true by default?
because its a privileged intent
discord isnt guaranteed to allow your bot to use it
(or rather, discord disallows those intents by default until you enable it in the dev portal)
but, why/what will a bot who cant read do? 😮
they can still register slash commands
intents.message_content = True is to allow the bot reading msgs, right?
aaaaaaa
okey so i only need the third option, the msg content privilege
i get 2 info warnings
INFO discord.client logging in using static token INFO discord.gateway Shard ID None has connected to Gateway.
i believe the first one is cuz my bot token is on the py file, right?
u can have it print "bot is online" or something like that for u to know
what should i overwrite?
im not that knowledgeable in python so..
if it was warning it would say warning
it says "info"
i want this command to be voice channel required meaning a user has to be in a vc in order for the command to work and if there not i want it to send a message saying they need to be in a vc for the command to work (dont judge me)
@client.tree.command(name='invite', description='Sends edited embed for people to join')
async def invite(interaction: discord.Interaction):
voice_channel = interaction.user.voice.channel
if voice_channel is None:
await interaction.response.send_message("You are not connected to any voice channel.")
return
await interaction.response.send_modal(crow())```
okey, thanks guys
hey everyone
I have a question was wondering if anyone could figure out why its not working for me. Im writing some code for a "jinx" bot. it sees if two people on the server have said jinx within 10 secs and keeps track of results. ```import discord
from discord.ext import commands
import asyncio
from collections import defaultdict
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
jinx_messages = defaultdict(list)
scoreboard = defaultdict(int)
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
content = message.content.lower()
if 'jinx' in content:
jinx_messages[message.channel.id].append((message.author.id, message.created_at))
# Check for jinx within the last 10 seconds
for jinx_message in jinx_messages[message.channel.id]:
if (message.created_at - jinx_message[1]).total_seconds() <= 10 and message.author.id != jinx_message[0]:
scoreboard[jinx_message[0]] += 1
await message.channel.send(f'{message.author.mention} was jinxed by <@{jinx_message[0]}>! Score: {scoreboard[jinx_message[0]]}')
break
# Remove messages older than 10 seconds
jinx_messages[message.channel.id] = [(author_id, timestamp) for author_id, timestamp in jinx_messages[message.channel.id] if (message.created_at - timestamp).total_seconds() <= 10]
await bot.process_commands(message)
@bot.command(name='score')
async def show_score(ctx, user: discord.Member = None):
if user:
await ctx.send(f"{user.display_name}'s score: {scoreboard[user.id]}")
else:
scores = '\n'.join([f'<@{user_id}>: {score}' for user, score in scoreboard.items()])
await ctx.send(f'Scoreboard:\n{scores}')
bot.run('token')
note that voice will be None if he's not in a voicestate
so you can't just do .channel on that
you'll have to check if voice is none instead of voice.channel
This is my code but sadly its not working and im getting no feedback from the bobt in the server
message intents are incorrect
you need message_content 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.
gl hf
ty will look into it :)
where are the docs about how to make the bot react with emojis to its own msgs and when certain number of reactions occur something else happens?
nice, now rewrite it to make use of an async database 🙂
nvm, that's not really needed in your case, as it's only relevant for 10 seconds
yep
bot your code is pretty clean, keep it up
keep using official documentation and examples to learn discord py
avoid YT tutorials
thanks it works now
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.reactions = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
@bot.command()
async def post_embed(ctx):
embed = discord.Embed(title="My Embed", description="This is my embed message.")
message = await ctx.send(embed=embed)
await message.add_reaction("emoji1")
await message.add_reaction("emoji2")
@bot.event
async def on_reaction_add(reaction, user):
if user == bot.user:
return
message = reaction.message
if message.author == bot.user and message.embeds:
embed = message.embeds[0]
if reaction.emoji == "emoji1":
# Reacted with emoji1
if reaction.count >= 3:
# Perform action when emoji1 has 3 or more reactions
await message.channel.send("Emoji1 has 3 or more reactions!")
elif reaction.emoji == "emoji2":
# Reacted with emoji2
if reaction.count >= 3:
# Perform action when emoji2 has 3 or more reactions
await message.channel.send("Emoji2 has 3 or more reactions!")
bot.run('YOUR_BOT_TOKEN')
Is this how to make a bot react to its own msg and then do things based on number of reactions?
i mean u can try it out first then see what errors you get back
no error no reaction xD
i tried it myself the reactions work but not the messages
do u know the format for emojis?
its <:name:id> and for animated emojis its <a:name:id>
write what
how did u do it? cuz it isnt working for me
I tried with the default emojis but it didn't work u can try to add a custom emoji
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "" is not snowflake.```
wut
u need to add \ before the emoji then copy and paste the results
idk if its the same with other emojis but it worked for the check mark one
yeah, i tried adding the slash and same error mmm
do \ ✅ in a text chat then copy and paste it to ur code
you should end up with the check mark as a reaction
.post_embed
oop
the only thing that doesnt work is the messages after a certain amount of reactions and for that ur gonna have to get more professional help cuz im still a beginner
whats the difference between commands.Bot and AutoShardedBot?
AutoShardedBot automatically creates shards of your bot to split it into smaller chunks which will handle certain guilds
I see now i get it why Stat bots works fine
So except this there is no big difference between them like some privelges
makes me sad my bot basically died without ads as i've stopped paying attention to it and just kept it running
this ended up being the retention
5% of people who engaged with the bot spent 2+ hours using it
7.5% spent 1+ hour
#ban command
@nextcord.slash_command(description="Bans a user. Please specify the reason.")
@application_checks.has_permissions(administrator=True)
async def ban(self,interaction, user: nextcord.User, *, reason=None):
try:
await user.send(f'You have been banned from {user.guild} because of: \n {reason}.')
await interaction.guild.ban(user = user, reason=reason)
except Exception:
await interaction.send("Failed to DM the user, oh well.")
await interaction.guild.ban(user = user, reason=reason)
embed=nextcord.Embed(title="Banned User", description=f"I have successfully banned `{user}` for the reason of: `{reason}`", color=0xfd9fa1)
await interaction.send(embed=embed)
im getting this error, does anyone know why? the ban does go through but the embed response isnt sent
laughs in x^-1
it is a almost perfect exponential
Yep
No uppercase in folders
only one problem?
Especially not KeyBoard it's always written as Keyboard either way
Then the rest depends on what your handlers do and why you need a keyboard folder for a single file
okay but what about structure?
bot_token.txt is not really something we like to see, consider using environment variables
Then the rest seems fine if the files are actually what they do and it's not over-engineered (too many files for junk code)
thanks anything else?
Hey, i made a command that delete people when pining someone that his id is in the json file but not working
import nextcord, colorama, aiohttp, requests, json
from nextcord.ext import commands, tasks
with open('./cache/dontpingmeids.json', 'r') as f:
ids = json.load(f)
class DontPingMe(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
print(message)
try:
if message.mentions:
mentioned_ids = [mention.id for mention in message.mentions]
if any(str(user_id) in mentioned_ids for user_id in ids):
await message.delete()
await message.channel.send("**Désolé, mais la personne que vous avez mentionnée n'aime vraiment pas ça. :pray:**")
except Exception as e:
embed = nextcord.Embed(title="Une erreur est survenue :vhrisk60:")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1028693898635251724/1080766112733593620/pngfind.com-warning-icon-png-2681594.png")
embed.add_field(name="L'erreur en question : ", value=f"\n`{e}`")
await interaction.response.send_message(embed=embed)
def setup(bot):
bot.add_cog(DontPingMe(bot))
No error
are any commands "working"?
it's not a command, but other commands work
can you confirm that your cog is loaded?
seems like you haven't debugged your code, as if that was the case, you could point out exactly which if statement had unexpected behaviour for you
yeap
Do you get a message in console? (which you print in the begginning)
Do you get an error message?
Are the ids actually strings in the file?
Try to print out mentioned_ids and ids
and you're checking this how exactly?
def cogsload():
for folder in ["commands", "events"]:
for filename in os.listdir(folder):
if filename.endswith(".py"):
print(botloading + f"{filename[:-3]} a été chargé avec succès")
bot.load_extension(f"{folder}.{filename[:-3]}")```
it says that the file "ping" where i coded the things is loaded
most likely
if any(str(user_id) in mentioned_ids for user_id in ids):
this will be False
that doesn't mean it is in fact loaded though
wdym
you could check by printing something specific in the cog itself, but yeah


