#discord-bots
1 messages · Page 191 of 1
the button
@bot.event
async def on_ready():
await bot.setup_hook(main())``` setup hook like this ?
class MyBot(commands.Bot):
async def setup_hook(self) -> None:
# load cogs here
like this you make a subclass of commands.Bot then override setup_hook
can anyone help? ^
class MyBot(commands.Bot):
async def setup_hook(self) -> None:
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')``` so like this
bot = MyBot(prefix, intents = intents, owner_id = owner_id,case_insensitive = True)```
yup now your cogs will auto load
thank you but buttons still not work
you created a new bot file right? can you sent that file entirely
import discord
from discord.ext import commands,tasks
import discord.ui
import json
with open("configuration.json", "r") as config:
data = json.load(config)
token = data["token"]
prefix = data["prefix"]
owner_id = data["owner_id"]
intents = discord.Intents.all()
bot = commands.Bot(prefix, intents = intents, owner_id = owner_id,case_insensitive = True)
bot.remove_command('help')
# Define a simple View that gives us a counter button
class Counter(discord.ui.View):
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='0', style=discord.ButtonStyle.red)
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
number = int(button.label) if button.label else 0
if number + 1 >= 5:
button.style = discord.ButtonStyle.green
button.disabled = True
button.label = str(number + 1)
# Make sure to update the message with our updated selves
await interaction.response.edit_message(view=self)
@bot.command()
async def counter(ctx: commands.Context):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=Counter())
bot.run(token)```
but even when i use the but it says interaction failed
works fine to me can you send the output of pip freeze
1 sec
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
beautifulsoup4==4.11.2
bs4==0.0.1
certifi==2022.12.7
charset-normalizer==2.1.1
cookies-discord-components==3.0.0
discord.py==2.1.0
exchange==0.3
ffmpeg-python==0.2.0
frozenlist==1.3.3
future==0.18.3
idna==3.4
imageio-ffmpeg==0.4.8
multidict==6.0.4
numpy==1.24.1
pycord==0.1.1
requests==2.28.2
soupsieve==2.3.2.post1
urllib3==1.26.14
yarl==1.8.2```
pycord might be interacting with discordpy
how to uninstall with pip
pip uninstall pycord
so i try again
it still fails
so, rn the way i'm implementing string arguments that can only be some strings (like only 'a' or 'b' ) is with typing.Literal
but i've recently learned that using enum works as well
is it a matter of personal preference, or is one generally better than the other?
if you are using venv i suggest you remove it then only remake it with discord.py or if not you should be using venv
whats venv
so in your project folder you can run python -m venv .venv which will create a fresh venv that will only contain basic packages then you can activate it and install what you need
its isolated to that project
https://paste.pythondiscord.com/uvubocusog.py
im tryna make a help command with a select menu and when you choose your option it edits the embed, it works but it doesn't edit the embed
so i will need to install discord.py
yes it will be like a fresh install of python
it will make sure there isnt anything interfering with discordpy
i cant install discord.py
Personal preference really. I personally prefer typing.Literal because it's less of a hassle than using an enum. There's Choice too, which I try to use when possible
how i can install package to a venv
depending on what terminal you are using .\.venv\Scripts\Activate.ps1 that would activate it for powershell
.bat for command prompt
then you install like any other package
python -m venv .venv this creates a venv in the current directory named .venv which will be like a isolated python install
then you can activate that isolated install by using the command .\.venv\Scripts\Activate{.ps1,.bat} then you can install like normal using pip install discord.py
yes only ones you need specific to that bot
yes make sure that you are in the venv when you start the bot
at the start of your terminal you should see (.venv) that signifies you are in a venv named .venv
my vsc says this
that should be fine yes
still not work
well assuming the latest code above is the same then nothing else i can think of would cause that
i just have discord.py isntalled as lib right now
ran basically the same code as above and it works
for me it says interaction failed
did you add the bot with app_commands scope?
That is not necessary if you're using buttons and not slash commands
whats that
well apparently you dont need it but in the url generator you can select applications.commands along side bot which will enable app commands when you invite
i think the scope is separate from permissions
i try 1 sec
it works
just 1 question
can i use buttons in dms ?
@chilly dove
yes you can
Choice?
https://stackoverflow.com/questions/72043793
if you mean this, it seems kinda weird
enter image description here
I need to do like this in discord.py slash command and i dont know how to do
what if there's multiple choices?
would dpy know how to handle that?
!d discord.app_commands.choices they're working on commands.Choice too iirc
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
yeah
wdym?
from what i see, how it works is a decorator followed by a type annotation in an argument
if i want two argument choices, do i just put...two decorators?
could i have an example?
There's an example in the docs
oh uh what i mean is like
if i want two arguments, and each is a choice
not one argument with two choices
@chilly dove how can i add multiple buttons to text
@app_commands.choices(
fruits=[
Choice(name='apple', value=1),
Choice(name='banana', value=2),
Choice(name='cherry', value=3),
],
animals=[
Choice(name='cat', value=4),
Choice(name='birb', value=5)
]
)
? 
you can create upto 25 buttons by using the same decorator over any function in the view @discord.ui.button
okay but how i can use them in dms there it says again error
@chilly dove
class spieler1game(discord.ui.View):
global spieler1
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'SCHERE'
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'STEIN'
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'PAPIER'
class spieler2game(discord.ui.View):
global spieler2
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'SCHERE'
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'STEIN'
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spiler2 = 'PAPIER'
@bot.command()
async def rps(ctx,member:discord.Member):
global spieler1,spieler2
await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
await ctx.message.author.send('Wähle aus',view=spieler1game())
await bot.wait_for("button_click",check=lambda message: message.author == ctx.author)
await member.send('Wähle aus',view=spieler2game())
await bot.wait_for("button_click",check=lambda message: message.author == member)```
i mad it like this
so the code waits for input
await wait()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
where i need to use it
In your button callback
Wait, no
After you sent the message with that view
And call self.stop in your button callback to make it stop waiting
wait is this compatible with prefix commands?
should've asked earlier
Slash commands, that why it's in app_commands module
class spieler1game(discord.ui.View):
global spieler1
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'SCHERE'
self.stop()
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'STEIN'
self.stop()
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'PAPIER'
self.stop()
class spieler2game(discord.ui.View):
global spieler2
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'SCHERE'
self.stop()
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'STEIN'
self.stop()
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spiler2 = 'PAPIER'
self.stop()
@bot.command()
async def rps(ctx,member:discord.Member):
global spieler1,spieler2
await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
await ctx.message.author.send('Wähle aus',view=spieler1game())
await discord.ui.view.wait()
await member.send('Wähle aus',view=spieler2game())
await discord.ui.view.wait()```
fff
so like this
what for an instance
what u mean with instance
sorry first time coding these buttons
and its kinda confusing
@naive briar
i have a discord.Member argument
how do i make it so it defaults to the sender of the message
class spieler1game(discord.ui.View):
global spieler1
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'SCHERE'
self.stop()
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'STEIN'
self.stop()
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler1 = 'PAPIER'
self.stop()
class spieler2game(discord.ui.View):
global spieler2
@discord.ui.button(label='Schere',style=discord.ButtonStyle.secondary,emoji='✂️')
async def schere(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'SCHERE'
self.stop()
@discord.ui.button(label='Stein',style=discord.ButtonStyle.secondary,emoji='🪨')
async def Stein(self,interaction: discord.Interaction, button: discord.ui.Button):
spieler2 = 'STEIN'
self.stop()
@discord.ui.button(label='Papier',style=discord.ButtonStyle.secondary,emoji='📰')
async def Papier(self,interaction: discord.Interaction, button: discord.ui.Button):
spiler2 = 'PAPIER'
self.stop()
@bot.command()
async def rps(ctx,member:discord.Member):
global spieler1,spieler2
await ctx.send(f'{ctx.message.author.name} hat eine runde Schere Stein Papier gegen {member.name} gestartet')
await ctx.message.author.send('Wähle aus',view=spieler1game())
await member.send('Wähle aus',view=spieler2game())```
interaction is failed can someone help
@bot.command()
async def msg(ctx,member : discord.Member):
if member == None:
member = ctx.message.author```
cool
if using normal commands you can use commands.Author
wdym normal commands?
non app commands
oh i'm using hybrid commands
ya should work there too
member: discord.Member = commands.Author
that way it will be the author if none is specified
it look like this right now
not sure what your end goal with that view is but generally you should try to keep the logic within the view rather then some in the view and some outside
i just want to set a variable by click
you should be using bot vars then if you want it global to your bot or if you need it just for command context you can set it on the view
its giving you a interaction failed because you are not responding to the interaction after clicking the button
in the button callback interaction: discord.Interaction has a .response attribute that you must use to respond rather then sending a message through the normal way
yes that will send a message in response to the button click
and how can i wait for a button press
i read about wait bot.wait_for("button_click")
You can change @bot.event to @bot.listen(). Event overrides the place where commands are processed
its because bot.process_commands is overridden from the built in event
cuz how can i wait for a button press
you usually wouldnt wait for a button as the class handles callbacks when you press the button
but i need to wait cause its rock paper scissors
in the docs its called like
discord.ui.view.wait
and in callback u use self.stop
but i dont know where to use this
Hewo guys :)
hey
Any problems?
view=spieler1game() you are creating the view instance here then passing in to send directly without setting it to anything
Ahh like any questions?
you need the instance to wait for that view
All knows regex, me don't, bro someone give regex docs 🗿
I am going to master regex today
if you are doing a game like that tho you should look into robodanny and how it handles prompting 2 players to play minigames
i have an plan
i just wait for a message of the bot
and send a message on response
I just want the Bot To wait for Input from a Button
But this works Fine
Yea so what's the problem
You are using discord.py?
is there a way to set app command default permissions on the parent command of a group cog?
for some reason my bot is not responding to anything
even tho I didnt change anything no commands seem to work
What's the problem then
no commands work. I havent changed anything but when I launch it it launches normaly then when I try using a command it doesnt work
What does doesnt work supposed to explain
No one can know your problem without seeing the code
its too long
oh
it seems to work
!paste
Pasting large amounts of 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.
It was a on_message funtion that I forgot to disable
So @event overrides the internal on_message event and that is where commands get processed but listeners don’t override the internal event
https://paste.pythondiscord.com/uvubocusog.py
im tryna make a help command with a select menu and when you choose your option it edits the embed, it works but it doesn't edit the embed
sup guys, anyone tried to make ai image generate bot via python?
anyone online?
I tried running this code from https://github.com/Rapptz/discord.py/blob/v2.1.0/examples/reply.py and I am getting the following error :
AttributeError: 'Intents' object has no attribute 'message_content' at line 22```
Okay
yeah that solved the issue but now it says that I am not passing the correct token
LoginFailure Error
Then that token is invalid 🤷
but it isnt
Is it a user token
copied from the discord dev portal and made a secret key to hold it
this one
even after resetting the token the issue still remain
here is the code and lengthy issue
!intents - this is not incorrect token error
Using intents in discord.py
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.
intents = Intents.default() is giving an error
undefined name Intents
changing this also didnt help
client = MyClient(command_prefix="!", intents=intents)
Did you even read the embed
yes
actually I was searching if I have enabled privileged initents in developer portal or not
yup I had not enabled them
is it necessary that a bot works in a server only?
Kakarott606
help needed
AttributeError: 'Interaction' object has no attribute 'author'
embed = discord.Embed(title="MrWelcome's Help Menu", color=discord.Color.dark_red()) embed.add_field(name="Prefix", value="**Ping me for prefix**", inline=False) embed.add_field(name="Utility", value="Utility Commands", inline=False) embed.add_field(name="Fun and Games", value="Mini Games", inline=False) embed.add_field(name="Bot Setup", value="How to setup bot", inline=False) embed.set_footer(text=f"Requested By {ctx.author}")
this is a cog
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
check the available attributes there ^
Username of who?
like iam#0979
hmm I’m not sure maybe it is interaction.user
works for me..
I used interaction.user here
embed.set_footer(text=f"Requested By {discord.Interaction.user}")
slash commands?
yes
Send your code
check dm
mhm
ohh
!paste
Pasting large amounts of 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.
dmed
You need an instance
And send the whole error
!d discord.Interaction.user
The user or member that sent the interaction.
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
def get_data(self, stock, start_date, end_date):
for retries in range(0,5):
try:
df = pdr.get_data_yahoo(self, stock, start=start_date, end=end_date)
return df['Adj Close']
except:
print("[ERROR]")
print ('yfinance JSONDecodeError, retyring: ' + str(retries))
print ('ticker: ' + stock + 'start: ' + str(start_date) + ';end: ' + str(end_date) + ';')
return []
@commands.command(name="chart", help="Return stock performance over a period of 2 years time")
async def chart(self, ctx, quo="msft"):
now = datetime.now()
old_year = now.year - 2
current_date = datetime.today().strftime('%Y-%m-%d')
current_date_arr = current_date.split('-')
old_date = str(old_year) + '-' + current_date_arr[1] + '-' + current_date_arr[2]
data = get_data(self, quo, old_date, current_date)
# clear the graph before creating one
plt.clf()
ticker = quo.upper()
# plot the graph and store it in a variable
plot = data.plot(title=f"{ticker}\n Stock Price over 2 years")
fig = plot.get_figure()
filename = 'output.png'
fig.savefig(filename)
await ctx.send(file=discord.File(filename))
async def setup(bot):
await bot.add_cog(Test(bot))
I'm trying to use the 'Cog' function, but I'm studying because I'm not familiar with 'class'. Is the code not working because I didn't type 'self' properly in the code above?
What is the problem
It doesn't work without any error code. if i don't use 'Cog' function, it's working well
I think it's because i didn't properly place 'self' in 'class', but i can't find the cause even though i've been watching basic python lecture videos for 2 hours. :((
Did you load the extension
yeah
yeahh
dont do async def setup
just in main.py
like
`
code...
code...
client.add_cog()
code....
code....
`
ohh
async def load():
for filename in os.listdir('cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
print(f"{filename} Load Successful")
async def main():
async with bot:
await load()
await bot.start(TOKEN)
i using like this but other cogs are working well.
yeah
i think i should put 'self' but it seems that there is a part missing somewhere. so i'm checking.
from cogs.Ban.ban import ban from cogs.Ban.mrban import mrban from cogs.Clear.clear import clear from cogs.Clear.mrclear import mrclear from cogs.Help.help import help from cogs.Help.mrhelp import mrhelp from cogs.Kick.kick import kick from cogs.Kick.mrkick import mrkick from cogs.Ping.mrping import mrping from cogs.Ping.ping import ping from cogs.Roll.roll import roll from cogs.Roll.mrroll import mrroll from cogs.eBall.eball import eightball from cogs.eBall.mr8ball import mreightball from cogs.Unban.unban import unban from cogs.Unban.mrunban import mrunban from cogs.ToF.tof import tof from cogs.ToF.mrtof import mrtof
and then
ohhhh
client.add_cog(ping(client)) client.add_cog(mrping(client)) client.add_cog(help(client)) client.add_cog(mrhelp(client)) client.add_cog(clear(client)) client.add_cog(mrclear(client)) client.add_cog(kick(client)) client.add_cog(mrkick(client)) client.add_cog(ban(client)) client.add_cog(mrban(client)) client.add_cog(roll(client)) client.add_cog(mrroll(client)) client.add_cog(eightball(client)) client.add_cog(mreightball(client)) client.add_cog(unban(client)) client.add_cog(mrunban(client)) client.add_cog(tof(client)) client.add_cog(mrtof(client))
In V2, setup, load_extension, add_cog, ..., all are now async
i wish to unsee this
you can hot reload an extension during runtime, but not an import
hot reload?
add the changes in the cog to bot without restarting it
!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)").
!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.
how to do buttons in discord.py
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
check examples/views folder in the discord.py GitHub repo
What would be the best way to dynamically configure a guild (including categories, channels, roles, all permisions, etc..)?
I currently have a config.yml file similar to @unkempt canyon's src code, but the configs are static, i need a dynamic configuraiton
you;d need a simple database
it's kind of a mix, i dont need a database because the permissions are statically defined in a config file, similar to what roles, channels and categories that should exist, i just need to dynamically create and configure them
Umm making bots in github will be smooth to use?
wdym?
We can making bots in github right? (Discord bots)
github codespaces?
Ye
i mean, sure but you have to pay
💀 anyway to make bots for free? ( im ready to code though )
Uh crep
i mean, i have a vps for $0.97 per month which is where i host my bots
its next to free
so why cant you just pay for a cheap vps?
I just cant cuz in my country we dont have paypal ;-;
you don't need paypal
Credit/dual currency debit cards wont come to help cuz ma parents wont help ;-;
Just use github pages as a host 💀
Oo
wont work
Ik
discord bots needs a server, github pages is not one
Serverless hosts sucky wacky
you could start with using codespaces and running your bot in a docker container and once you hit the limit you'll simply have to wait until you can use it again, but there might be some other free options (im not aware of any that's currently avaiable) but they're usually really bad
otherwise you can just self host
which is probably the best option if done correctly in contrast to other "free" solutions
Oo
Hello, if i want put cooldown on command , how should i do it ?
await interaction.nextcord.ext.commands.Cooldown(5) (f' Slow down boy , this command limitless wait 5mins')
``` Something like this or not even close ?
How can I do a button cooldown?
You should use:
@client.command(name="command_name")
@commands.cooldown(1, 300, nextcord.ext.commands.BucketType.user) # change to your BucketType (Example: guild)
async def command(ctx, .....)
......
@command.error
async def command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
time = int(error.retry_after)
msg = "......"
await ctx.send(msg)
Its actually a decorator
What does this mean? [WARNING ] discord.gateway: Can't keep up, shard ID None websocket is 43.7s behind.
I thing this
@app_commands.checks.cooldown(1, 7200, key=lambda i: (i.guild_id, i.user.id))```
Your bots Heartbeats seem to be delayed
Who's know?
What can I do about it?
You should identify blocking io in your code
!d discord.ui.View.interaction_check | Not sure if there's and abstraction for button cooldowns but you can probably make your own
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
Thanks!
there is no special implementation for button cooldowns so you'll have to write your own, but you can take advantage of the Cooldown object provided by app_commands
https://github.com/Rapptz/discord.py/blob/master/discord/app_commands/checks.py#L76
and if it helps you can see how the cooldown check for slash commands is generated: https://github.com/Rapptz/discord.py/blob/master/discord/app_commands/checks.py#L370
How can I fix this error? discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Int64' object has no attribute 'id'
async def revoke(ctx, case_id: int):```
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
@naive briar
@client.command(name='revoke')
@commands.guild_only()
async def revoke(ctx, case_id: int):
# Check if the command was used in the correct channel
if ctx.channel.id == 745832741135712386 and any(
role.id in [710241598348329080] for role in ctx.author.roles):
collections = [warnings_collection, kicks_collection, bans_collection, mutes_collection]
entries = [await collection.find_one({"case_id": case_id}) for collection in collections]
entry = next((entry for entry in entries if entry is not None), None)
if entry is not None:
collection = collections[entries.index(entry)]
if collection == bans_collection:
banned_user = await ctx.guild.fetch_ban(entry['user_id'])
await ctx.guild.unban(banned_user)```
I think the issue is:
banned_user = await ctx.guild.fetch_ban(entry['user_id'])
await ctx.guild.unban(banned_user)```
fetch_ban takes an abc.Snowflake as per the docs
you're passing Int64
!d discord.Object
class discord.Object(id, *, type=...)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
you can pass the id to this, and then pass this to fetch_ban
You mean like this?
banned_user = await ctx.guild.fetch_ban(discord.Object(id=entry['user_id']))
await ctx.guild.unban(banned_user)```
why are you even trying to fetch the ban?
So I could use this?
if entry is not None:
user = discord.Object(id=entry['user_id'])
collection = collections[entries.index(entry)]
if collection == bans_collection:
await ctx.guild.unban(user)```
yes a discord.Object should work
How do i send a modal in a prefix cmd with ctx
Is it possible to create Slash commands with Discord.py?
Of course
You can't
Unresolved attribute reference 'display_avatar' for class 'Object'
avatar_url = user.display_avatar.url```
You can't display the avatar of a user that is not in the guild?
That is good. Thank you.
well the error says you have an Object and not a User, so presumably you should be fetching the user beforehand?
if entry is not None:
user = discord.Object(id=entry['user_id'])
collection = collections[entries.index(entry)]
if collection == bans_collection:
await ctx.guild.unban(user)
avatar_url = user.avatar_url```
you cant directly show one without an interaction, so the closest workaround would be sending a button/select that sends the modal when its used
so yeah you'll need to fetch the user, and also avatar_url is pre-2.0
Can I fetch user from the object? user = await client.fetch_user (discord.Object(id=entry['user_id']))
you should try getting it first Bot.get_user if not in cache then fetch Bot.fetch_user
i want to make my discord bot send random images from folder but stack overflow confuses me a lot
there is no need for the object tho you just use the id
What do you mean?
get and fetch user takes one positional argument an id thats all you need
user_id = entry['user_id']
user = await client.fetch_user(user_id)```
@chilly dove Do you mean like this?
assuming entry['user_id'] returns a int of the user id yes
the user is usually cached tho so you should try get_user first
if the user they're fetching is banned (as implied by their previous snippet), they probably wouldnt be cached
too bad discord.py doesnt have try_* methods
Thank you
interaction.message is optional
it's only for buttons and other UI things
guys I'm getting started with bots and I don't get what I have to do with intents
intents are certain things that you subscribe to from the discord api, if you subscribe to messages your bot will know when there is a new message
if you don't subscribe, discord will never notify your bot of that
do I need to pass intents to the instance of the client?
yes, there are privileged intents which you need to apply for if you are in over 100 servers or if you are under 100 servers you can just enable them in the developer portal
mhmh
there are also unprivileged intents which you do not have to apply for
you make a discord.Intents object and pass it to your client/bot
to enable all unprivileged intents, you can just do discord.Intents.default()
intents = discord.Intents.default()
client = discord.Client(intents)
TypeError: Client.__init__() takes 1 positional argument but 2 were given
no problem
how similar is the discord.py library to base python. Ive seen some code for discord bots and it looks like a whole new language. is this really the case?
i guess what im asking is how much of my current python knowlage would i use if i were to learn discord.py and make a bot with it.
its mostly objects, decorators, typehints, and at minimum basic knowledge of async/await
also fundamental python stuff
need help
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.command(name='play', help='Plays a song from YouTube')
async def play(ctx, url: str):
# Connect to voice channel
voice = await ctx.author.voice.channel.connect()
# Play audio from the URL
player = await voice.create_ytdl_player(url)
player.start()
bot.run('not telling you')
isnt working
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
guys I pip installed discord-py-slash-command-4.2.1 but still can't import discord_slash
is that not the right module?
the interactions reference explains how to use app commands https://discordpy.readthedocs.io/en/stable/interactions/api.html
how would i go about making a category system where i can assign a certain category to each command independent of its cog and then replace the cog help with category help?
if that made any sense
U csn install em like normal
I’m confused
each command can have a category
and i want to make a help command that filters by category
is discord going to phase out prefixed commands in the future?
They mostly have already
they are trying to do that indirectly
- you can see the slash menu automatically popping up when you use a common prefix like ! ? etc
- message_content intents are strictly unavailable for bots who don't have an actual use for it , things like prefix commands and snipe commands are not one of them...
- slash commands provide features like autocompletes, choices and max_length etc which a prefix command never can (yet another reason to use slash)
it's not like they can just stop you from using prefix commands, but it is what it is
yo sarth can you show me an example with wait_for, like asking for name or something
ofc
ctx: commands.Context
client: commands.Bot/discord.Client
# getting input
await ctx.send("type your name")
def predicate(msg):
if msg.author.id == ctx.author.id:
# compare your condition for the message
return True
# the first message that will match condition and return True will be the value of `response`
response = await client.wait_for("message", check=predicate)
await ctx.send(f"hello {response.content}")
wait_for will take the event name with on_ removed
can you not do it all in one command? without defining a 2nd function
a lambda works just fine
You can put it in a lambda if it's relatively simple
check = lambda msg: msg.author == ctx.author
if your check does complex logic you might want to consider extracting it out into it's own function
What does the check do exactly? I just want to accept user input for multiple statements
i wanted to write comments for explaining so used a normal function
this just checks that the person who invoked is the same as who responded right?
yes
well long story in short, wait_for waits for the event you mention in first argument ( message being the case here ), when the event gets dispatched, the function returns the arguments of the event.. the check is used to make sure which event you want to collect with a condition
So it doesn't pick up a completely unrelated message from someone else in a different server
why not just ```py
def predicate(message):
return message.author == ctx.author
^
client.command()
async def name(ctx: discord.Context) -> None:
await ctx.send("What's your name?")
check = lambda msg: msg.author == ctx.author
response = await client.wait_for("message", check=check)
await ctx.send(f"Your name is {response.content}")
Something like this?
yep that should work
and so I can accept multiple different variables just reuse the same check and change the response?
what is the point of doing
if ...:
return True
at the end of the function
there can be more complex comparisons, i wanted to type the
# the first message that will match condition and return True will be the value of `response`
comment seperately
yes the check can be used multiple times
and I'd have to change the response variable so it's not overwriting right?
you'll have to reassign the variable for a new input ( i.e use wait_for again)
okay thanks, I thought so
How does one use reactions as buttons in embeds for pagination?
Like when click on a reaction, it changes the page
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
to an extent. Because they are restricting message intents. Of course, if you need them, u can get them.
Thx
Wdym category
Do u mean an autocomplete function
do they plan to phase em out entirely?
when i invoke my help command it shows all of the categories and the commands within that category
i guess in theory you can subclass Command, add a custom "category" parameter, override the add_command()/remove_command() methods to maintain a mapping of categories to commands, and then use a custom help command implementation that checks the category mapping
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
the **attrs adds the provided attribute to your commands.Command class, you could use that maybe
those attrs are passed to the constructor, not just assigned as attributes
there is an extras parameter you could use instead of the command subclassing, but the extras stuff feels like a hack
oh right thats' related to the cls
the Command class is not slotted, so in theory assigning the category manually can work as well
No, I dont believe so.
Can u send a screenshot
so they're just going to nerf them & be done with it?
Not unless Discord wants to remove the ability of sending messages
In which case, it wouldn't really be a chat app anymore, would it 😛
Alright, so u can make help a group and have a subcommand for all those things.
@slate swan How do you do buttons that never timeout, like infinitely clickable by everyone
Pass in timeout=None to the View
no
i think there is an easier way
how can I use buttons without subclassing view
Why don't you want to subclass View?
I have a lot of if statements and I think it'll be easier if I don't
I don't see how an if statement affects your ability to subclass something
So I have if statements that decide whether an embed field is added or not, and I'm not sure how I'd do it within the subclass
You pass required state down the "tree", so to speak
The root starting at your command callback and your leaves ending up at your individual component classes
could you show me some psuedocode?
def function(...):
...
view = View()
view.my_button = discord.ui.button(label = "My Button")(function)
like this maybe
Don't think so?
why not?
there is no difference between instantiating a subclass and instantiating View directly
@sick birch ?
This sort of code is generally not recommended, even if it works
Good evening, I would like to create a command to make a kind of image gallery. I would like when members type the command they can attach an image with a title and description. and that everything is sent as an embed. I would like to know if this is possible. THANKS
Yeah that is possible
how to?
it's not possible to have multiple images within an embed, i don't think
i search a tutorial ...
@slate swan
class MyView(ui.View):
def __init__(self, response: str) -> None:
super().__init__(...)
self.response = response
@ui.button(...)
async def my_button_callback(self, interaction: discord.Interaction, _) -> None:
await interaction.response.send_message(self.response)
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
view = MyView("Hello, world!")
await ctx.send(..., view=view)
Here's an example of passing state down
only thumbnail and set_image yea
so why did you say it was possible?
Difficult, but possible, yes.
You can create an embed that shows an image, and have buttons that let users manuever around
I thought he meant one image then multiple embeds?
my fault
i dont understand
so, i'd add the if statements within the class? Cause I only want the button to appear if the other if statement is satisfied
when you say users manuever around
he means pagination
you can do whatever you want with response
Yes, and pass down the information the if statements depend on
if self is in scope
wow
you wouldn't be able to use it in the decorator
is there any tutorial for this?
creating your own pagination is pretty advanced, there are libraries for it though I believe
it is
it's not really advanced, you can do it in 30-35 lines of code maybe
how so?
a good pagination with a class and everything I don't think so
I am a beginner
yes you can, it's as simple as storing a list of messages and then whenever a person clicks on a button you update the index in that list
i'll write it right now as an example
I mean one I did was 100 lines
you need to create multiple embeds ```py
embed1 = discord.Embed(title="same title",url="same url")
embed1.set_image(...)
embed2 = discord.Embed(title="same title",url="same url")
embed2.set_image(...)
await send(embeds=[embed1, embed2])
that's how twitter embeds work
yes but it was in one embed
it will be in one embed....
here, response is what? the message content?
ill show an example, waitup
Yes
I think I'm over complicating this lmao
Probably
I don't think it's in my capacity to do that after all. shame
class PaginatedView(discord.ui.View):
def __init__(self, messages, index = 0):
self.messages = messages
self.index = 0
@discord.ui.button(label = "Next")
async def next(self, interaction, button):
if index not in range(len(self.messages)):
return
index += 1
await interaction.message.edit(messages[index])
await ctx.send(messages[0], view = PaginatedView(messages, 0))
here is a simple pagination example, it may be incorrect but you get the point
only 12 lines
How can I pass my variables within the command to the class? add them as self to the class then args to the command?
That's what I showed you in the example
the variable is in self
you use self.response to access it
this linux? 😍
yesir
respect
im on ubuntu rn got arch on my laptop
@sick birch what does self.stop() do?
Stops listening for inputs
Okay
thanks
can you get guild name from ctx? Like ctx.guild.name
yes
hi
Hi c:
Now that I'm reading it, it doesn't really help my problem
What I want is, instead of using the ui buttons, use reactions to control the page instead. For example
why
buttons are a much better ux than reactions
i agree
Will check this out thx
you should use buttons though
Because I wanna use an emoji to edit a message how I want it
buttons do the same thing though
why a reaction?
they're quicker and they're faster to send (reaction ratelimits)
buttons work with emojis too...
you can add the emoji to the button 🤷
!d discord.ui.Button the emoji kwarg
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
@tawny junco
But then there's a big box around the emoji. I think the single reaction emoji looks best for what I'm trying to do. Don't get me wrong, I use buttons for another embed. This time I wanna use an emoji
Also this is for learning experience. If i don't like it I'll just remove it
I'll suggest discord-ext-menus
or make your own custom paginator
it will involve wait_fors for reaction_add/remove event
Reaction-based pagination is also considerably harder to make than a simple button pagination
i have suggested ext.menus
I don't care really about difficulty, just wanna do things the way I want it 😂
Yes〜 indeed you have. Ty
Fair enough ¯_(ツ)_/¯
I see
how do i disable a button from another method inside the view?
!d discord.ui.View.children
property children```
The list of children attached to this view.
this will give you all components in the view, check your button and disable it
or self.button_callback.disabled = True should work too
im not too sure of this one
Hey, this bot uses it the way I wanna use emoji!
The bin emoji! However mine won't be a bin
Will my reaction look like that too? 🤔
Yes
https://gist.github.com/InterStella0/454cc51e05e60e63b81ea2e8490ef140
you might be interested in this
A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md
but nvm this is buttons
so you're not doing pagination
you're just making a button to delete the message?
Noo
It's for pagination
There can be more than 1 reaction my friend
But it's only gonna be 1 emoji
I have a bot that translates using google translate's api. I want a single reaction button to show pronunciation. That's all
I would basically flip to the pronunciation page
Is what I imagine
and then flip back?
Yes
!d discord.Client.wait_for and Message.add_reaction is what you're probably looking for then
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**...
It works with embeds right?
Any
Sure
it's pip install discord-ext-menus
def set_index(self, index: int):
if not 0 <= index < len(self.embeds):
return
discord.utils.get(self.children, custom_id = "previous").disabled = (index == 0)
discord.utils.get(self.children, custom_id = "next").disabled = (index == len(self.embeds) - 1)
self.index = index
the buttons won't be disabled and i know discord.utils.get returns the correct button and the conditions are correct
You have to edit the message once you've disabled the buttons. Simply setting disabled to True/False won't make them actually (un)clickable
yeah but im updating the message right after
wait nvm
i forgot to put view = self so it was still using the original view
anyone have any tips to make this look cleaner?
it's currently used like this:
paginator = Paginator(embeds)
await paginator.start(ctx)
What’s the recommended way to exit a function, like if a condition is met exit out of the function and don’t continue
return?
Thought so
Question for those that are regulars in this channel: what sort of common pitfalls or gotchas do you see discord bot developers stumble with? My current list includes:
- Message content intent
- Bots not responding to commands
I'd like to be able to expand this 🙂
parsing commands using message content lol
following old/outdated youtube tutorials
removing the default help command instead of just subclassing it
doing anything in on_ready
This is a good one I didn't think of, thanks!
Oh, if any of you want to help with any of these mentioned issues I have oppurtunities open (see #dev-contrib ) 🙂
Variable access.
unmaintained 3rd party libraries for slash commands and components that many YouTube videos promote
difference between object types and instances, pretty common mistake people here make imo
class inside class 
so the wait_for command only ends and goes to the new line when the check is True?
Wait_for waits until the next event is received
or the block timeouts
it timeouts with an TimeoutError exception
Also, variable reassignment. How reassigning a reference not belonging to that instance won’t reassign the instance even tho it’s a reference.
!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**...
.bm good ideas for tags start here
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
Is it safe to do a while loop?
there's nothing specifically much wrong with that
Like
while True:
wait_for ...
since thats the only way you'll do within the command
So I assume after the event is complete it would loop and reset any specified timeout time right?
indeed
i didn't have any good reason to keep it that way so i made them their own classes and separated them into their own file
is it possible for a bot to get an emoji from a server they're not in
other than using the discord cdn
i want to steal the python discord online and offline emojis
!server
!d discord.PartialEmoji.read uses the cdn but its pretty much what you need
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
how do i get the partialemoji
oh i can probably get it from a converter
apparently not
!d discord.PartialEmoji.from_str
classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").
The formats accepted are...
i get partial emoji is not a custom emoji
did you pass in the escaped form?
yessir
ok
*name:id
the usable formats are listed here
now i get an error reading it
wrong paste
don't know how to paste stuff from this terminal tbh
this is not a common error hm
@commands.is_owner()
@commands.command(help = "Steal an emoji from another server.")
async def stealemoji(self, ctx: commands.Context, emoji):
emoji = discord.PartialEmoji.from_str(emoji)
print(emoji)
await ctx.guild.create_custom_emoji(
name = emoji.name,
image = await emoji.read()
)
you could just typehint your emoji argument with discord.PartialEmoji instead of that
that error happened because you're using from_str, so there isnt a connection state provided, the partial emoji converter should give you the state for the emoji.read
discord.py being a weird one again
just use image= await bot.http.get_from_cdn(emoji.url)
( thats what read uses internally)
discord/asset.py line 87
return await self._state.http.get_from_cdn(self.url)```
🚶 reasons why i don't regret switching from dpy at all
i tried that
hold on
it can't convert status_online:470326266625785866 to partialemoji

the bot isn't in the server btw
and where do i get emoji from
i only have a string to work with
weird it should use the same regex as the partial emoji from str
actually, i can supply a url
ok it worked finally
@commands.is_owner()
@commands.command(help = "Steal an emoji from another server.")
async def stealemoji(self, ctx: commands.Context, emoji_id):
emoji = await self.bot.http.get_from_cdn(f"https://cdn.discordapp.com/emojis/{emoji_id}.webp?size=128&quality=lossless")
await ctx.guild.create_custom_emoji(
name = emoji_id,
image = emoji
)
this is what i had to do
i need help
ok
why when i put my openai api key in a .env file it does not detect it and says i need a the key
partialemoji doesnt really depends if the bot is in the server or not, the converter apparently requires you to set <emoji_name:emoji_id> thats why it didnt work for you for emoji_name:emoji_id
api_key =os.getenv("OPENAI")```
blame @slate swan
openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.
and it gives this error
when i tried using it with the angle brackets it converted it to an emoji
not related to discord.py
its in my discord bot
that doesn't relate it to discord.py
oh, so why not just discord.Emoji | discord.PartialEmoji for your typehint 
blame @discord cuz it changes <:name:id> to :name: for no nitro users
sorry, i didn't mean emoji i meant emoji name
when i typed <emoji_name:emoji_id> it converted it to :emoji_name:
it wouldn't have worked anyway since i am not in the emoji server either
thats y I suggest from_str
!d files
Distribution files
You can also get the full set of files contained within a distribution. The files() function takes a Distribution Package name and returns all of the files installed by this distribution. Each file object returned is a PackagePath, a pathlib.PurePath derived object with additional dist, size, and hash properties as indicated by the metadata. For example...
@slate swan is it possible to make my own command deco? Like that checks if server owner.
custom checks yeah
!custom-checks
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
yes
Thx for the help guys! Everything works fine
The error pretty much says how you can fix it 😃
i wish errors could fix themselves
"Error occured while attempting to fix another error"
attempting to turn my bot on and it doesnt do anything, no error codes either
`import bot
def run_discord_bot():
print("Running the Discord bot...")`
Process finished with exit code 0
i have
@client_event async def on_ready(): print(f'{client.user} is now running!') in my bot.py file
so console shouldnt be ending in Process finished with exit code 0
I would suggest to look at discord.py examples
made a seperate python file called bot.py
show it's code
you're not running the Bot from what you've sent
yeah
one sec
!paste
Pasting large amounts of 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.
do you know python's OOP? you're not creating a client instance, also the client will not run if send_message isn't called and client.run is a blocking call, everything below it will never run so it's useless how you're wrapping it inside a function
I would suggest to look at the example that I sent
That's an abomination
Holy crap.
I want to make one to ten command but whether i win or lose it should send a message but i expected this
But reality hits me hard
Here's the actual code if you ask me
@client.command(aliases=['ott'])
async def onetoten(ctx):
number_1 = ['1','2','3','4','5','6','7','8','9','10']
number_2 = ['1','2','3','4','5','6','7','8','9','10']
embed=discord.Embed(title='One To Ten', color=0xe0f9ff)
embed.add_field(name='Your Number', value=(random.choice)(number_1), inline=False)
embed.add_field(name='Bots Number', value=(random.choice(number_2)), inline=True)
if number_1 > number_2:
embed.set_footer(text="You Win!")
if number_1 < number_2:
embed.set_footer(text="You Lose")
await ctx.send(embed=embed)
len(number1) , len(number2)
I hope this works
I'm just fixing the code itself. Idk what you want.
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
I'm trying to make one to ten command whether i win or lose the footer of the embed should say "you win" or "you lose"
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
the embed doesnt edit for some reason
but everything else works
the help command doesn't even show up now
I am new to discord.py bots coding. I need a code that will register slash commands for the discord.py bot
minutes = random.randrange(1,4) and asyncio.sleep(minutes) not working together .. why ? Cuz im trying to make a command which is like slap, player get's permission edit on send messages , but after time permission not setting back
How is it not working?
Show your code for setting perms
if chance > 3:
await asyncio.sleep(minutes)
embed = nextcord.Embed(description = f'{interaction.user.mention} smeigė gerą bankę į {user.mention} užverdamas jo kakarynę {minutes} min. {random_piso}') #user.mention
random_piso = random.choice(nupiso)
await interaction.response.send_message(embed = embed)
#await interaction.response.send_message(f'{interaction.user.mention}Užsimojo')
await channel.set_permissions(interaction.user, send_messages = False)
#await interaction.channel.send(f'{interaction.user.mention} smeigė gerą bankę į {user.mention} užverdamas jo kakarynę {minutes} min.')
if chance < 3:
random_uzsipiso = random.choice(nusipiso)
random_prasileido = random.choice(text_kai_nusipiso)
await asyncio.sleep(minutes)
embed = nextcord.Embed(description = f'{interaction.user.mention} Užsimojo į {user.mention} bet {random_prasileido} ir sukrito {minutes} min. {random_uzsipiso}') #user.mention
#await interaction.channel.send(f'Bandė jobint į {user.mention}, bet {interaction.user.mention} {random_prasileido} {minutes} min. {random_gif}')
#await interaction.response.send_message(f'Nusiplake')
await channel.set_permissions(user, send_messages = False)
maybe should i add two more lines like this ```python
await asyncio.sleep(minutes)
await channel.set.permissions(user, send_messages = True)
anyone knows why when i react to this msg doesnt work?
do you get any errors?
I try in private message but doesnt work
so how can i use this
Why sometimes command just not working ? In concole printing , but in discord just red text
discord isn't receiving a response to the interaction so it flags the slash command invokation as failed
maybe share your code
so I could tell what's the problem
@glad cradleI shared already, its at the top of messages
the second condition is bad indented plus you're not handling possible cases where chance is 3
it would be better if you upload the full code snippet
!paste
Pasting large amounts of 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.
@glad cradle It should be something like that: If i write command slap and mention person, if im lucky im knocking down mentioned person with 1-4min mute, if not lucky i should get mute from 1-4 mins , and it should respond with random GIF's . But cant make it working . But mute should be send_message = false not role
why you let the Bot stop the command execution for 1-4 mins? that's not how you mute members
It should change only permissions for Send_message for 1-4 mins
But that command removing send message option for both
dont understand why it doing it
ok but you're not doing this
you're:
- picking random numbers
- sleeping for 1-4 mins
- editing the channel permissions
you should first edit the channel permissions later sleep and then re-edit channel permissions
though I don't think this is really ok
But other thing, both getting channel edit permission
if im typing command , im getting aswell
https://prnt.sc/ztj3TFOHxSMN Someone can tell me who's blocking gif appear ?
random_sukrito = random.choice(random_gif)
random_prasileido = random.choice(text_kai_nusipiso)
random_praleido = random.choice(random_gif1)
random_pistelejo = random.choice(text_kai_nupiso)
if chance > 3:
embed = nextcord.Embed(description = f'{interaction.user.mention} {random_pistelejo} {user.mention} atjungė {minutes} minutėms. {random_praleido}') #user.mention
await interaction.response.send_message(embed = embed)
await channel.set_permissions(user, send_messages = False)
await asyncio.sleep(minutes*60)
await channel.set_permissions(user, send_messages = True)
if chance < 3:
embed = nextcord.Embed(description = f'{interaction.user.mention} Užsimojo į {user.mention} bet {random_prasileido} ir sukrito {minutes} minutėms. {random_sukrito}') #user.mention
await interaction.response.send_message(embed = embed)
await channel.set_permissions(interaction.user, send_messages = False)
await asyncio.sleep(minutes*60)
await channel.set_permissions(interaction.user, send_messages = True)
GIFs don't load in embeds, except if it's was set by set_image
🤷
It needs to be a valid image URL
How valid url looks like ?
That directly points to an image
but i put directly link
If you click on tenor links, do you see only the image and nothing else?
Yesterday was working allg
Then why it isn't now then
where do you guys run your bots? Are there any free services except Heroku and Replit?
i will check it out
tnx
I use my old raspberry pi
Very powerful
Practically free
I just noticed that PyPi says python 3.8 | 3.9 | 3.10, it won't hurt if I use discord.py with python 3.11 right?
which is rare
i use with 3.11
Also it gives many erros with 3.8
its 3.9 3.10 and so on
ok cool
can someone help me w my discord bot code
i thought dpy 2.0 still had support for python 3.8? what kind of errors were you seeing?
dont have to ask, just share enough information for someone to help
Is this still a good doc on how to create a bot with slash commands on dpy? https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
Or is there a better one out there? Cause I feel like something might have changed since this gist's release
So I want to make a key system, I already made the code. I just can't figure out how do I code it so that it will remove the "buyer" role.
Code:
dont remember tbh
i dont py 3.8 atm
so i cant test, it was on a virtual machine
PyPi says that it does support 3.8
i might be wrong then
i remember having error, it could be 3.7
think before speak 😓
well, 3.8 is old either way
still seems fairly accurate, though it doesnt mention the other stuff it didnt cover like transformers
transformers 😳
also this
you can have a background task or a loop that goes through redeemed keys, checks if they're expired, and removes the role from the member, you'll just need to store the guild id, user id, and expiration in your database
!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").
if you scroll up that you'll see recipes on how to use it
How do I do that 😭
I think it's just Im pretty sleepy :D
i just pointed out the tasks.loop() decorator, thats one way to handle it
uhh
btw pymongo is a synchronous/blocking library so its generally not what you should use in a discord bot, motor is an asynchronous wrapper for mongodb
Can I just send my replit thingy
okay guys, now gifs in embed messages working, but why link not dissapearing ?
What's going to happen when you pass nothing on tasks.loop deco? 
discord/ext/tasks/__init__.py lines 765 to 769
def loop(
*,
seconds: float = MISSING,
minutes: float = MISSING,
hours: float = MISSING,```
`discord/ext/tasks/__init__.py` lines 739 to 741
```py
seconds = seconds or 0
minutes = minutes or 0
hours = hours or 0```
Do you have an extensible bot core that can be reused across projects with supporting documentation?
How about CI/CD deployment pipelines for your production server?
People overlook these way too often in favor of new features
what you mean?
Like this
which file?
All of em
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
does anyone know what part of this i'd need to include if i want to catch the error in a try/except
are you just interested in handling the error in a specific command, or generally handling it across all commands?
if its the former you'd be try/excepting discord.Forbidden, latter would also involve unpacking the CommandInvokeError within your on_command_error event handler
i think just this one, it happens if someone has their DMs closed and I just want it to try and send the DM to someone, and if they don't have their DMs open then stop everything and send a message out saying which user has them closed
"which user"? is it just DMing 1/2 members, or many members?
it DMs multiple people
and is it for announcing something? if so just pinging them in one message would be more ideal, since you dont want to trip discord's anti spam
for what i'm using it for i don't think that will be necessary
thank you though, this fixed what i wanted it to
can anyone suggest some features for my discord.py
@client.command()
async def userinfo(ctx, member: discord.Member=None):
if not member:
member = ctx.author
embed = discord.Embed(title='User - {}'.format(member), description=f'ID: `{member.id}`', color=0x00ff00)
if member.joined_at:
embed.add_field(name='Joined to server:', value=member.joined_at.strftime('%Y-%m-%d %H:%M:%S'), inline=True)
embed.add_field(name='Created at:', value=member.created_at.strftime('%Y-%m-%d %H:%M:%S'), inline=True)
roles = [role.mention for role in member.roles if role.name != '@everyone']
if roles:
embed.add_field(name='Role:', value=', '.join(roles), inline=False)
user = await client.fetch_user(member.id)
banner = user.banner
if banner:
embed.set_image(url = banner.url)
await ctx.send(embed=embed)
How to make it show information such as: User, ID, created_at, banner if the person has it when it is not on the server
lack of ideas/features to implement (seeing this more and more recently)
hi
true
i finallly fixed the problem i was having with discord bot
not it's finallly workin
'
!intents
Using intents in discord.py
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.
Is it possible to have more than 25?
anyone got some cool discord bot ideas?
I need more than 25, but it gives me this
i see, well, i added it. But how do i initiate client.run using intent?
finally, it's working. My baby get life

you can't, alternative would be using autocompletes
Is there any good bot example out there? I would like to know how I should organize this :')
you mean some open source discord.py bot?
Yes
@unkempt canyon :https://github.com/python-discord/bot
R.danny ( made by discord.py's developer ): https://github.com/Rapptz/RoboDanny
Tysm, I'll take a look thx
give me ideas
if you're new to discord.py robodanny might be better than python for reference
it's more simply written
red is nice but pretty much overcomplicated
i like the cog system
hey i am coding a discord music bot and i am getting this error on my play command someone can help me
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: FFmpegAudio.init() missing 1 required keyword-only argument: 'args'
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegAudio(source=url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))```
if it's a youtube music bot then we can't help
it is
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
good evening, I don't understand my mistake, I don't know what's wrong
@commands.command()
async def galerie(self, ctx, ID=1072237400547409971):
channel = self.bot.get_channel(int(ID))
if channel is None:
await ctx.send("Je ne trouve pas ce salon...")
return
message = await channel.fetch_message(channel.last_message_id)
if len(message.attachments) > 0:
attachment = message.attachments[0]
if attachment.filename.endswith(".jpg") or attachment.filename.endswith(".jpeg") or attachment.filename.endswith(".png") or attachment.filename.endswith(".webp") or attachment.filename.endswith(".gif"):
self.image = attachment.url
elif "https://images-ext-1.discordapp.net" in message.content or "https://tenor.com/view/" in message.content:
self.image = message.content
embed=discord.Embed(title=(message.content))
file=self.image
await ctx.send (embed=embed, file=file)
Command raised an exception: AttributeError: 'str' object has no attribute 'to_dict'
what's the self.image var
this is the image that I got from the id of a message
@slate swan
a url is not a file....
self.image = attachment.url
``` -> ```py
self.image = attachment.to_file()
!d discord.Attachment.to_file
await to_file(*, filename=..., description=..., use_cached=False, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").
New in version 1.3.
i resolve it with ```py
image_upload= attachment.url
embed=discord.Embed(title="blabla", description="blablabla")
embed.set_image(url=image_upload)
await ctx.send (embed=embed)
now all i have to find is get the message count and display that count in the title of the embed
@slate swan dont know if you've done it yet but you should reset your token since its revealed in one of your screenshots
holy shit
fixed
thanks for warning 😁
Did you finish ur neovim config
u mean my theme
no it's only for obsidian
please how to count the number of messages in a channel?
Thx u!
I think it was channel.history
i never used it...
42,091
328,082