#discord-bots
1 messages · Page 206 of 1
I will not spoonfeed you, you must learn on your own
okay so what i do to fix that
but I'll make it easier for you, you CAN do guild = ctx.guild
hm okii wait lemme check
or you can remove that line entirely and replace guild to ctx.guild everywhere in your command
how to make this script work on bots too, is working only on users (connecting using token)
wait, that f string will automatically print log_channel = <log_channel var>?
isnt using code to control users illegal
!e
my_var = "some value"
print(f"{my_var = }")
@velvet compass :white_check_mark: Your 3.11 eval job has completed with return code 0.
my_var = 'some value'
TIL
Thats probably my favorite f-string hack
They said it was a bot token
Its now my fav too 😄
Gonna make my life so much easier istg
Should be
{
"Authorization": "Bot TOKEN_HERE"
}
It's important that you have Bot literal before the token
why not just straight up print the variable?
so you can have the my_var = before?
Hey @sick birch! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
depends
yep
It does not depend. If you are automating user actions it is against Discord's ToS and they will obliterate your account
@velvet compass true
How to make a discord bot send specific channel but on a specific server do you guys any ideas?
Do you have the ID of the channel?
I recently reset my bot token and secret, replaced the old token with the new token but the bot isn't responding? I'm not explicitly setting the client secret either so... what am I supposed to do?
yes i have
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Message content intents?
enabled
in code too?
yep
Processing commands, in case of overriding of on_message?
nope I'm using a listener
to mention: it was working before I reset the secret and token
Perhaps get the result and check for errors?
how to check errors :)
r = requests.post(...)
print(r.json())
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
according to the documentation that's a GET method
paste the traceback please
its too small to read
Also what are you trying to do?
You're getting the last 50 messages but then ignoring the response
just send message
im just testing :)
this is what it does
i think i need to rewrite this
or?
that endpoint doesn't send message
it fetches the last 50 messages and returns the result
https://discord.com/developers/docs/resources/channel#create-message
This is the endpoint that sends messages
so what can i do
Use the proper endpoint
i need endpoint?
Yes
so... how do slash commands work now
discord.py is updated since i last used it is it different
@sick birch but should i remain on v6?
Hey guys I have a problem
shoot
it's deprecated, so no
I'm actually just starting out, and while following a tutorial, made a small program, but it returns an error.
`
import discord
from discord.ext import commands
TOKEN = "BOT TOKEN"
client = commands.Bot(command_prefix = '.')
#answers with the ms latency
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')
client.run(TOKEN)
`
And this is the error:
`
Traceback (most recent call last):
File "C:/Users/alsat/OneDrive/TEJ & SAI/A TEJ/OTHERS/TEMPORARY FILES/temp.py", line 6, in <module>
client = commands.Bot(command_prefix = '.')
TypeError: init() missing 1 required keyword-only argument: 'intents'
`
Not sure how it works but I have the code for you if u want?
https://github.com/Rapptz/discord.py/tree/master/examples here are examples
id like someone to explain how it works so i can build upon it later pls
thx robin
np
You need to specify which intents your bot needs to function inside your instance of commands.Bot
this is lookin similar to cogs if i remember correctly, any idea why?
What are intents? I'm new to this
basically permissions you give your bot
@sick birch should i use v9?
so the perms integer?
no
in your code do this:
from discord import Intents
and
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = "!", intents = intents)
Essentially they are telling Discord which events/data your bot needs from Discord in order to function.
the intents.message_content = True can be copied and then edited for other intents, just replace the message.content part with the intent name
tp
what i need to modify?
Oh ok thanks!
Yo*, my discord bot won’t respond to any commands. Anyone help?
the limit i guess what can i enter here
send code
anyone know how to fix
Sure
pls
Hi can someone help me?
@sick birch I tried that from yesterday, but an await keeps coming up which cannot be executed
All the code in get_options should be moved into the command
And the get options function should be deleted
And then? why should this be in the command?
Because the command is asynchronous
Okay but first look here
#1080233650047688734 message
and the options must be created in init
Sure. Just pass in the options as parameters
But do the actual fetching in the command
The idea is to only list the first 25 warnings, since a select menu can only have 25 options. You can then use a button called "Page 2", for example, to see the next 25 warnings in another select menu
Yes. Your select class shouldn't do any data fetching
Fetch it in the command and pass it down
And how does the view then get the options?
Pass it in as parameters
The view can then use that and pass it down again to the select
Create the list in the command or in the view?
The command, since it's async
Command (fetch async data here) -> pass to View -> view passes to select
?
can you robin?
i don't want to mention you again cause its annoyed .Can you help me with my problem?
what are you trying to do with that line of code
also i would suggest you delete that screenshot @short ice
@warn.subcommand(name="edit-by-user")
async def warn_edit_by_user(self, inter: nc.Interaction,
member: nc.Member = SlashOption(name="member", description="Please select a member", required=True)):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT case_id FROM warning_system WHERE user_id, guild_id = ?, ?', (member.id, nc.Interaction.guild.id,))
cases = await cursor.fetchall()
options = []
for case_id in cases:
await cursor.execute('SELECT reason FROM warning_system WHERE case_id, guild_id = ?, ?', (case_id, nc.Interaction.guild.id,))
reason = await cursor.fetchone()
new_option = nc.SelectOption(label=str(case_id), description=reason[0])
options.append(new_option)
dropdown = EditWarnDropdown(member, options)
await inter.response.send_message(content="hi", view=dropdown)```
@sick birch is this now right?
you wrote an extra m in has_permmissions
wait
that was right ty
but when i use the command clear it shows me that
@hushed galleon do you know the issue from yesterday?
well it seems you're at least kind of getting the idea right now
i found a solution with robin but now i got a error. I think i forgot something but i dont know what
here is the error
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 296, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\cog.py", line 840, in warn_edit_by_user
dropdown = EditWarnDropdown(member, options)
TypeError: EditWarnDropdown.__init__() takes 2 positional arguments but 3 were given```
wait
there?
here
you need to load it
that is the main file?
and you need to pass a bot object not a client object
you should rename client to bot*
someone can help shortly?
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
how can i make a Cog
that depends tbh
I would make hybrid commands
ok
can you send me a vid of slash commands
use the docs
i suggest disnake
where?
you can do text commands, slash command, user command, and message commands
Your deepest sorrows
i believe in you panda
This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.
Example
# foo.py
print('spam')
if __name__ == '__main__':
print('eggs')
If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:
# bar.py
import foo
If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.
Why would I do this?
• Your module is a library, but also has a special case where it can be run directly
• Your module is a library and you want to safeguard it against people running it directly (like what pip does)
• Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test
This.
.
@commands.slash_command(name="command name", description="description of what the command show tell")
async def foo(inter: disnake.CommandInteraction,'''your args'''):
'''your logic'''
this is a simple command
yy
slash_command sweating
if you want better options, without having to use specific stuffs
you can add the "option" param in the command and use a list of "disnake.Option"
Phew Disnake, my heart dropped for a sec.
yy
why? x3
disnake is times better than discord.py, plsu who knows maybe danny decides again to drop the lib
i prefer a stable one
Discord interaction uses the same format iirc
i mean yeah x3
i still prefer disnake, kinda know that tomorrow i wont see a message about "Deprecating the library"
So I kindoff have a dynamic inventory code I wanted to integrate into discord.py, don't exactly know how
for x in PlayerDetails["Inventory"]: print("[",PlayerDetails["Inventory"].index(x)+1,"]",".","[",x[0],"]")
Just didn't know where to start
How would I exactly put all the details into the description of 1 embed
Traceback (most recent call last):
File "/Users/balthazar/Desktop/PandaBot.py/main.py", line 4, in <module>
bot = commands.Bot(command_prefix = "!",
TypeError: init() missing 1 required keyword-only argument: 'intents'
why ?
pls
i'm a beginer
!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.
what library are you using
I'm not talking with you
sorry
Read this @winged notch
thanks
nextcord
Traceback (most recent call last):
File "/Users/balthazar/Desktop/PandaBot.py/main.py", line 3, in <module>
intents = Intents.default()
NameError: name 'Intents' is not defined
copied code 
Why are you copying code you don't understand
i dont know
^ could anyone help ?
import random
def handle_response(message) -> str:
p_message = message.lower()
if p_message == 'what is paradrift':
return 'paradrift is a fun sporty game, available on steam & developed mainly by nomaden#940'
if p_message == 'roll':
return str(random.randint(1, 6))
if p_message == 'help':
return "`How may I assist you?´"
why wont my bot respond
why would it
is that your whole code?
is there a way to make a bot copy text to the users clipboard through a command
You should learn how to code first
and then start with dpy
no
i told you, learn python first
yeah i was watching that vid a lil bit still didnt get it lol
alr alr alr ill watch all the way through some day, cuz that i did not do
^^^
i belive the PlayerDetails["Inventory"] is a list of strings right?
if so:
...
description = ", ".join(PlayerDetails["Inventory"])
embed = Embed(description=description)
...``` something like this will work
you need to modify the row of these components, iirc you can supply that kwarg on the respective object component instantiation, though it depends on the library and actually I haven't used that much nextcord but I know for sure this
i work with nextcord and to every Item you can provide row argument
no but you can send a message with the contents of a message in the DMs of users
pretty similar to @lament depot bookmark command
why 😭
works within #sir-lancebot-playground
oh replaced with a new thing
I have an open PR to bring it back though
!d f strings
!d format strings
i see
nevermind
!fstrings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
oh right i'm being silly haha
I have a code
file = discord.File(file_path, filename=os.path.basename(file_path))
embed = discord.Embed(
color=embed_color
)
embed.set_image(url=f"attachment://{image_file_path}")
await interaction.followup.send(embed=embed, file=file)
but the bot sends photos and embeds separately
x in attachment://x should be same as the filename variable in your discord.File
how can i wait for a wait for reaction? lol
!d discord.Client.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**...
there's an example in the docs
thank you
hello guys
hi
;-; all i can find is the wait for command
what are you looking for exactly?
you should be using wait_for, just wait for a reaction event
await bot.wait_for("reaction_add", check = ...)
i used wait for but i make it send a message the line after
but it'll send that message reaction or none
i want it to wait for a reaction before sending ;-;
that's what wait_for does
it sends the message without one tho-
could you send your code?
sure one sec
def check(reaction, user):
return message.id==reaction.message.id
try:
reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
pass
if reactedTimes==0:
msg_sent=await message.channel.send("Loading")
you should be waiting outside the check function
why does datetime always give me issues 😦
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
tried both of these
import datetime
from datetime import datetime
i am discord just parsed it that way lemme edit my msg
ahhh
def check has the same indentation as try
it should
it does but still sends without reaction ;-;
what do you mean "sends without reaction"?
like it sends the last line (a message) without any reactions on the message
it dosent actually wait for a reaction ;-;
on_reaction_add does not send a message, it returns a reaction and a user
oh nvm
i'm not sure
if you really want both you can use
import datetime
from datetime import datetime as dt
that way both work like
datetime.datetime.utcnow()
dt.utcnow()
or just keep it simple
import datetime
datetime.datetime.utcnow()
well thank you, ill figure something out lol
Invalid permissions given to keyword arguments.
channel: discord.VoiceChannel = await self.create_channel(member)
permissions = channel.overwrites_for(member)
permissions.manage_permissions = True
await channel.set_permissions(
member,
permissions = permissions
)```
how can I do it then?
why would you provide a permission overwrite obj to permissions
I sent it wrong
just use channel.edit and use permission_overwrites kwarg
I was just trying some permissions and sent that one, but I can't also use connect permission, mnanage_channel etc
overwrites?
!d discord.VoiceChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: The `region` parameter now accepts [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead of an enum...
overwrites are per user/role
the passed object for that kwarg should be like this ```py
{ member1: PermissionOverwrite, member2: PermissionOverwrite}
!d discord.PermissionOverwrite i think there's an example here
class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.
Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.
The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.
x == y Checks if two overwrites are equal.
x != y Checks if two overwrites are not equal.
iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
yeah I am there
let me test it
bruh
the member ahs permissions for managing but can't manage
ty!
you're welcome
Code: py if before.user != before.after: print("Username change")
Error:py AttributeError: 'User' object has no attribute 'user'
Read the error
ah
before and after are both users
how do I start coding
ah I see it now
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
for discord.py read the discord.py documentation
but only if you're somewhat familiar with python
I don’t get it
I’m sped lmao
can someone code a server for me? Or is that not possible
what do you mean?
like members in a discord server
yeah
what do you want it to do
sorry we don't do that here
member bots and nitro bots are against discord terms of service
i'm sure you know that
i won't code a bot for you, if you have questions or an error with an existing bot ask your question here
this is for discord bot help and discussion
oh ok
what should i add to my discord bot
surely there's a better way to do that...
While following a tutorial, I wrote the code for a basic discord bot
`
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run("my token")
that's correct, but isn't that just the quick start bot?
so u don't know?
[2023-03-02 05:53:42] [INFO ] discord.client: logging in using static token Traceback (most recent call last): File "C:\Users\alsat\OneDrive\TEJ & SAI\A TEJ\OTHERS\TEMPORARY FILES\temp.py", line 22, in <module> client.run("my token") File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 860, in run asyncio.run(runner()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 647, in run_until_complete return future.result() File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 849, in runner await self.start(token, reconnect=reconnect) File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 778, in start await self.connect(reconnect=reconnect) File "C:\Users\alsat\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 704, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None 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.
you shouldn't use parse your messages to run commands btw, use the new commands system
enable the message content intent in developer portal, the error is already telling you what to do
How do it do that?
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.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
people don't read error messages anymore they expect the helpers to read for them
I saw the error. I don't even know what privileged intents mean
It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page
You don't really need to know what it means
this is pretty clearly telling what to do
Just follow the steps outlined in the error message
nvm I figured out my problem
how would u do it
Privledged intents are these btw @fading wigeon
Dict
if you're trying to make reaction roles, just make a message-role map
messages = {
message_id: role
}
then, when someone reacts to that message give or take away the role
this pretty much cuts down your actual reaction code by half
i just learned theres discord menus as an alternative for buttons ;.;... is one better than the other?
menus?
it isn't an alternative
menus only supports reactions as far as i'm aware
menus is a helper extension to make reaction menus but it's pretty much obsolete
gotcha
Danny did say they were going to work on Pages which is essentially that, but with views
@slate swan are you making a paginator?
no eta though. It's easy to roll your own though
yeah
you can look at or use mine if you'd like
https://gist.github.com/mudkipdev/4b0ce96a2d9bd6205e16c52798546571
it uses buttons
it's easy to add your own code on top of it
I will probably use it as an example 🙂 ty. someone gave me their paginator w/ that used disnake and a bunch of other stuff a few months ago and i still haven't fully understood it 😄 so i've just pushed it off till i finished my mimo coding lessons.
this is very nicely done though.
thank you
How could I detect a custom status?
Hey, I'm trying to make it so that if a user runs !statuscheck it tells them their custom status how could I code that?
and if the keyword is set to "A" they get a role!
Checking before.activity and after.activity.
If you’re doing something for games, or streaming, you need to look for those values specifically and some users don’t have it work right for streaming so I just made a twitch parser with the connections from oauth2
i do not know if that's possible?
custom statuses are not really activities
is it wrong ?
Can
would the calculation change if i removed the outermost brackets? base_xp *= ((cfg.xp.dig_down + cfg.xp.dig_side) / 2)
Do you know what decorators are
These?
base_xp *= ((cfg.xp.dig_down + cfg.xp.dig_side) / 2)
^ ^
!e
x = 2
x *= ((10 + 10) / 2)
print(x)
x = 2
x *= (10 + 10) / 2
print(x)
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 20.0
002 | 20.0
no it would not
where can I get full information on interaction.guild? like how to get its name, members count, owner, roles count, etc
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
so its a discord.Guild, not a discord.interaction.Guild?
discord.Interaction.guild returns discord.Guild
discord.app_commands.errors.CommandInvokeError: Command 'server' raised an exception: TypeError: object of type 'property' has no len()
what does your code look like
you are trying to use len() on a property
I want the bot to show the amount of channels in the embed not the whole list
Do you know OOP
what catlover said, it needs to be interaction.guild
also you should use 4 spaces or a tab as indentation not 2 spaces
its the same issue
No, just try it
I did already
then how do I get the count
Get it from an instance
You should at least know what instances are before trying discord.py
am I dumb or smth. I havent put the line await interaction.response.send_message
finally
interaction.guild worked
Can anyone send me the docs that explains how to make the bot send time like this: <t:1677730495:f>
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
yea,[["Heasing",50,"Common"],["Heasing2",30,"Rare"]],technically this is how it works in my normal python code , just wanted to replicate that in the description of my embed
Can you provide some code?
oh
ok\
Inventory = [["Heasing",50,"Common"],["Heasing2",30,"Rare"]]
for x in Inventory:
print("[",Inventory.index(x)+1,"]",".","[",x[0],"]")
@slate swan^
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
!d enumerate
enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.
```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
``` Equivalent to...
oh
For example
!e ```py
values = [10, 30, True, "something"]
for i, item in enumerate(values, start=1):
print(i, item)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 10
002 | 2 30
003 | 3 True
004 | 4 something
ooo
but like how would you use this in description
you cant use for loops in f'{}'
or atleast from what i tried
!e
print(f"{[i**10 for i in range(10)]}")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824, 3486784401]
well you kinda can but if you dont know how you can still do something Like this :
desc = ""
for item in something:
desc += item
!listcomp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
You can do description for loop in your code
how do i change my bot status to playing?
!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...
hello, can you help me on this thread please?
https://discord.com/channels/267624335836053506/1080769206435459073
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True)
async def clear(interaction:discord.Interaction, amount: int):
await interaction.response.defer(
thinking=True,
ephemeral=True
)
await interaction.channel.purge(limit=amount)
await interaction.followup.send(
f"deleted {amount} messeges",
delete_after=5
)
@clear.error
async def on_error(interaction:discord.interactions, error:commands.CommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(
"You don't have permission to use this command.",
ephemeral=True
)
elif isinstance(error, app_commands.BotMissingPermissions):
await interaction.response.send_message(
"I don't have permission to manage messages. You can give me the required permissions in the server settings.",
delete_after=10
)```
why the bot still showing "The application did not respond"
thanks a ton down!
Can anybody tell me how to check if message.author is server owner?
hey guys, does anyone know how to make them commands with the multiple options
not the dropdown menus
like this^^
it's a slash command option and it depends on what library you use
Autocomplete also
can anyone help me ?
Ask a question not if there is someone who can help

I wanna send message through bot to other users and message I sent must be displayed in DMs between bot and other users. what can I do for that?
The application did not respond could be caused by bot not responding in 3 sefonds
If your bot takes more than 3 seconds to respond you can usw
but I'm using defer
thinking=True,
ephemeral=True
)```
Do you know how to use it through?
You still need to respond to it
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
like ?

👍
no need delete after send ephemeral
if message.author.id == message.guild.owner_id:
...```
but the bot isn't showing thingking
Try to remove thinking = True
can you explain in more detail. I couldn't find proper answer in that link.
You need to get user you want to message
And use .send on it
With message you want to send
How do I limit a slash command to 1 guild?
Sync it to only 1 guild
umm is it possible to be friends with your own bot?
like i wanted to add it to a group dm to show someone something.
but it doesn't let me add them by default
not possible
ah
bots can only be added to Guilds
gotcha
What does discord.Interaction.user.status do?
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") instead.
it shows offline
value of discord.Status.offline sure
I am dnd
either that user is invisible, offline, or you just dont have presence intents to see it
not off
what intents I have to enable?
Whether guild presence related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache...
and about the banner of the user?
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
TypeError: Client.fetch_user() got some positional-only arguments passed as keyword arguments: 'user_id'
I tried fixing it before I would ask for help
~~[<Role id=1062301004663623750 name='@everyone'>, <Role id=1062346664385466438 name='Blue'>, <Role id=1062312865798815804 name='👑• Siam Official'>]
How do I turn this mess into role mention s~~
Fixed
@naive briar Hey me again. U available?
Either way I'll ask my question and anybody can answer 🙂
so I have a series of slash commands, I want to make some of them available everywhere my bot is and some only usable by me in my discordserver.
How would I do that? do I need a specific decorator?
hello why do I have this kind of error?
if message.author.id == message.guild.owner_id:
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'owner_id'
is django good?
Is aight
the invocation context is a dm channel, which doesnt have a .guild
Why is discord py's ui soo bad?
Like it cant differentiate two members.
Ill explain
Share some code examples perhaps?
dpy doesn't handle ui
Do you mean with buttons and interactions and stuff?
yes
In the class, add a discord_user_id variable.
When you need to call the class, you set the discord_user_id to the user who called the button and do a simple if interaction.user.id == discord_user_id
Alr so here's the overview of what i did:
When a member joins, a private channel is made for them. Inside that private channel, there is a embed message with buttons.
So here's where it fails .. When two members interacts with the buttons, one of them will get a response while the other gets nothing. I even made a custom event just to goddamn get this right but nope, it failed.
Show the code
import discord
class Gender(discord.ui.View):
def __init__(self) -> None:
super().__init__()
@discord.ui.button(label="Boy", style=discord.ButtonStyle.blurple)
async def b(self, it: discord.Interaction, button: discord.ui.Button):
self.gender = "boy"
member = it.user
guild = it.guild
role = discord.utils.get(member.guild.roles, name="Boy")
if role:
await member.add_roles(role)
else:
role = await guild.create_role(name="Boy", color=discord.Colour.blue())
await member.add_roles(role)
await it.response.defer()
it.client.dispatch(member.name, it, "boy")
self.stop()
@discord.ui.button(label="Girl", style=discord.ButtonStyle.red)
async def g(self, it: discord.Interaction, button: discord.ui.Button):
self.gender = "girl"
member = it.user
guild = it.guild
role = discord.utils.get(member.guild.roles, name="Girl")
if role:
await member.add_roles(role)
else:
role = await guild.create_role(name="Girl", color=discord.Colour.red())
await member.add_roles(role)
await it.response.defer()
it.client.dispatch("button_click", member, "girl")
self.stop()
oh is self.stop() the issue?
oops i forgot something
Probably
You're stopping discord.py from listening to the view
So it's not handling any interaction from that view after that
Yeah, once the member interacts with it.
Try this:
import discord
from discord.ext import commands
from discord.utils import get
from discord import app_commands
class TEST(commands.Cog):
def __init__(self, client):
print("[Cog] TEST has been initiated")
self.client = client
@app_commands.command(name="test")
@app_commands.guild_only()
async def test(self, interaction: discord.Interaction):
mybuttons = Buttons()
mybuttons.discord_user_id = interaction.user.id
await interaction.response.send_message("Click!", view=mybuttons)
class Buttons(discord.ui.View):
def __init__(self):
super().__init__()
self.discord_user_id = 0
# Possible Bug: Seems like this is used nowhere
# noinspection PyUnusedLocal
@discord.ui.button(label="Accept", style=discord.ButtonStyle.green)
async def Accept(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.discord_user_id == interaction.user.id:
await interaction.response.send_message("Pressed button", ephemeral=True)
async def setup(client):
await client.add_cog(TEST(client))
``` I havent tested but I assume it works.
But im creating more.
TypeError: Guild.create_text_channel() missing 1 required positional argument: 'self'
**i am getting this error pls help me to fix it **
!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.
Do you know what instances are
!e
class Cat:
def __init__(self):
pass
def meow(self):
pass
Cat.meow()
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | TypeError: Cat.meow() missing 1 required positional argument: 'self'
how can i create a permission for a command that works with a specific role?
!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 "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 "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 "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 "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 "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
i am newbie bro so i dont know much
How many discord servers can my discordbot be in before I have to convert all my text commands to slash commands?
I am trying to make a message cmd that will sync my slash cmds. but when I type the cmd, it doesnt responds. nor it does sync. I do have intents.message_content = True. there's a another message cmd in the on_message and it responds but the syncing one inside the same on_message event does nothing
as long as you have message content intents
which you are need to get verified for after 100 servers ( you can apply after 76 servers )
Neato
from discord.ext import commands
class SyncingCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('Command sync loaded!')
@commands.command()
async def sync(ctx, self) -> None:
if ctx.author.id == 696623699666665532:
fmt = await self.bot.tree.sync()
await ctx.send(f'Synced {len(fmt)} commands')
print('Command successful')
else:
return
async def setup(bot):
await bot.add_cog(SyncingCog(bot))```
whats wrong with this? the issue is its not responding anything
you need to add this extenstion (Cog) in your main bot file
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
async def main():
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await bot.load_extension(f'commands.{filename[:-3]}')
await bot.start('token')
discord.utils.setup_logging()
keep_alive()
asyncio.run(main())```
I did it already
its only adding the slash cmds
no response from the bot
did you switch the parameters places? so self is first
I did
@commands.command()
async def sync(ctx, self) -> None:
``` in this line
I did
does command sync loaded print?
yes it did
all i can see is that if condition is invalid
and in else you return
so nothing is done
from discord.ext import commands
class SyncingCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('Command sync loaded!')
@commands.command()
async def sync(self, ctx) -> None:
if ctx.author.id == 696623699666665532:
fmt = await self.bot.tree.sync()
await ctx.send(f'Synced {len(fmt)} commands')
print('Command successful')
else:
await ctx.send('You are not my developer, smh.')
async def setup(bot):
await bot.add_cog(SyncingCog(bot))``` updated code
but no problems solved
message content intent?
its true
Did you load the extension
yes, it even printed
does something more print now?
Send the code for that
import discord
import asyncio
import json
import random
from discord.ext import commands
import os
from keep_alive import keep_alive
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.presences = True
bot = commands.Bot(command_prefix='$', intents=intents)```
Huh
if you enable all you can just use Intents.all() btw
Do you have a on_message event
yes
you need to process commands inside
@bot.event
async def on_message(message):
if message.channel.id == 1078724782016712805:
if message.author == bot.user:
return
if message.content.startswith(''):
async with message.channel.typing():
await asyncio.sleep(2)
response = random.choice(data)['response']
await message.reply(response, mention_author=False)
else:
return
Did you call process_commands in it
this is inside the on_message
Did you even read something in the link
You can just use @bot.listen() instead of @bot.event and the command is working again
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
how?
like I want to make a reload command that reloads all the cmds
so that I can sync
Well you'd need a stable base that doesn't require much maintenance then make cogs/groups and load them dynamically. Have the extensions reload using the build-in reload function and re-sync with dev guild. If the bot is public make a separate command/task for updating it globally.
You can re-sync the bot 1000 times a day before you get rate-limited and global syncs are much more struct depending on how many commands you have but they generally cap at 1/2 times a day with an added wait time of up to an hour.
So ideally you want to do this with git and have a main/ feature branch and do it automatically.
I already made it
while u were typing lol @cloud dawn
one question, isnt load and reload same?
No
🤔
about updating cmds, can I use load instead of reload?
!d discord.ext.commands.Bot.reload_extension
await reload_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
bruh
I made load, unload, reload cmds already. I am thinking to push off reload cmd
What's the problem
reload can load and unload?
woah
seems awesome! now I dont need to make 2 commands
wont it raise ExtensionAlreadyLoaded?
Facing this error: https://paste.pythondiscord.com/utovewames
while executing the reload cmd
What??
nvm
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 156, in callback
await inter.response.send_message(view=view)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 866, in send_message
await adapter.create_interaction_response(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 184, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
which code triggers the error?
EditWarnDropdown code
class EditWarnModal(nc.ui.Modal):
def __init__(self, target, case_id, reason):
self.target = target
self.case_id = case_id
self.reason = reason
super().__init__(f"Edit Warning {self.case_id} for {self.target}")
self.reason = nc.ui.TextInput(label="Reason", style=nc.TextInputStyle.paragraph, placeholder="Type here your reason", default_value=self.reason, required=True, max_length=50)
self.add_item(self.reason)
async def callback(self, inter: nc.Interaction):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
current_time = int(time.time())
await cursor.execute('UPDATE warn_system SET reason = ? AND last_edit_time = ? AND last_edit_by = ? WHERE case_id = ? AND guild_id = ?', (self.reason.value, current_time, inter.user.id, self.case_id, inter.guild.id,))
await db.commit()
await inter.response.send_message(content="sucess")```
how could i do this in a simplified form ?:
desc = ""
for x in "stuff":
desc+=x
like [desc+=x for x in "stuff"]
but that doesnt work
EditWarnDropdown they said
Oh my bad wait a sec
any clue?
desc = “stuff”
Both do same thing
i mean
You want a list or the same string
i need help about my discord bot
the same desc string
Yeah that's it then
stuff = [ "hey" , "hello"]
desc = "".join(stuff)
print(desc)
there a print hidden code in the script but i can't find it
could you help me please ?
hidden code
Interesting
i want to find a hidden print in the script
typical nitro code gens
nah
Then just search?
i didn't find
crtl + f
just did it
Maybe wrong scope, what IDE are you using?
And what kind of output do you get
vscode
I mean what does that hidden statement print
Maybe error
nop
then what does prints ?!
or exception
can someone help me?
wait
Is it life's truth ? cause maybe god be doing it
and now u got scammed
you get scammed 💀
Can u show code
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.
then the dev is a stupid ass who like's to disturb the functionality of the world
Dont worry man ill not steal it
tf what does bot do ?
The what
To me it sounds more like "bot that gives free boosts"
values = [["H",30,"Common"],["H",30,"Rare"],["H",30,"Super Rare"]]
desc = ""
stuff = [desc+=str(i),item[0] for i, item in enumerate(values, start = 1)]
print(desc)
what about here then?
Like nitro boosts?
@shell wing do you know how can i find this shitty hidden print
?
ik it was my first rxn as well
Nitro gen bot 💀
NOO
Then
yea the bot manages boosters of the server like their perks and all
Ah
send code maybe
If you post the code we can
Yeah
i put alt accounts tokens in it and it boosts servers
Damn
bro is wilding
just tell me how the person can hide it and i will try to find it mates
Like seriously
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
ah
Just look at #esoteric-python and you will understand there are countless ways to print something without print statement
bruh
Lmao
im not even gonna try seeing other channels than this one.
If u cant provide code how will we tell you what to do
too much knowledge for me atm when im trying to pass my 12th
like ?
just search by yourself then
this isnt ur channel, go #esoteric-python
just drop some technics to print without print statement
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
!e py import io;_ы_ы_ы_=print;_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();_ы_ы_ы_(_ы__("",_ы_([_(__(_(__(____)))) for ____ in "amogus is sus"],key=__ы)),file=ы);print(ы.getvalue())
go to the right channel, #esoteric-python
Sorry forgor
Here you go
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
amogus is sus
Actually this has print
it still uses print and that can be searched with ctrl+f
it's a discord bot 💀
But we can hide it
Just raise
that is breaking the Tos of both discord and this server, + normally dpy doesnt do ghost printing, and as said by exenifix..u can find ur answer in #esoteric-python
@vale wing what about here?
if i were to make such bots....after the buy was done, i'd block that guy
💀
💀 agreed
Nice
nice
Its sus
No print
print(ы.getvalue())
👀
Now
Yeah
💀
!e py import io;_ы_ы_ы_=eval("".join(chr(_ы) for _ы in [112,114,105,110,116]));_ы_=sorted;__ы=lambda ь:1;_ы__=str.join;_=chr;__=ord;ы=io.StringIO();_ы_ы_ы_(_ы__("",_ы_([_(__(_(__(____)))) for ____ in "amogus is sus"],key=__ы)),file=ы);_ы_ы_ы_(ы.getvalue())
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
amogus is sus
Ok that's it
this code gives me actual sus vives
Ok its more sus now
👏
This does seem to be wildly off topic though
i mean tf is that
Yeah sorry about that was just demonstrating how you can print stuff without print and a bit of overenjoyed
so anyway to make this short?
Is there a reason to make it shorter instead of keeping it readable?
well uh
i tried making it so
i could use it in a description of a bot
cause f'{}' doesnt support normal for x in etccc
just wanted to make a smile inventory system work in a embed 😭
I kinda don't get what the output string should look like
well
something like:
1 H
2 H
3 H
or atleast tht's what i wanna do in the description of the embed
M that's like
desc = "\n".join(f"{i} {item[0]}" for i, item[0] in enumerate(items, start=1))```
This is pretty much readable also
i'm trying to make a command based on account age (example 14 day or lower the bot say no and 14 day or higher should say yes) can y'all send me code template?
!d discord.User.created_at
property created_at```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
For determining age you could use like ```py
from datetime import datetime
age = (datetime.utcnow() - user.created_at).days```
anyone here knows telethon and can dm me?
hi, can you help me find an error in the code, everything seems to be correct, but it doesn't work
show the code
and error
@marble nacelle send it here not in dms
also use discord formatting for code
!code
now you know
Nice
yea it was pretty simple, my ass did not understand

thanks to down too
How do u disable a button in discord py?
For a specific user/role *
you cant disable a button for a group of users so they cant click it, you only can disable a button globally or enable globally although you can check in code if user that clicked a button has permissions to click it
PS C:\VSC - Coding> & C:/Python310/python.exe "c:/VSC - Coding/Izu-Discord/main.py"
Traceback (most recent call last):
File "c:\VSC - Coding\Izu-Discord\main.py", line 3, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
But I installed discord_slash commands...
This is outdated library, use latest discord.py or its fork like disnake
better?
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Btw to remove that invalid distribution warning check your site-packages directory and remove all folders with incomplete names like -ip ~whatever etc.
hello
did you mean websocket.connect?
also, you shouldn't use replit for discord bots
and i'm pretty sure replit uses poetry not pip
can u help me fix
did you mean websocket.connect
i already asked that
also, are you just copy pasting code from somewhere else
Hi! I want to get into making discord bots. I've been using auto code for a bit and then I got an old sad computer I can run it on, any suggestions for where to start?
Any way of using Application Commands with COGs through discord.Client?
Or do I have to use hybrid commands?
!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.
install linux on the computer and use systemd to add your bot as a service
hosting on windows is fine but it's not as reliable, unless you use something like windows server
We will not assist with an account generator @graceful ermine
Can someone could help me?
I'm trying to make it where after a user changes their status it logs it as a print message
@bot.event
async def on_member_update(before, after):
if not isinstance(after.activity, discord.CustomActivity):
return
if "vvvc" in before.activity.name.lower() and "vvvc" not in after.activity.name.lower():
duration_hours = calculate_duration_hours(before.activity.created_at)
log_message = f"{after.display_name} took off 'vvvc' after wearing it for {duration_hours} hours."
print(log_message)
def calculate_duration_hours(start_time):
utc = pytz.utc
duration_seconds = (datetime.datetime.now(utc) - start_time).total_seconds()
duration_hours = duration_seconds / 3600
return round(duration_hours, 2) ```
Na for some reason it sent it as a discord invite
bruh
you're in the server tho
huh?
Who wants to make a replit python discord bot with me?
don't use replit for bots
there's a guide on the python discord website explaining why
So install python?
yes
nah
💀
replit is easyer
not really

iv been doing it for 1 year now i got use to it
Who wants to make a replit python discord bot with me?
Then stop replying
anyone think a wakatime command would be fun
what are the differences between all the discord api wrappers?
I've used pycord since discord.py stopped being developed
but it seems discord.py is now back in development, is it better than pycord?
in my personal opinion yes
but there are more beyond just discord.py forks
yeah
(hikari)
so many options lol
the main ones are discord.py, hikari, pycord, nextcord, and disnake
Who wants to teach me how to make my first python bot
do you know python
discord.py is not very beginner friendly
i can help you with python but i'm not helping you with your bot seeing as it was against the discord terms of service
Hello. can anybody teach me code to make my bot access my DMs with others for retrieving data?
what kind of data
if it's some data that has been set by the user you should use a database
When I receive dm from others, I want my bot in my server display that dm in my server.
use an on_message event and check if the message is in a DM
can you check my code if you are available now? I also used on_message event but it didn't catch dm from other users to me.
How could I fix this??
@bot.event
async def on_presence_update(before, after):
if not isinstance(after.activity, discord.CustomActivity):
return
if before.status != discord.Status.offline and after.status == discord.Status.offline:
custom_activities = [
activity for activity in before.activities
if isinstance(activity, discord.CustomActivity) and "x" in activity.name.lower()
]
if len(custom_activities) > 0:
custom_activity = custom_activities[0]
duration = calculate_duration(custom_activity.created_at)
duration_str = format_duration(duration)
log_message = f"{before.display_name} went offline after wearing 'x' for {duration_str}."
log_channel = bot.get_channel(log_channel_id)
await log_channel.send(log_message)
if "x" in before.activity.name.lower() and "x" not in after.activity.name.lower():
duration = calculate_duration(before.activity.created_at)
duration_str = format_duration(duration)
log_message = f"{after.display_name} stopped wearing 'x' after wearing it for {duration_str}."
log_channel = bot.get_channel(log_channel_id)
await log_channel.send(log_message)
def calculate_duration(start_time):
duration = datetime.datetime.now(pytz.utc) - start_time
return duration
def format_duration(duration):
total_seconds = duration.total_seconds()
if total_seconds < 60:
return f"{int(total_seconds)} seconds"
elif total_seconds < 3600:
total_minutes = total_seconds / 60
return f"{int(total_minutes)} minutes"
elif total_seconds < 86400:
total_hours = total_seconds / 3600
return f"{int(total_hours)} hours"
else:
total_days = total_seconds / 86400
return f"{int(total_days)} days"```
presence intent
what about it?
you don't receive any activity data if you don't enable it
Did you turn it on in the code?
Yes
why are you using replit
My vscode is down
when I debug stuff it gives me false errors
Oh no I did not
?
its not possible for a bot to watch other people dmming you, but it can watch other people dmming the bot
hi fawn
not watching. just copy dm from log
what do you mean by log?
do you mean retrieve the DM after it has been sent, or when it's sent?
how would that look like
I made my bot display member count on a server in game presence, but why the member count don't changed when a new member joins?
@client.event
async def on_ready():
server = client.get_guild(guild_id)
playing = discord.Game(f'With {server.member_count} members')
await client.change_presence(status=discord.Status.idle, activity=playing)
print('Presence ready')```
You need to create a loop
The bot would show the member count that was when the bot started
to change the member count as a new user joins, you need to make a loop that checks if a new user has joined or any left after every 10mins or 5 mins
cause if you do it every 5s or so, it's gonna spam the API and get ratelimited
Anyone has the hex code for making embed color transparent?
!d discord.Color.dark_embed
No documentation found for the requested symbol.
i dont think thats the same
which library do you suggest for making a telegram bot?
python-telegram-bot
or something like that, i used it once
how?
thanks
But works tho 💀
async def on_ready():
print('whatever you want') #normal print statement
client.loop.create_task(status_task())
async def status_task():
while True:
server = client.get_guild(guild_id)
await bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f'{server.member_count} members'),
status=discord.Status.online)
await asyncio.sleep(5) #time in seconds
smh like this
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
dark embed or dark message
You shouldn't be changing your presence every 5 seconds btw
ok tysm
change it in mins like and not less than 10min just do be safe
@bot.tree.command(name="add", description="Adds a user to the ticket.")
async def add(interaction, member:discord.Member):
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
await interaction.channel.set_permission(interaction.member, view_channel=True, send_messages=True, read_messages=True)
await interaction.response.send_message(f"{interaction.member.mention} has been added from the ticket.", ephemeral=True)```
no errors, should this work becuase it's currently not?
What does it even supposed to do
