#discord-bots
1 messages · Page 268 of 1
you cant use await in normal function
Can anyone suggest good Instagram scaping libraries?
(Which are legal)
i get this error
make it asynchronous function
- its not related to this channels topic
- no since it breaks instagram tos
async def setup(bot):
await bot.add_cog(CommandHandler(bot))```
you mean like this
try and see
Ah sorry my bad
Oh i get it
error?
@slate swan can you check my github repo if my now
no error in terminal but did not respond to my command
show command code
@bot.command()
async def ping(ctx):
# Calculate message latency
message_latency = round(bot.latency * 1000)
# Calculate message round trip latency
before = time.monotonic()
message = await ctx.send("Calculating...")
after = time.monotonic()
round_trip_latency = round((after - before) * 1000)
# Calculate shard latency
shard_latency = round(bot.latency * 1000)
# Create and send the latency embed
embed = discord.Embed(title="Latency", color=discord.Color.blue())
embed.add_field(name="Message Latency", value=f"{message_latency}ms")
embed.add_field(name="Message Round Trip", value=f"{round_trip_latency}ms")
embed.add_field(name="Shard Latency", value=f"{shard_latency}ms")
await message.edit(content=None, embed=embed)```
and where is that located? inside this cog?
the main file tho
you have message_content intent enabled?
yup
you have to enable it in code too
you have that code on github so i can see it?
how would the best way be to check if an item for my economy bot needs to be used against another player? should i add another column in my database and do research based on that?
ok 2m
Could you elaborate on this?
needs to be used against another player
is this just a boolean value?
like say i have an item that i can use to rob them with a 100% success rate i dont want to use that on myself just another user
yeah if i understood correctly i would add another column to database with boolean type
okay cool thanks for the info
already onto 8 columns about to add 9th
is the discord bot api just a package?
there are packages that are wrappers over a discord API
the most known one in python is discord.py
!pip discord.py
The Discord Bot API is a RESTful web API being hosted by Discord under the https://discord.com/api/v10 URL, you sent HTTP requests there to do different actions (like send message, etc)
But the Discord API is complex and you really don't want to make bots by doing that - so packages like discord.py do the hard work for you and give you a nice, Pythonic interface to interact with Discord
@slate swan https://github.com/kusuta012/Krack
Contribute to kusuta012/Krack development by creating an account on GitHub.
cools
what was the issue again?
no erros in terminal but the does not respond to commands but it does dm that it has been restarted when it passed on_ready event
so there is surely no problem with the message intent
the message_content is not about sending messages its about receiving them
so when you do .ping it wont respond?
why you use bot.start?
instead of bot.run
yea
well indeed the doesen't even dms me for restaed
show full output of the console
ython/Python Projects/discord bot/main.py"
Bot connected to Discord.
Bot logged in as Krack
Extensions loaded successfully
how about you replace ```diff
- @bot.event
- async def on_message(message):
- @bot.listen()
- async def on_message(message):
alright
2023-07-10 22:39:29 INFO discord.client logging in using static token
2023-07-10 22:39:55 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 5a87d0d311e837abe0771d80275e92a4).
Bot connected to Discord.
Bot logged in as Krack
Extensions loaded successfully
GG!
and does the commands work?
YES
cool
thanks a lot i appreciate you help
👍
this is only warning for now does it work when you run it?
you installed what
do pip show discord.py
it wont work still when you do pip show discord.py i want to see output of this command
do python --version
3.11.4
in vs code do ctrl shift p search for Python interpreter and set it to 3.11.4
works
ig i was stuck on the wrong interpreter
alr so whats the basics like say i wanted a simple command that just messages hello world
A hands-on guide to Discord.py
https://fallendeity.github.io/discord.py-masterclass/#creating-a-bot
here is how to get through discord developer portal
A hands-on guide to Discord.py
can we make member selector for modal ?
it is explained below but most likely you want Bot
Yeah you probably want bot
i will
now how exactly do i make the bot active
do i just run the program or is there some extra steps to keep it active
you run the script
but to make it online you have to keep the script running obviously
so if you want the bot to be 24/7 you need some kind of hosting or vps
how do i stop it then
kill the terminal or do ctrl + c while focused on the console
cool
huh ?
i need to make modals with pycord
i found that tutorial on ytb
Learn how to code a Discord bot with context menus using interactions.py (formerly discord-py-interactions)!
In this video, you will:
- Explore the usage of modals
- Code your own modals
- Test them out
- Respond to modals
- and more!
Discord Developer Portal: https://discord.com/developers/applications/
Documentation: https://discord-interacti...
tutorial on youtube explains it all
bruh
thats why pycord is bad it does not support everything
oh
also there are modals in pycord
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
should be but im not the only one who is creating it
add me to friends and ill msg you
oki
Traceback (most recent call last):
File "F:\mesdraps\vouches_bot\main.py", line 29, in <module>
async def feedback(ctx, interaction : discord.Interaction) :
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 887, in decorator
command = Command(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 666, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 374, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 834, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 793, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
import discord
from discord.ext import commands
from discord import ui
from colorama import init
from colorama import Fore, Back, Style
import json
import os, glob
import shutil
import pathlib
config = json.load(open("config.json"))
init()
bot = commands.Bot(command_prefix = "#", intents = discord.Intents.all())
###############################################################################################
class Mdl(discord.ui.Modal, title = "Submit a feedback") :
product = discord.ui.TextInput( label = "Product :",
placeholder = "Mention here the product you bought",
required = True)
@bot.tree.command()
async def feedback(ctx, interaction : discord.Interaction) :
modall = Mdl()
await interaction.response.send_modal(modall)
bot.run(config['bot_token'])
Remove the ctx
alr
i don't find the cmd :
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/#using-commands-and-events im using the example code here but i cant figure out how to add a command
what type of the command?
ah okay
@slate swan could you help with that ?
you did not sync the command tree
how can i sync it ?
oh ok
@slate swan btw can i make an interaction.response.send_modal with a simple prefixed command ?
no cause you get interaction only with slash commands
oh ok
@bot.command()
async def super_command(ctx, argument1, argument2):
...
import discord
from discord.ext import commands
from discord import app_commands
from discord import ui
from colorama import init
from colorama import Fore, Back, Style
import json
import os, glob
import shutil
import pathlib
config = json.load(open("config.json"))
init()
bot = commands.Bot(command_prefix = "#", intents = discord.Intents.all())
@bot.event
async def on_ready():
print(f'Bot Name: {bot.user}')
for server in bot.guilds:
await bot.tree.sync(guild=discord.Object(id=server.id))
###############################################################################################
class Mdl(discord.ui.Modal, title = "Submit a feedback") :
product = discord.ui.TextInput( label = "Product :",
placeholder = "Mention here the product you bought [ EX. : 3 months Server Boosts ]",
required = True)
@bot.tree.command(name = "feedback", description = "")
async def feedback(interaction) :
modall = Mdl()
await interaction.response.send_modal(modall)
bot.run(config['bot_token'])
i cannot even find the slash command lmfao
for server in bot.guilds:
await bot.tree.sync(guild=discord.Object(id=server.id))
``` this wont work
gimme what should i write pls
okk
okay
after that ?
command should be there
slash command you mean ?
yes
mhm
hi, how do i fix this?
how about you do .sync(guild=discord.Object(...))
put in id of your testing server
why dont u try using something like
@bot.event
async def on_ready():
print(f'{bot.user} is now connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"use '!commandshelp' for a list of all the commands!"))
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)}command(s)")
except Exception as e:
print(e)
@bot.tree.command(name="commands")
async def commands(interaction: discord.Interaction):
await interaction.response.send_message(f"This Will be the commands help thingy")
okok
did you create a command named commands
not working
@bot.command()
async def sync(ctx) :
await ctx.bot.tree.sync(guild=discord.Object(1101820707085754519))```
assign it to a varriable and print it out
or just put it in print
yeah...
i just realized that
to print what ?
print(await ctx.bot.tree.sync(guild=discord.Object(1101820707085754519)))
did you run the command?
yeah
it must have printed something
at least empty list []
are you sure the command is being invoked
bot = commands.Bot(command_prefix = "#", intents = discord.Intents.all()) i used this prefix :/
#sync
do #help
so it does print something
yeah just when i used #help cmd
set the description for your slash command
did
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
it takes year month and day but they must be int you have str
huh
yes i for sure can imagine whats the rest of the code
copy pasting random lines from documentation is not the solution
i would learn python basics and then come back to this project
is it possible to restrict one select value in a drop-down menu to a user with a particular role?
what should i know before i make a bot for the first time?
like what is the best thing to use
this might not be up-to-date, but can still be relevant
If you want it to be good, yes
Or if you have an old machine you can use that too
damn i don’t have an old machine to use
hmm
if i run it on the machine im currently using will it explode
discord.client logging in using static token what is this
@warm jackal if im not wrong i think heroku can host it
okay
theres probably some youtube videos that shows you how to set it up and stuff
Traceback (most recent call last): File "C:\Users\Melih\Desktop\discbot\bot.py", line 16, in <module> client.run(TOKEN) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 668, in run return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 647, in runner await self.start(*args, **kwargs) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 611, in start await self.connect(reconnect=reconnect) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 552, 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.
why do i get this error?
please how can i make a slash command discord.Option(discord.Member, "") but to select members with a specific role ?
nvm i fixed mine
Traceback (most recent call last): File "C:\Users\Melih\Desktop\discbot\bot.py", line 5, in <module> from discord.ext import commands File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\__init__.py", line 19, in <module> from .flags import * File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 73, in <module> @dataclass ^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1230, in dataclass return wrap(cls) ^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1220, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 958, in _process_class cls_fields.append(_get_field(cls, name, type, kw_only)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 815, in _get_field raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
hi how can i fix this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
C:\Users\Documents>python script.py
File "C:\Users\Documents\script.py", line 159
return "I apologize, but I don't have the answer to that question at the moment. Could you please ask me something else?"
^
IndentationError: unindent does not match any outer indentation level
bruh my mom got me a rasberry pi and all it has is the power cable
can i even use it
like i have no mini hdmi cables or heat things for it
is there a way to make it so the bot will say any input you give it live, without your inputs appearing?
or using a private channel to type in where the output is in another channel
Hey, im trying to send a auto message but having trouble. Dont know how to start the loop. This is what I have.
@tasks.loop(seconds=10)
async def auto_send():
channel = vini.get_channel(1123454159543357540)
embed = discord.Embed(colour=0x182D9F)
embed.set_author(name="Just Some Subtle Reminders")
embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #┃commands \n \n Learn how to join our team over here #┃how-to-join"
embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
await channel.send(embed=embed, delete_after=60)
why my bot is not getting hosted
Does it work fine when u run it in your terminal?
Call auto_send.start() 🤷
by the token or by the code?
In your code
What do you mean by the token
damn does anyone remember okimii 😔
How do I see the content of a message with Discord.py? Because ```py
print(f'{message.author.name}: {message.content}')
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.
you need to enable them in your code and your dev portal ^
async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
choices = []
for item in self.items_list:
choices.append(self.items_list[item]['name'])
if current:
return [
app_commands.Choice(name=choice, value=choice)
for choice in choices if current.lower() in choice.lower()
]
else:
default = choices[:25]
return [app_commands.Choice(name=d, value=d) for d in default]
async def autocomplete2(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
serverchoices = []
for server in self.sillyservers:
serverchoices.append(server)
if current:
return [
app_commands.Choice(name=choice, value=choice)
for choice in serverchoices if current.lower() in choice.lower()
]
else:
default = serverchoices[:1]
return [app_commands.Choice(name=d, value=d) for d in default]
@ app_commands.command(name="vendingsearch", description="Searches The Rust Server's Vending Machine")
@ app_commands.guild_only()
@ app_commands.describe(item="List of items")
@ app_commands.describe(server="Select a server")
#@ app_commands.choices(server=[*server_names])
@app_commands.autocomplete(item=autocomplete)
@app_commands.autocomplete(server=autocomplete2)
async def search(self, interaction: discord.Interaction, server: str, item: str):
I'm trying to get the "autocomplete" function to work for both "server" and "item" however it doesn't seem to work this way.
When I disable it for server the item autocomplete function works and vice versa.
How can I get it to work for both?
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
You only need the decorator once, and pass two kwargs to it
@commands.command()
async def lb(self, ctx):
gid = str(ctx.guild.id)
if gid not in data1 or data1[gid]['lvl_mode'] != 1: # Checks if ranking system is enabled or not
await ctx.reply("Ranking system is disabled in this guild.")
else:
lb = []
for member in ctx.guild.members:
if member.bot:
continue
else:
id = str(member.id)
xp = data1[gid][id]['xp']
lb.append((member, xp))
lb = lb.sort(key = lambda x:x[1], reverse = True)
embed = discord.Embed(title ='Leaderboard')
for index, (member, score) in enumerate(lb, start = 1):
embed.add_field(name = f'{index}.', value = f'{member.mention} - XP: {score}', inline = False)
Error occured: Command raised an exception: TypeError: 'NoneType' object is not iterable
why am i getting this all the tim
.sort sorts the list in place , just do:
lb.sort(key = lambda x:x[1], reverse = True)
the bot ignores now after doing this
wont throw any error but wont response either
wait nvm
im dumb
forgot to add ctx.send
It doesn't quite work tho. As I said. It'll work properly for 1 paramater but for the second it wont
Did you remove the second decorator?
Yes
It's okay. I figured out the issue. It was my autocomplete code
screenshot of file tree structure
of your project
and the code you run is inside main.py?
it was looking for folder cogs inside venv folder either put the main.py file outside or change the path it should look for
@commands.Cog.listener()
async def on_member_join(self, member):
gid = str(member.guild.id)
with open('logs_data.json', 'r') as f:
data2 = json.load(f)
roles = data2[gid]['role']
autorole = discord.utils.get(member.guild.roles, name = f"{roles}")
await member.add_roles(autorole)
Traceback (most recent call last):
thon311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "_logs.py", line 161, in on_member_join
await member.add_roles(autorole)
File "C\Lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
looks like autorole is None
does the cog get loaded?
show how you defined the commnad?>
and where is this command located?
inside cog class?
show full cog
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.
and how do you know the cog is being loaded

put a print inside constructor
cog constructor
__init__
just print something so we know its being invoked
Is that the print you put in the cog __init__?
ok but did it print whatever you made it to in the cog constructor
sorry what?
you are supposed to put a simple print inside the __init__ thats all
inside the __init__ method of the Cog
And..? What happens
does the print is being printed when you run the bot ..
so the cog is not loaded
show how you load the cogs
show file structure
Wdym new mistake? What did you change?
show this listener
why would you put __init__ inside the Cog.listener()
yes, why would you put it in here
"i changed nothing"
do you know what __init__ is?
then why did you put it the decorator params??
I cant even comprehend that
what do you think it is?
not like construcor is the same name for __init__
..do you know what that means? cause you obviously didnt write that
code
if self.arg == "":
title = "Набор игроков"
``` what if this if will be False
then the title varriable will never be created
Hi,
Can anyone help me?
nope since you are doing a nuke bot
No nuke
how do you know that?
he confirmed that a while ago
Yes, But Now I created New bot
why are you deleting the message in asyncio??
so many nuke bots online yet you come here to make one for yourself
!d discord.Message.delete
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.
How?
yeah it is
delete_after was when you were sending it
Now after 5 seconds
!d discord.TextChannel.send
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
yeah use the delete_after and type in after how many seconds you want it to delete
why i should belive
Bruh
Why Error
what does this mean
Anyway
5
!d discord.Message.nonce
The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.
thats like your own id for the message
yeah then delete those two error line
and one last question
and use this method to send it
your indents 💀
!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...
How this letter after
5 seconds to be deleted
type?
what?
add the delete_after kwarg with your value
is this done automatically?
Yes, bots only send rich embeds
Can you send me an example
await ctx.send(f'your_message',delete_after=5)
Hello I need help I'm a beginner in python, and I'm creating a custom rp system with discord (pypresence). And I made a GUI for the question form. However if the person doesn't put an answer in an entry the code crashes I would like that a person can help me so that pypresence passes if there is not give.
Code of recuperation of data :
id=id_entry.get()
details=details_entry.get()
state=state_entry.get()
party=party_entry.get()
min_party=min_entry.get()
max_party=max_entry.get()
large_img=large_entry.get()
largetext_img=largetext_entry.get()
small_img=small_entry.get()
smalltext=smalltext_entry.get()
button1_label=button1_entry.get()
button1_url=button1_url_entry.get()
button2_label=button2_entry.get()
button2_url=button2_url_entry.get()
This channel is for discord bots
yes but where is channel for this request ?
i dont think anyone will answer you here i worked once with pypresence and still dont know what you are asking for check out #1035199133436354600
Thank you very much ❤️
How to remove this response 🗿
you are asking how to add buttons to view?
here is how to create a confirm button
example
I don't see dismiss message written anywhere
Look await ctx.channel.send("......")
How to add message Response
Check photo look He Said The application did not respond How to fix?
can you show the whole code for that command and any error you getting
Wow wonderful song
instead of doing await ctx.channel.send do await ctx.send
I know that, but I don't want to
display the slsh command
wdym not display slash_command
I mean send channel
Not this
You can make him write something instead
then just send ephemeral to true so that only the person who used the command can see the message
You can do that instead
Write this and I'll write something myself
Yes but how
nextcord
mb didnt check
Can you send me code
its not context tho
pycord 😔
Fixed Right?
its not pycord as well
mb it was nextcord
skull
nor nextcord
nah disnake
its disnake and its GuildInteraction
Fanaly question
the message says so it self who can see it
How to this work?

reading the docs would be a great idea
same as the prev one i guess
This?
it would be just await channel.send(...)
the channel will be None always
yeah i just noticed
I said select channel how?
that is not what you said
Like this
Example
Who uses my command
Send channel private just code send me
I can not comprehend what you're saying
if you want to send a dm use this https://docs.disnake.dev/en/stable/api/members.html#disnake.Member.send
hint u need to put ID as an int
No
thats what i understand as private channel
No
What?
those guys already told you multiple times what's wrong
channel will be None always
You mean remove Id
no i mean read the docs
When did they say that?
Man I have a huge problem with docs discord I can't understand
what part is confusing?
When you used my command
My bot Automatic Send channel private
the current problem you have is with the data type
so you expect everybody to give you code with already solved solutions
I can not read that
that's just random words
Waite
If english isnt your first language, try google translate?
bro you've sent that 3 times now
sending the same screenshot over and over isnt going to explain it
we've already told you the things you need to fix
Whenever they use it, I want you to send the bot to that channel
Like logs
What?
Great 
- channel will always be None check the docs how to provide the channel id to the
get_channelmethod -> https://docs.disnake.dev/en/stable/ext/commands/api/bots.html#disnake.ext.commands.Bot.get_channel - the TextChannel have no such attribute
messagecheck out what attributes it has -> https://docs.disnake.dev/en/stable/api/channels.html#disnake.TextChannel
Man i mean Like logs whenever you use them send them to that channel
we knowwww
.
and the second point from here
did you check the example i sent?
Man just send code
we dont code for you
Whyy
cause thats not how it works
we did 💀
what you dont understand in it
looks like youve ignored all of it
I finally fixed it thanks for your help.
@slate swan @turbid condor
try it out and see how it works
then try to implement it in your case
then go to disnake github
they have examples as well
!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.
the token you passed was None
can anyone assist me with lavalink
os.getenv(key, default=None)```
Return the value of the environment variable *key* as a string if it exists, or *default* if it doesn’t. *key* is a string. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): Unix, Windows.
do you load the environment varriavles?
show code
you have the token in the .env file?
Down, can you help me with lavalink.py
no i never worked with it
D:
How can I disable a discord.ui.button after 60 seconds?
I'm not looking for timeout, but actually to disable it
await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when a view’s timeout elapses without being explicitly stopped.
so where you have it
Where/how? https://paste.pythondiscord.com/qudozukuli
Ignore if self.vote_count >= 1: it's just for testing
when you create View you pass timeout
then you override on_timeout method and disable the button in this method
A hands-on guide to Discord.py
elaborate on "doesnt work"
What am I doing wrong?
https://paste.pythondiscord.com/ogobigobex
nothing it should be working
await self.message.edit(view=self)
AttributeError: 'Counter' object has no attribute 'message'```
ah yes you did not pass message
do like this in your command
view = Counter()
view.message = .send(..., view=view)
Thanks Down
Hey there, when using commands.hybrid_command() how can I check user has admin perms?
either commands.has_permissions or app_commands.checks.has_permissions
not sure which one though
one of those
this is weird
because I've made slash commands, they all work
but then I do the same in my admin.py file
but I get an error message
show the error maybe
Error when logging in: Extension 'cogs.admin' raised an error: TypeError: unsupported parameter kind in callback: VAR_POSITIONAL
yeah sorry I was copying it ^^
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.
The slash commands doesn't except *roles it throws this error
Still get the error though
yes i know it wasnt going to solve it just noticed it
Just make it roles
yeah but isn't it a problem if it's not *roles?
Error when logging in: Extension 'cogs.admin' raised an error: TypeError: unsupported parameter kind in callback: VAR_POSITIONAL
hehe ... it doesnt
ho wait
pff I changed the wrong one
now it works lmao
you have that in two commands
thanks !!
I think his persistent view is not working when he runs it from main.py but when he runs it from confirm.py they work
Tho idk the full story since wasn't involved in the problem solving
what are confirm.py and main.py
is it possible to restrict one select value in a drop-down menu to a user with a particular role?
how tf do i define guild
how to i get the top to read it all as one argument
instead of doing something like
ctx, arg
you do
ctx, *, arg
current code
async def stats(ctx: commands.Context, *, blueprint):
ok ill try that
what tf are you actually trying to get by definig guild?
Hello all. I understand bots do not have access to user's connections, and instead one would need to use OAuth2 and a web application. Would passing the response back to the bot program be against TOS, or, more importantly, would Discord be able to detect this behavior? Already got my account blocked for too many logins with Selenium
how can i check whether there are numbers in a message content?
hi i need help with my telegram bot code... anyone know a server where you can help each other?
try asking in #1035199133436354600
No that should be fine, if you go through the proper authentication flow with Oauth
Can't double check right now but maybe: any(character.isdigit() for character in string)
Thank you!
u can use char.isdigit() to check if a message contains digits or not
like
for char in message.content:
if char.isdigit():```
actually they do
you can use the users api endpoint
/users/@me/connections? Docs say bots will always return None as response, but I actually haven't tried it.
Just trying to get users connected Steam account user ID so I can use for Steam API. It's been a massive headache so I'm open to any suggestions if there's an easier way to do it than OAuth
ive tried it
it returns a lot of info
no just users
ill show u an example wait
Great, thank you
do you know how i coukd get these digits?
you do need a user account token in the authorization headers tho
could use yours
or an alt's
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Busted! I solemnly swear to adhere to TOS. Thank you for ensuring I know what NOT to do!
Beats me, but I'll separate the API call from the bot code to keep it legal lol. Thanks again
self bots are agains tos and helping in such topic here will eventually result in punishment
so its considered a self bot because ur using a user account token
thats exactly what self bot is
@turbid condor
write a function for example
like ```py
def extract_numbers(string):
return "".join(filter(str.isdigit, string))
uhhh
Regex 
i aint explaining how it works this faster
im just wanting to store the number that a user puts in their message e.g. 100 crates, it will store the 100
!e ```py
def extract_numbers(string):
return "".join(filter(str.isdigit, string))
print(extract_numbers("abc123def456"))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
123456
What
ohhh thanks
i would have to say that he needs to import additional module and what it is 
I'm just saying that they can also use regex, but fair, I guess
so im making like a game bot and they can order a purchase with their coins and get crates and stuff, so in a modal ive made it so they can input their order with x20 crate1, x40 crate3, x70 crate3 etc. now i get these values by splitting this order and using the order[0]. however, the order length wont be the same for everyone and so i have to make the order length the same for now. how would i make it so the orderlength can be different and so i can split it and get each part of the order?
no
I was wondering, is there a way to reduce this code by putting the decorator method (with the "@") into the class block ?
import discord
from discord.ext import commands
class Bot(commands.Bot):
pass
bot = Bot(...)
@bot.tree.command(name="hi", description="Greets the bot !")
async def greet(interaction: discord.Interaction):
await interaction.response.send_message("Hi there !")
something like
import discord
from discord.ext import commands
class Bot(commands.Bot):
@Bot.tree.command(name="hi", description="Greets the bot !")
async def greet(interaction: discord.Interaction):
await interaction.response.send_message("Hi there !")
maybe try self.tree.command not sure if that would be valid
also, not sure why you're even trying this in the first place, as you're probably just looking for ways to organize, in that case, check out cogs
cogs ? what's that
the docs will tell you 🙂
and no that wouldn't work since it's out of default methods so there is not self argument
alr thx
yeah, but trying to extend a bot with "default commands" is probably not the way to go
I meant class methods mb
Self bot means using someone elses token/authorisation key for your use?
no this means to use a user account to behave as bot meaning react to commands etc
show code
counter = 0
with open("/home/container/spam.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter+=1
file.writelines(f"{str(message.author.id)}\n")
if counter == 5:```
you are using file when its already closed (outside with block)
so do I do open
instead of with open
Just put it inside with block
put file in the with block?
curr_time = datetime.datetime.now().timestamp() * 1000
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
author_msg_times[author_id].append(curr_time)
expr_time = curr_time - time_window_milliseconds
expired_msgs = [msg_time for msg_time in author_msg_times[author_id] if msg_time < expr_time]
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
if len(author_msg_times[author_id]) == max_msg_per_window:
try:
key3 = f'antispam:{message.guild.id}'
if r.exists(key3):
minutes = r.get(key3)
min = int(minutes.decode("utf-8"))
duration = datetime.timedelta(minutes=min)
await message.author.timeout(duration)
embed = discord.Embed(title="User Muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
print(f"spam detected: {message.guild.id}")
embed.add_field(name="Reason", value="Spamming")
embed.add_field(name="Mute Duration", value=f"{min} minutes")
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"logs:{str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
print(f"spam detected logs: {message.guild.id}")
else:
pass
except KeyError:
pass
``` i have an anti spam thing
but its slow
should my on_message be under all the commands?
you're showing us too little
await first_channel_message.reply(content=None, components=[first_channel_give_button, first_channel_remove_button])
TypeError: Messageable.send() got an unexpected keyword argument 'components'
well, where did you get that code from in the first place?
nvm i am a big idiot
this isnt blocking when a blacklisted word is showing
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
'u coders dont gotta see this'
]
@bot.command()
async def love(ctx, name1, name2):
love_percentage = calculate_love_percentage(name1, name2)
if name1 == blacklistedwords and name2 == blacklistedwords:
ctx.send('try something more appropriate please.')
else:
await ctx.send(f'The love percentage between {name1} and {name2} is {love_percentage}%.')
def calculate_love_percentage(name1, name2):
random.seed(name1.lower() + name2.lower())
love_percentage = random.randint(0, 100)
return love_percentage```
what do you think this means
if name1 == blacklistedwords
?
incorrect
o
oooooh
so instead, you need in
!e
a_list = ["a", "b", "d"]
if "a" == a_list:
print("oeuf")
if "d" in a_list:
print("we're in boys")```
@potent spear :white_check_mark: Your 3.11 eval job has completed with return code 0.
we're in boys
thanks
What's the correct way to defer a slash command?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Defer it before doing anything that will take a long time to complete
So would it be interaction.defer() or interaction.response.defer()?
The second one
No wonder it wasn't working, thank you
Ohh i see thankss
author_id = message.author.id
curr_time = datetime.datetime.now().timestamp() * 1000
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
author_msg_times[author_id].append(curr_time)
expr_time = curr_time - time_window_milliseconds
expired_msgs = [msg_time for msg_time in author_msg_times[author_id] if msg_time < expr_time]
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
if len(author_msg_times[author_id]) == max_msg_per_window:
try:
key3 = f'antispam:{message.guild.id}'
if r.exists(key3):
minutes = r.get(key3)
min = int(minutes.decode("utf-8"))
duration = datetime.timedelta(minutes=min)
await message.author.timeout(duration)
embed = discord.Embed(title="User Muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
print(f"spam detected: {message.guild.id}")
embed.add_field(name="Reason", value="Spamming")
embed.add_field(name="Mute Duration", value=f"{min} minutes")
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"logs:{str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
print(f"spam detected logs: {message.guild.id}")
except KeyError:
pass
this code is delayed then spams the logging_channel.send and the message.channel.send and then it gets like rate limited
it was working fine
then stopped working
well delayed
or maybe my network
What's the correct way of importing a Cog command/s to the main file? Because I get a "The command <command_name> does not exist.
!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)").
The setup function goes inside of the Cog class right?
srry, beginner in Discord bots :v
Nope it's outside
class xyz(commands.Cog):
def__init__(self, bot):
self.bot=bot
#rest of code
async def setup(bot):
await bot.add_cog(xyz(bot))
Oooh, It calls itself automatically when importing the Cog in the main file, right?
@slate swan you need to ask here and not in dms
Yeah when you use load_extension function in your main file
Thanks!
Hello Can Anyone Help me?
You need to be more specific, what is happening? and show errors
you're using the tower1 variable before defining it
"tower1" isn't defined
Bruh
and you can probably shorten that code a whole lot if you use appropriate data structures
is a equal to 1 then?
christ
you really should learn how to use lists and loops
it can be anything between 1 and 3...
hardcoding everything is not a good solution
Which one is wrong?
can you share your code?
I am not fembou
Hello?
It's hard to tell when you have so much hardcoded in
can you share the full trace?
Man i am very tired Can you help me ?
i see
☠️
can you share the extension code?
Check phto
@slate swan
You are defining variables inside conditional statements
.
And this
yea, can you share the code for cogs.confirm
your code is trying to load cogs.confirm though
also if no matter the random outcome, they're gonna be defined the same, what's the point of the conditionals?
Zeffo how to solve typeerror in my bot
learn to type properly
oop 🤣
sure
is confirm an extension
It has a setup function right?
If it only contains classes and you wanna put it as file in cogs then no
show the setup function 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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
It isn't a cog
this is a View not a Cog
what are you trying to do exactly
yes, but why is it in an extension
which part of your code uses that view
so why not just define the view there
in the same file which uses it
By copy pasting that code in the "modal" you are talking about
In the file you are using that class
Where are you exactly calling that class, like where are you using it
You must be creating an object of it somewhere
yes Confirm class
You have created a View
So you are supposed to use it right
You use it by calling the class, like so
view = Confirm()
And pass it in .send(msg, view=view)
If you want to do it in a command then
Eg
@bot.command
async def example(ctx):
view = Confirm()
await ctx.send(somemsg, view=view)
Hello, Anyway Know My bot Just Dm work Why I can't Use Commands In channel But I can Use on dm why?
Confirm should either be imported or copy pasted in that same file
Yes
Is it working now

Your bot don't have the message_content intent
What?
Where is the Confirm class from
Because it doesn't seem like that code is in the same file as the class
No
What??
Check photo
What does that mean
And?
Help me???
Is there any error

With what
The command's name is ask not confirm
Can you help me?
Show your entire code
Anyone HELP ME??
The error literally just told you how to solve itself, read it
WHO??
Re-read my message
Ty
Where is that ask command
Fixed Ty
Where is the ask command
did you put it in that confirm file
Why are you creating two different bots
Copy the Confirm class and ask function and paste them in this file ^
Also import the necessary modules
Right or?
Show what you did
ctx is the context
as for prefix u want to change it?
Yeah, show
I mean command prefix just channel use not dm
Yes
Hmmm so what happens when you try to run commands present in cogs
So it's working now?
There should be a check called guild_only() use that for commands tha you want to be used in guilds only
Can you send me example
For example like this
Async def hi (ctx,guild_only)?
Welp idk about nextcord like how to use checks in that if it's same as dpy then
@bot.command()
@commands.guild_only()
async def hi(ctx):
That's how u do it in discord.py but don't know if it works for nextcord
Fixed Ty man ❤️
For slash commands it would be @app_commands.command.guild_only??
For example
@bot.slash_command
Async def hi (ctx: disnake.GuildCommandInteraction)```
Note i use disnake
is there no way to do with decorator?
i dont
!d discord.app_commands.guild_only
@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
@app_commands.checks.guild_only() or @checks.guild_only()
Just say discord.GuildCommandInteraction
thanks
dm_only
?
doesnt exit
U sure u tried dm_only()?
It doesn't exist
ok
!d nextcord.ext.commands.Bot.slash_command
slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., dm_permission=None, nsfw=False, default_member_permissions=None, force_global=False)```
Creates a Slash application command from the decorated function.
!d nextcord.Locale
class nextcord.Locale(value)```
An enumeration.
oof ok ty
well u want buttons under a message right?
!d nextcord.ext.application_checks.check_any
@nextcord.ext.application_checks.check_any(*checks)```
A [`check()`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.check "nextcord.ext.application_checks.check") that will pass if any of the given checks pass, i.e. using logical OR.
If all checks fail then [`ApplicationCheckAnyFailure`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationCheckAnyFailure "nextcord.ext.application_checks.ApplicationCheckAnyFailure") is raised to signal the failure. It inherits from [`ApplicationCheckFailure`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ApplicationCheckFailure "nextcord.ApplicationCheckFailure").
Note
The `predicate` attribute for this function **is** a coroutine.
no its for me
have u created the button logic?
!d status
Rich can display a status message with a ‘spinner’ animation that won’t interfere with regular console output. Run the following command for a demo of this feature:
python -m rich.status
``` To display a status message, call [`status()`](https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.status "rich.console.Console.status") with the status message (which may be a string, Text, or other renderable). The result is a context manager which starts and stops the status display around a block of code. Here’s an example:
```py
with console.status("Working..."):
do_work()
``` You can change the spinner animation via the `spinner` parameter...
What is wrong?
Unresolved attribute reference 'message' for class 'Counter'
Unresolved attribute reference 'message' for class 'Counter'
Cannot find reference 'edit_message' in '() -> InteractionResponse'
Cannot find reference 'send_message' in '() -> InteractionResponse'
Cannot find reference 'send_message' in '() -> InteractionResponse'
await interaction.response.edit_message(view=self)
await interaction.response.send_message("You can only vote once.", ephemeral=True)
await interaction.response.send_message("You are not eligible to vote.", ephemeral=True)
await self.message.edit(content=None, embed=embed, view=self)
await self.message.edit(view=self)
view = Counter()
view.message = await ctx.send(embed=embed, view=view)```
pycharm?
Yes
I mean, it's giving me errors, but the code is working
yeah they are just some warnings
Cannot find reference 'send_message' in '() -> InteractionResponse'
await interaction.response.send_message("You can only vote once.", ephemeral=True)
Can somebody please help me?
Any errors??
show actual traceback
There is no traceback errors
so whats the problem
The warning messages?
if the code is running it means it works
and as you said they are warnings not errors
try different ide
Looking for dev that can make a discord bot for me dm me for more info if you are interested
Can somebody explain this:
class JoinDistance:
def __init__(self, joined, created):
self.joined = joined
self.created = created
@classmethod
async def convert(cls, ctx, argument):
member = await commands.MemberConverter().convert(ctx, argument)
return cls(member.joined_at, member.created_at)
@property
def delta(self):
return self.joined - self.created
@bot.command()
async def delta(ctx, *, member: JoinDistance):
is_new = member.delta.days < 100
if is_new:
await ctx.send("Hey you're pretty new!")
else:
await ctx.send("Hm you're not so new."```
how is the classmethod ran if I never called it
discord.py calls it
oh so it gets called automatically
what you mean by that?
i mean the commands.Context
oh okay
not needed by default the first is arg is Context
whats the difference between a member and a user?
ty
# This is the button class of xboxreactbutton
class xboxreactbutton(View):
def __init__(self):
super().__init__(timeout=None)
@button(label="Xbox", style=discord.ButtonStyle.green, custom_id="1", emoji="")
async def submitbutton(self, interaction: discord.Interaction, button: Button):
await interaction.response.defer(ephemeral=True)
xbox_role = interaction.guild.get_role(1128348625785847940)
if xbox_role in interaction.user.roles:
await interaction.user.remove_roles(xbox_role)
await interaction.followup.send(f"Added {xbox_role.mention} role!", ephemeral=True)
return
await interaction.user.add_roles(xbox_role)
await interaction.followup.send(f"Removed {xbox_role.mention} role!", ephemeral=True)
# This is inside the command that sends the embed
view = xboxreactbutton()
view.add_item(discord.ui.Button(label="Pre Register", url="link/register"))
await interaction.channel.send(embed=embed, view=xboxreactbutton())
Hey, this is working but it is not showing the url button, only the xbox one, any idea why?
Is the url argument an actual URL
Because I believe it needs to be
it was I just changed it for here
And sorry I just figured it out, I need to do view=view because I am creating a new view variable which has the url button too
It works now
Didn't notice that
How do I prevent the button from delaying timeout after each interaction?
super().__init__(timeout=60)
But every time the button is clicked, it resets the timeout
anyone know the problem?
i think its because i have so many listen events for on_message
make a task which calls timeout and stops the view
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/BFHQ my on_message doesnt work except the first 32 lines
if message.author.id == client.user.id:
return
``` why would you have this 4 times in the same event
https://paste.pythondiscord.com/BFHQ#1L3
remove this line
and instead of @client.event put @client.listen()
wait if i put 1 on top it will still ignore itself?
yes?
oh
https://paste.pythondiscord.com/KNBQ still not doing anything
what does that mean
like the first thing I said
this code is so messy i dont know
only the first few lines work
maybe cause you have so many if else that doesnt make sense
oh
I deleted the the else that I dont need but still not doing anything
anyone else know?
Tbh instead of so many if statements can't u use elif?
And then again your code is too messy can't understand what u are trying to do or achieve
also many of lines look like they repeat or have almost the same logic
I'll suggest him seperating this event into multiple functions or cogs
discord.py 2.3.1 is this the latest version?
!pypi discord.py

is there any open source code example to know when a youtube channel uploaded a video?
for comparison, what mee6 does for example
How can i send a File using Discords API?
https://paste.pythondiscord.com/MUIQ so I put it in different functions but the code here is delayed
its an anti spam
but its like 10 seconds delayed
then after the 10 seconds it spams message.channel.send and logging_channel.send
Hello, Anyway Know How to Just One Rile Can Use slash command?
Sorry?
I want only the person who has role owner to be able to use slash command how
@sick birch
how can i make my bot watch over the chat and have something happen if someone says a certain word
You can go to your Discord server settings and change who can see slash commands:
I believe that restricts only the people you've selected to be able to see it
!pypi fastapi
Bruh what is that
No i know but Code?
Go to Server Settings > Integrations > Click on your bot
I know man
But i mean code
You want it to be done code-side rather than Discord-side?
I mean okay I guess
You can add a check to your slash command: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=app_commands check#discord.app_commands.check
The first example has pretty much exactly what you want
Man he said user.id
I mean role!!!!
Same concept
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_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.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
There you go
Item = id role?
Yes
@decorator
def function():
...
that's the flow
my bot is going well but i need to be able to have either a file or string as a argument but i dont know how to do such a thing
@command()
async def my_command(ctx, argument: text):
...
you can do the same with a file using discord.Attachment as a typehint
# if python 3.10 or higher
argument: str | discord.Attachment
# or
from typing import Union
argument: Union[str, discord.Attachment]
async def stats(ctx: commands.Context, blueprint : discord.Attachment | str):
?
now
now i gotta figure out how discord read it
didnt workj
said the argument was missing
what you try to input
and what was the error you got?
discord.ext.commands.errors.MissingRequiredArgument: blueprint is a required argument that is missing.
hm well looks like you cant mix it up
either create 2 commands one for file and one for text or accept only files/text or try playing with converters
but duplicated code but ohwell
who said you have to duplicate code
me#
now how to convert discord attachment to longgggg string
!d discord.Attachment
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
!d discord.Attachment.read
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
New in version 1.1.
like this ?
no
oh

