#discord-bots
1 messages Β· Page 201 of 1
i spammed it to much it sends over 25 images a min
been running since he helped
no restarts nothing
2 hours then
stop as in pause
your bot won't even respond to any commands while that request is happening
Hey, im having trouble accessing and api endpoint and i really need help, its urbandictonary API. ```py
@commands.command(
name = "urban",
description = "Gets the definition of a word/slang from Urban Dictionary",
aliases = ["urbandictionary", "urbandict"],
usage = "Syntax: ,urban <message>\nExample: ,urban skidding",
arguments = "message"
)
async def urban(self, ctx, *, word=None):
if word is None:
await ctx.invoke(self.bot.get_command("help urban"))
try:
async with ctx.typing():
async with aiohttp.ClientSession() as cs:
async with cs.get(f"https://api.urbandictionary.com/v0/define?term={word}") as x:
f = await x.json()
for i in range(len(f['list'])):
try:
embeds = []
embeds.append(
discord.Embed(
title = f"{x['list'][int(i)]['word']}",
description = f"{x['list'][int(i)]['definition']}",
color = utils.color
).add_field(
name = "Examples",
value = f"{x['list'][int(i)]['example']}",
inline = False
).set_footer(
text = f"π {x['list'][int(i)]['thumbs_up']} - π {x['list'][int(i)]['thumbs_down']}"
).set_author(
name = ctx.author,
icon_url = ctx.author.display_avatar.url
)
)
except Exception as e:
pass
print(e)
paginator = pg.Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
paginator.add_button('first', style=discord.ButtonStyle.gray, emoji=':skip:')
paginator.add_button('prev', style=discord.ButtonStyle.gray, emoji=':left:')
paginator.add_button('next', style=discord.ButtonStyle.gray, emoji=':right:')
paginator.add_button('last', style=discord.ButtonStyle.gray, emoji=':skip2: >')
paginator.add_button('delete', style=discord.ButtonStyle.danger, emoji=":cancel:")
await paginator.start()
except:
pass
bro i dont know anything about python discord bots

i mean i can help but you're not listening
i got my help and its been spammed by over 1k people and No pause / crash / stop
sure
i didn't say i doubted you
Can anyone help on this api endpoint im getting? py 'ClientResponse' object is not subscriptable
you're doing x['list'] instead of f['list']
u said "sure" which people use as example
ME : i just got 150 kills in fortnite in 1 game
friend : Sure
u cant get 150 kills in fortnite in 1 game
ah im stupid thanks π
also, you shouldn't create a new aiohttp client session every time you run your command, you should have one client session that you reuse, here's an example
my face when i enter this channel
class DiscordBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__()
# add anything else here
async def setup_hook(self):
self.client_session = await aiohttp.ClientSession()
async def close(self):
await self.client_session.close()
await super().close()
bot = DiscordBot(...)
@slate swan
interesting, ill def try that thanks π
anyone able to help or point me in the right direction?
you can paste your code using https://paste.pythondiscord.com or use a discord codeblock if it's short
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
and then paste the link here?
yeah
I know to paste it here, just wasn't sure if it was ok too
1.02 23:36:38 [Bot] Ignoring exception in command verify:
21.02 23:36:38 [Bot] Traceback (most recent call last):
21.02 23:36:38 [Bot] File "/.local/lib/python3.9/site-packages/discord/commands/core.py", line 124, in wrapped
21.02 23:36:38 [Bot] ret = await coro(arg)
21.02 23:36:38 [Bot] File "/.local/lib/python3.9/site-packages/discord/commands/core.py", line 982, in _invoke
21.02 23:36:38 [Bot] await self.callback(ctx, **kwargs)
21.02 23:36:38 [Bot] File "/bot.py", line 67, in verify
21.02 23:36:38 [Bot] await message.add_reaction(emoji)
21.02 23:36:38 [Bot] AttributeError: 'Interaction' object has no attribute 'add_reaction'
21.02 23:36:38 [Bot] The above exception was the direct cause of the following exception:
21.02 23:36:38 [Bot] Traceback (most recent call last):
21.02 23:36:38 [Bot] File "/.local/lib/python3.9/site-packages/discord/bot.py", line 1114, in invoke_application_command
21.02 23:36:38 [Bot] await ctx.command.invoke(ctx)
21.02 23:36:38 [Bot] File "/.local/lib/python3.9/site-packages/discord/commands/core.py", line 375, in invoke
21.02 23:36:38 [Bot] await injected(ctx)
21.02 23:36:38 [Bot] File "/.local/lib/python3.9/site-packages/discord/commands/core.py", line 132, in wrapped
21.02 23:36:38 [Bot] raise ApplicationCommandInvokeError(exc) from exc
21.02 23:36:38 [Bot] discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'add_reaction'
can anyone help?
did you read the error though? AttributeError: 'Interaction' object has no attribute 'add_reaction'
yes
are you using pycord?
yes
look at what ctx.respond returns
interaction, and interaction has an attribute named original_message
ok
or original_response is probably what you want
@bot.slash_command(description="Verify command")
async def verify(ctx):
member = ctx.author
number = random.randint(1, 5)
embed = discord.Embed(title=f"Verification - Pick the number {number}", color=0x00ff00)
embed.add_field(name="You have 3 tries to pick the correct number!", value="React with the corresponding emoji to pick your number.", inline=False)
message = await ctx.respond(embed=embed)
# Add reactions to the original message
for emoji in ['1οΈβ£', '2οΈβ£', '3οΈβ£', '4οΈβ£', '5οΈβ£']:
await message.add_reaction(emoji)
def check(reaction, user):
return user == member and str(reaction.emoji) in ['1οΈβ£', '2οΈβ£', '3οΈβ£', '4οΈβ£', '5οΈβ£'] and reaction.message.id == message.id
this what makes no since
sense *
that should work right? @smoky sinew
looks like what it should
ctx.respond doesn't return message, it returns interaction like i said
you are confusing yourself
oh
yes
interaction = await ctx.respond(embed=embed)
message = await interaction.original_response()
ok
@smoky sinew nm i was a dumbass again
i had
@bot.slash_command(description="Verify command")
@bot.slash_command(description="Verify command")
not
@bot.slash_command(description="Verify command")
ok
is there a text input ui component?
context: pagination in embeds
How are those related
No
We're not at that level of interactivity yet π
Though it would be cool to see
only in modals
#dm user
@nextcord.slash_command(description="DMs a user a message from Runa.")
@application_checks.has_permissions(administrator=True)
async def dm(self, interaction, user:nextcord.Member, *,message, attachment:nextcord.Attachment=None):
try:
await user.send(f'You have received a message from {interaction.guild.name}: \n{message}')
await interaction.send(f"I have sent {user.mention} the message: {message}")
if attachment:
await user.send(attachment)
except Exception:
await interaction.send(f"Failed to DM {user.mention}.")
im trying to use this slash command to send images and it works. but does anyone know how to modify it so i can send multiple attachments at once?
i don't think you can have a list of parameters with slash commands
Hey sorry if its wrong channel, but any ideas why my files are showing up like this when downloading them via FTP
Wrong encoding or those are not text files
How do you create these files
Theyre downloaded from my server host for a game. never had this issue before @vale wing
If i open them in notepad theyre fine
install the plugin it shows an option on top
@shrewd apex I tried, still nothing π€
after installing restart py charm
also make sure to associate log files with their appropriate type when opening
btw ur pycharm update is pending
updating pycharm now. ill give it a try
you shouldnt update pycharm just delete it and use vscode
π
it does look like there's real content in between all those null bytes, but i would suggest making another help post and including your current code
What encoding does it show
if you want multiple attachments try asking for a message url/ID which has those attachments instead of an attachment option maybe
or allow both choices
do you know if its possible to send a list/array of attachments into a slash command?
it's not
okay thank you, i think your message id suggestion is clever
@vale wing encoding is ascii
just head into settings?
Check out bottom right corner, you should be able to specify encoding there
tried US-ascii still not showing properly :/
Should I just raise an exception in is_staff check if it's false so that I can handle it in the error handler?
def is_staff(interaction: discord.Interaction) -> bool:
role = interaction.user.get_role(config.role.staff)
return role is not None
@app_commands.check(is_staff)
@app_commands.command(name="ping", description="Ping Pong")
async def ping(self, interaction: discord.Interaction) -> None:
...
since the error is discord.app_commands.errors.CheckFailure by default
@vale wing awesome, fixed it π utf-16le
like this
def is_staff(interaction: discord.Interaction) -> bool:
role = interaction.user.get_role(config.role.staff)
if role is None:
raise exceptions.InvalidPermissionsException()
return True
Just return false
but I want to handle it in error handler
like so
async def on_error(interaction: Interaction, error: app_commands.AppCommandError) -> None:
if isinstance(error, exceptions.InvalidPermissionsException):
return await interaction.response.send_message("Invalid permissions!", ephemeral=True)
this is what my bot will be doing, just a basic rock paper scissor
Ok? So what do u want
I want to make the discord bot that game, but I was getting connection errors. It was not pinging back.
Can u show code and error
I tried to run this
intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello!')
client.run('<Your Bot Token>')```
but it says, ModuleNotFoundError: No module named 'discord'

I'm sure I did
Try again
ββpip install discord.pyββ
I needed to update it!!
that's what it was...fff
my bad, thanks all
it's connected, but not pinging back
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 = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello!')
client.run('<Your Bot Token>')```
This is my .env file
still not getting a response from my bot
I'm following along with this
https://www.pragnakalp.com/create-discord-bot-using-python-tutorial-with-examples/
Introduction Discord is a group-chat platform similar to Skype, TeamSpeak, or Slack that allows users to communicate simple text messages as well as rich messaging. In this tutorial, we will learn to create a Discord bot and add it to our channel. How we can send text, image, video, audio, files through the bot, and β¦ Continue reading Create Dis...
you've added the bot to your server, made it sure it can read the channel and you've enabled message content intents in the dev portal?
yes
just my code runs on replit
oh, where should I run it
while you're still developing it, it's easiest to run it on your own computer
once you feel like it's stable and ready for use, you can choose a proper hosting service
I can run it on sublime or pycharm
PyCharm seems good
pip install discord.py
I already did
Use venv instead if u r on pycharm
and updated it
I already did
do
@bot.listen() instead of @bot.event
Does on_ready work?
how can I tell?
Nope just replace the @bot.event
It should print "We have logged in as......" In console
Did u make sure to enable all intents on dev portal?
Sounds like average discord bots tutorials
Did u put the bot Token? π
yep
where would you like me to run it?
Try replit
Great
It's working? Also it isnt a dc bot lol
sorry?
yes it works
but the bot does not ping
Show the code and how you're sending the command
It doesn't work doesn't explain the problem
import discord
intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
print("message-->", message)
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello!')
if message.content.startswith('image'):
await message.channel.send(file=discord.File('download.jpg'))
if message.content.startswith('video'):
await message.channel.send(file=discord.File('sample-mp4-file-small.mp4'))
if message.content.startswith('audio'):
await message.channel.send(file=discord.File('file_example_MP3_700KB.mp3'))
if message.content.startswith('file'):
await message.channel.send(file=discord.File('sample.pdf'))
client.run('my key')
my bad
import discord
intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('Hello!')
client.run('my key')
And how did you send the command?
sorry, what command?
He is using on_message xd
Same thing
she
My bad
why you making fun of me
:-:?
how do I use aiohttp for my bot to check a specific channel for any message and if the message has a user id send that person a dm
Kindly go through discord.py library it doest work like that
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
why not use d.py instead of aiohtto?
there are some issues hehe
some issues
what are the issues
I am sure u r gonna have more issues if u send raw requests ngl
sounds like someone tryna selfbot
yea lmao
nah I made that long time ago
its patched
and its a long time ago anyways
I need help beacuse..... heres a story
u can still selfbot so wydym by patched?
lets skip that topic, shall we
my bot very good bot is on discordbotlist site
when someone upvote my bot I need them to receive a dm saying thank you
the discordbotlist has a webhook which sends the person's user id in the channel
bot sees the channel user id and sends them a dm saying thank you
message content needed for this but discord says no no no
hence I have to use aiohttp for this purpose
nahhh
Still won't work ngl
If u don't have messages content, then won't work even if u send raw requests
Can I get a link of the bot list please?
check dm cant send here cuz of rules
Sure
soooo what if I use selenium and use it to check any new message in that discord channel and then connect the bot lines of code and send them a dm
Nonono why being so difficult
Just setup a web server which will receive the webhook events, instead of sending the webhook messages to a channel
Just run a web server with yr bot. Use quart or smth idk
I have not much info in hosting but I have a vps
can I do with that?
Sure
Doesn't even have to be bundled with your bot
Separate web app like Flask that POSTs to Discord with a thank you message
You can use aiohttp web for a simple web server, and send requests to Discord whenever your web servers receives an event
Idk anything about AWS, so don't expect anything from me
sooo I have to make a web server which checks for any new upvoters and then make that web server to tell my bot to send that person dm?
No
You make a web server, and create an endpoint which will receive requests whenever the webhook is fired, that is, whenever a person votes. Then, you send a request to Discord via aiohttp
It doesn't poll
Web server just listens for webhook
You should checkout how web server works and how to create one. It will be clearer that way
The idea behind the same is smth like this:
import flask
import requests
app = flask.App()
@app.route("/vote-webhook")
def vote(request): # request parameter represents the payload send by the API
payload = request.payload
. . . # access the payload dict and send the necesaary request to Discord with requests
This is sync, but u can make it async with FastAPi
So, I install discord.py for create a bot, and sometimes the module isn't import in my new script. I went to see whatever in its folder and there are still the same as installed. I uninstalled and reinstall it for many times already, and then it works. Wow.
So, the next two days. It didn't work agian ;-;
no need for seperate webserver u can run a websockets listener along with the bot
- Most discord libs conflict so u can have only one per env
- Make sure u have it installed on the same python version/interpreter u are using to run ur code
- If u installed in a venv make sure to activate venv before running the project
Does anyone have a tutorial on how to make cooldowns but it writes minutes and seconds and not 175.65 seconds
Did something change?
code:
banner = f"""
\u001b[37m β βΒ· βͺ Β·ββββ
\u001b[37m βͺβΒ·βββͺ ββ βββͺ ββ
\u001b[37m βββββ’ ββββ ββΒ·ββΒ· βββ
\u001b[37m βββ βββ.βββββββ. ββ
\u001b[37m . β βββββͺβββββββββ’
\u001b[37m Logged in as: {bot.user} : {bot.user.id}
\u001b[37m Guilds: {len(bot.guilds)}
\u001b[37m Commands: {len(bot.commands)}
"""
@bot.event
async def on_ready():
print(banner)
bot.user is None before on_ready is triggered
ah
@gusty flax
so when someone makes their ticket, only they can see the ticket and the mods right?
yes, give me a second ill gather some docs for you to go of
Im trying to do that
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
The overwrites parameter can be used to create a βsecretβ channel upon creation. This parameter expects a dict of overwrites with the target (either a Member or a Role) as the key and a PermissionOverwrite as the value.
what does the overwrite do tho. like how does it make it the secret channel only that user and staff can see?
lets say there is a claim ticket command like this:
@bot.command()
async def claim_ticket(ctx): pass
and assuming there is a category already set up with the correct permissions for the moderators/staff members that should be able to read and respond, then all you need to do is to sync the new channel with the category, which is done automatically when passing a category object to the category argument:
username = ctx.author.name.casefold()
# replace `0` with the category id
category = ctx.guild.get_channel(0) or await ctx.guild.fetch_channel(0)
channel = await ctx.guild.create_text_channel(
name="ticket-{username}",
category=category,
)
that will successfully create the channel that is in-sync with the category, but you also need to add the member to the channel, i actually forgot how to do it correctly and the docs confused me a lil bit, but you can do that with the discord.PermissionOverwrite object and passing it to create_text_channel but I figured you can try this instead:
permissions = discord.Permission()
permissions.send_messages = True
permissions.read_message_hisotry = True
overwrites = discord.PermissionsOverwrite.from_pair(permissions)
await channel.edit(overwrites={ctx.author.user:overwrites})
this should work but you can try
^
thank u so much. ye i got to it all except the last part. tysm π
i mean, the code is quite readable, you just create a permission object and allowing send_messages and read_message_history (i did a typo for "history" in the above code so correct that), then you just create an overwrite object that inherits from the permissions object, which then you create a mapping with the user and pass it as an argument to overwrites to the channel edit
Like, in this server?
i just dont know if thats the exact correct way of doing it, but as far as i understood from the docs is that should be correct
no just regular ticket channels where users can talk to mods
like modmail, but not in dms
weeeeeeell
the discord API provides you with all channels
Even ones you don't have access to see
BUT is undocumented behavior and is TOS violating soooo
Take that how you will
you cant view the messages if thats what you mean
Nah
you just know it exists
But you can see the channels (which are often user IDs or user names)
Personally seems like a security flaw to me
heyy, I need some help please
So I am trying to run this code but when i try running it and type the command I get the response that it worked, but when I look in the DB nothing was added
import discord
from discord import app_commands
from discord.ext import commands
import mysql.connector
from typing import Literal
from utils.functions import *
from utils.constants import *
from utils.embeds import *
# Connect to the database
mydb = mysql.connector.connect(
host="127.0.0.1",
user="bam",
password="bambam",
database="one_piece"
)
cursor = mydb.cursor()
class Drops(commands.Cog):
def __init__(self, bot: commands.Bot)-> None:
self.bot=bot
@app_commands.command(name="drop_shards", description="drop shards")
@app_commands.describe(amount="the amount you want to drop", element="Which element do you want shards from?")
async def drop_shards(self, interaction: discord.Interaction, amount: int, element: Literal['Fire', 'Water', 'Dark', 'Earth', 'Light', 'Lightning','Grass', 'Neutral']):
if amount < 0:
await interaction.response.send_message("Mehh provide a number over 0 smh")
return
else:
element = element.lower()
cursor.execute(f"UPDATE {element}_shards SET amount = amount +%s WHERE player_id =%s", (amount, interaction.user.id))
mydb.commit()
await interaction.response.send_message(f"Successfully added {amount} {element} Shards to your profile")
async def setup(bot: commands.Bot)-> None:
await bot.add_cog(
Drops(bot),
guilds=[discord.Object(id=1052225383065456752)]
)
Does anyone have a tutorial on how to make cooldowns but it writes minutes and seconds and not 175.65 seconds
yeah so the ```py
permissions = discord.Permission()
permissions.send_messages = True
permissions.read_message_hisotry = True
overwrites = discord.PermissionsOverwrite.from_pair(permissions)
await channel.edit(overwrites={ctx.author.user:overwrites})
should work correctly, but there is an easier way which is just:
```py
await channel.set_permissions(
ctx.author, read_messages=True,
send_messages=False
)
so you'd have this:
@bot.command()
async def claim_ticket(ctx):
category_id = 0 # replace `0` with the category id
category = ctx.guild.get_channel(category_id) or await ctx.guild.fetch_channel(category_id)
channel = await ctx.guild.create_text_channel(
name="ticket-{username}",
category=category,
)
await channel.set_permissions(
ctx.author,
read_messages=True,
send_messages=True
)
tho i would recommend adding more checks like if the bot has the permission to create channels, etc...
doesn't seem to be any issues with the discord.py related code, this should go in #databases
could you elaborate what's not writing in minutes and seconds?
a cooldown message?
in that case, this is also un-relevant to discord.py, create a post in #1035199133436354600 and ask about how you can convert seconds into minutes:seconds
Like βyou can use this command in 2m and 2s
Oh thanks!
Alright, thank you very muchπ
why am i having this problem?
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Roll' raised an error: SyntaxError: did you forget parentheses around the comprehension target? (Roll.py, line 181)
line 181 = line 36
what does it mean when a guild becomes available/unavailable? like is it when a server gets deleted or something?
you want that specific ticket command? (itll take a lot of code)
or just slash commands?
oki
thanks btw
npp
okay, first thing fixed
guys, how do i get the lenght of a list and store it into a variable?
your_variable = len(your_list)
iirc it means server outage
ah okay thank you
it's because it shows me this output:
'list' object has no attribute 'len'
Did you overwrite list somewhere
Do len(start), len(end)
a question, is there a way of using try except and when except it returns null?
API outages
ah okay thank you
#emojis update
@commands.Cog.listener()
async def on_guild_emojis_update(self, guild:nextcord.Guild, before, after):
embed=nextcord.Embed(color=0xfd9fa1, title='Emojis Updated',timestamp=datetime.datetime.utcnow(),description=f'Before: {before}\nAfter:{after}')
await self.bot.get_channel(channelID).send(embed=embed)
can someone help me with this code? i want to show the emoji that got added/removed but im not sure how to pull up the specific emoji.
i cant do it as it is right now, because with several hundred emojis the embed wont send at all due to 6000 character limit
You will have to write up a little algorithm that calculates the difference between emojis before and after
How could I detect bad words in a interaction command?
I have already done that
the bot had joined my server
it's just not online
ah thank you robin, iβll see if i can figure out how to make that algorithm
i think all discord objects are hashable in dpy
does somebody knows how to add a cooldown to a command?
Theoretically the answer to that question is no, but send the error because I'm sure it's not impossible to fix
send the code please (you probably just called a variable before it was assigned)
yes i can
i was gifted with the superpower of fixing only impossible to fix issues
Truly wonderful
then help me add a cooldown on my command cause im so lost
this dont lok like all da code !!!
giv code or dm it or something and tell me
do pastebin or something of that nature
Where do you get that error because it works on my machine?
Replace if message.author.id == bot.user: with if message.author.id == message.guild.me.id:
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
Do you have a full error?
I don't really know what it means without it.
Yeah because you can't reference it that way... hmm
Brain is working for a quick fix.
Really quick would be global but I despise it.
user = self.client.get_user(int(userid)) returns none why lol
Because it isn't cached most likely
user = self.client.get_user(int(userid)) or await self.client.fetch_user(int(userid))
So I have my bot online and in my server, but it's not responding
import discord
from discord.ext import commands
import random
intents = discord.Intents.all()
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user.name}')
@client.command()
async def play_rock_paper_scissors(ctx):
player_choice = await client.wait_for('message', check=lambda message: message.author == ctx.author)
options = ["Rock", "Paper", "Scissors"]
computer_choice = random.choice(options)
choices = {"player": player_choice.content, "computer": computer_choice}
result = check_win(choices["player"], choices["computer"])
await ctx.send(result)
def check_win(player, computer):
if player == computer:
return "It's a draw"
elif player == "Rock":
if computer == "Scissors":
return "You Rocked it's world!"
else:
return "Ohh yeah, nah, you lose..."
elif player == "Paper":
if computer == "Rock":
return "You win! Paper covers Rock."
else:
return "Ohh yeah, nah, you lose..."
elif player == "Scissors":
if computer == "Paper":
return "Cut in half! You win. Fatality."
else:
return "Ohh yeah, nah, you lose..."
client.run('my token')```
I need to add a print statement above player_choice. Would it be a simple print("Please enter, Rock, Paper, Scissor") ?
How to overcome the challenge of everyone role needing external emoji perm despite the bot having it
Like bot can't show external emojis if everyone role doesn't have them
Anyone in here who can help me proper setup my pool connection for postgresql & asyncpg using a setup_hook?
are you typing in !play_rock_paper_scissors?
and also why would you use a print statement in a discord bot? it will only be visible in your terminal
are you still using requests bruh
no
aiohttp?
kidna
wdym kinda
/kaΙͺ.ndΙ/ used in writing to represent an informal way of saying "kind of": I was kinda sorry to see him go.
that doesn't explain anything
lmao what
you either use it or you don't
rate the damn bot 0-10 for verify
having the user confirm a one digit number isn't effective for verification
so 5
like 1οΈβ£?
yes
you realize you can just get the name of the emoji lol
yes
that's even worse
you can still get the emoji name and map it to a number
the embed thingy (how things are positioned) could use a rework imo
what's the point of that though
Hey, i've created an embed with 2 buttons. i've then got a command which i type into a channel and it posts. it all works perfectly and i click the button and it works. but when i re-start my bot and go to click those same buttons i get interaction failed? any ideas why?
class ClaimWelcomePack(discord.ui.View): # welcome pack to pack buttons
@discord.ui.button(label="Register", style=discord.ButtonStyle.green)
async def button_register(self, button, interaction):
await interaction.response.send_message('welcome pack claimed')
using Pycoord
its step 1
just generate an image containing the number text like an actual captcha which will prevent pretty much all spam
there are 3 steps
step 1
Simple Image
Step 2
"Captcha"
Step 3
custom captcha~~ -~~
Pattern
your button isn't persistent. If you want the button to work after restart, make it persistent. See https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py for an example
explaining what you didn't explain anything
@fading marlin So i have to make a command to call it? Is there an easier way to do this automatically some how?
no you just add the view when your bot starts to make it persistent
@smoky sinew i am mostly discord.js for bots not python
discord.js has some async concepts too you know
yes I tried !play_rock_paper_scissors it won't respond
is there any error?
check term
nope, no response from bot
what?
its with print '
sorry what?
check if the command is running at all maybe
how do I do that?
add a print to your command...
with a print statement or a debugger
β
and is the bot logging in?
so i can just
self.add_view(PersistentView())
when my bot first starts?@smoky sinew
yes
that works
what's that supposed to mean? if you didn't have discord.py installed you would've gotten an error saying that the module could not be located
this is everything I have installed
so does pycharm need to use a different interpreter other than python 3.10?
unless you want to use another one, no?
it's discord.py I need to be using?
because pycharm says no module called discord
yet it's installed
it already does
it uses a virtual environment by default
do I add discord.py here?
you'll need to install discord.py through pycharm or switch the pycharm interpreter
so i need some help with the API portal
no, just double tap "shift" and search for packages
you can add discord.py there
where? it does not work on that screen
what do you mean where? let me open pycharm
also im in python 3.11, how do i get discord.py in there?
i dont have anything installed, should i have anything installed
you said double tap shift. I did. Nothing happened
pip install discord.py on windows, pip3 install discord.py on mac or linux
i'm used to intellij, it might be different on pycharm
you should get a search box when you press it twice, just tested it
inside python right
no, it's a terminal command
on create project screen?
where did you press shift twice
no, when you're editing your code
ok
?
you're not on mac or linux though
beast! it's installed there now
try python -m pip install discord.py then, if you don't have python installed get it from https://python.org and make sure to check "add to path" when installing it (don't install it from microsoft store)
also i thought you meant on windows its pip3
i have it installed
in fact its running right now
ok
but it says it wasnt found
then how did you run it
you mean pip wasn't found or python wasn't found?
if it's pip, did you do a custom installation when installing python?
I get 2023-02-23 13
15 ERROR discord.client Ignoring exception in on_ready
?
when I run the script in pycharm
yeah but can you send the whole thing
2023-02-23 13:08:12 INFO discord.client logging in using static token
2023-02-23 13:08:13 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 6ac361a3fd51af16a59821895df8907b).
2023-02-23 13:08:15 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\rubyr\venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\rubyr\PycharmProjects\pythonProject5\main.py", line 13, in on_ready
guild = discord.utils.get(client.guilds, name=GUILD)
NameError: name 'GUILD' is not defined```
and the code?
so you didn't send the whole code initially?
python
what is GUILD?
import random
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == '!play_rock_paper_scissors':
options = ['rock', 'paper', 'scissors']
bot_choice = random.choice(options)
await message.channel.send("Choose one: rock, paper, or scissors")
def check(msg):
return msg.author == message.author and \
msg.channel == message.channel and \
msg.content.lower() in options
player_choice = (await client.wait_for('message', check=check)).content.lower()
if player_choice == bot_choice:
await message.channel.send(f'I chose {bot_choice}, so it\'s a tie!')
elif player_choice == 'rock':
if bot_choice == 'paper':
await message.channel.send(f'I chose {bot_choice}, so you lose!')
else:
await message.channel.send(f'I chose {bot_choice}, so you win!')
elif player_choice == 'paper':
if bot_choice == 'scissors':
await message.channel.send(f'I chose {bot_choice}, so you lose!')
else:
await message.channel.send(f'I chose {bot_choice}, so you win!')
elif player_choice == 'scissors':
if bot_choice == 'rock':
await message.channel.send(f'I chose {bot_choice}, so you lose!')
else:
await message.channel.send(f'I chose {bot_choice}, so you win!')
client.run("my token")```
I'm sorry to spam
installed right off of python.org
why are you using completely different code there?
i dunno what pycharm is i just took python from python.org and thats how i installed it
and how i run it
you have three options:
- reinstall python from python.org and check "add to path" when installing
- open windows' "edit system environment variables" page and add the python path to the PATH variable
- type out the whole path when running python
"C:\PythonPathHere\... -m pip install discord.py
by "python path" i mean the python exe file, to find it just press "open file location" when searching for python in the start menu
i have it in D:\ but yeah alr
I have spent 3 days on this, I think I might come back to it in 6 months when I am better at coding
thanks for your help
if it goes to a shortcut page, press open file location a second time on the shortcut
await reloadbuttons(bot) # when bot starts
async def reloadbuttons(self) -> None:
self.add_view(ClaimWelcomePack())
View must have no timeout```
i'm guessing you need to set timeout = None in your view
class WelcomePackView(discord.ui.View):
def __init__(self):
super().__init__(timeout = None)
...
i installed it to a folder called python btw so
also you don't have to give up completely, i can help see what the problem is, i'm just confused on why you posted two different pieces of code
class ClaimWelcomePack(discord.ui.View): # welcome pack to pack buttons
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Register", style=discord.ButtonStyle.green, custom_id='register')
async def button_register(self, button, interaction):
await interaction.response.send_message('welcome pack claimed')
print('click')
I click it, nothing errors but still interaction failed π¦
if it says requirement already satisfied on all of them then yes probably
that's strange
i can give you a simple example of a discord bot if you'd like
would you like an example with message commands or slash commands?
well like, i havethe code but I dunno how to make it go into the discord bot
the discord API portal confuses me
am i right in using bot?
async def on_ready():
await set_bot_status()
await reloadbuttons(bot)```
but i would also like to see an example cuz some of this i got from realpython
have you tried using add_view in setup_hook instead like the persistent example showed?
sure
you need to go to https://discord.com/developers/applications and make a new application
once you've made one, go to the bot tab, press "add bot" and then copy your token
invite the bot in the "url generator" tab under oauth2, with the bot scope and optionally application.commands scope if you want slash commands
message commands btw, i made stuff with message commands
No, only tried what you mentioned here. π
from discord.ext import commands
import discord
bot = commands.Bot(
command_prefix = "!", # the bot prefix you want to use
intents = discord.Intents.default() # what data you are subscribing to receive from discord
)
@bot.command()
async def hello(ctx):
await ctx.reply(f"hello, {ctx.author.mention}")
bot.run("your bot token should go here")
also what part of the code should that go
that's all of the code
yeah
you can add onto that however you like
potentially copy and paste code from the realpython example too, but if it's using on_message commands, i recommend switching it over to the new message command system
alright, well try something like this:
class DiscordBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
await self.add_view(ClaimWelcomePack())
and then you can replace commands.Bot with DiscordBot, if you don't have your own bot class already
yeah its if message.content == 'what they would have to say'
that's very old
so should i just
deplete of that stuff?
when i pasted it into python, half of it was like... errors but i dunno if that was just with discord or not
you don't have to delete it, just switch it over because that way of making commands wasn't relevant since 2016
the command logic should mostly be the same, just the argument parts and the actual command parts are different
it's ok, I'm not wasting another second on it for now
should i still do the client-bot conversion
class DiscordBot(commands.Bot
commands.Bot is erroring. not defined? Not sure if im putting that code in the right place?
well, do you have from discord.ext import commands imported?
you should put it in your main file
No i dont have that, should i add it? i just have
import discord
using Pycoord
what is "#what data you are subscribing to recieve from discord"
i don't know pycord, but i guess so @polar ice
in the context of the discord API, intents is how discord knows what kind of information to send to your bot
if you have a typing intent (which is automatically included in discord.Intents.default()), your bot will be notified when people start typing in a channel
there are also privileged intents, which if you're in over 100 servers you need to apply to subscribe to
there are messages and message_content
message_content is privileged and not included in discord.Intents.default, which you need for making message commands
messages is not privileged however
ok so i put message_content
i just want it to reply something after someone says something with a command
so if they did QK randnumgame it would do a random number game for example
i'm not sure if you need message content but it would be something like this:
from discord.ext import commands
import discord
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix = "!", # the bot prefix you want to use
intents = intents # what data you are subscribing to receive from discord
)
@bot.command()
async def hello(ctx):
await ctx.reply(f"hello, {ctx.author.mention}")
bot.run("your bot token should go here")
right ok so how do i put it into the bot
that is the bot though
it connects using the bot token, the bot token basically acts as a password
which is why i said to copy it
Anyone in here who can help me proper setup my pool connection for postgresql & asyncpg using a setup_hook?
paste it in where it says "your bot token should go here"
so basically, i put it into python?
yes, but not the python window
you need a code editor, paste the code into it, and run it with python
so which should i download
pygame is best for game making ?
yea
so in VSC do i just open up python or whatever has to do with python and put the code in?
vscode will just use the python that you already have
and it has a built-in run button
what would a good way of keeping the history of a bot's commands?
how i'm doing it rn is writing it to a text file
like who is using them?
just a log of commands
person a used x command on timestamp
app commands?
if not inter.author.guild_permissions.administrator:
return await inter.response.send_message("You don't have Administrator Permissions!", ephemeral = True)
``` doesnt wrok dam 
oh it it maybe inter user
uh i'm using hybrid commands
Is anybody familiar with Pycoord?
im trying to make a button persistant. ive done everything which it says in the docs but still nothing
did you import from discord.ext import commands
try that in your main file, i'm not sure how you're making commands
@smoky sinew py @bot.slash_command(name="server", description="Server status") async def server(ctx):
Im using slash commands
ok so i pasted the code into a VSC file
do i have to install the python thing that it prompts
just import it anyways
yeah, that will help
https://guide.pycord.dev/interactions/ui-components/buttons
in here, if i do the test command it shows the buttoms and that works. but not the original.
Ill try import them now
Learn all about implementing buttons in your Discord Bot using Pycord.
make sure you pressed ctrl + shift + p in vscode and typed in "select interpreter" and chose your python 3.11 @clever lotus
it keeps having an error
what error?
when i install it
i'm not sure if add_view works in pycord though
according to the docs it should it says
bot.add_view(MyView()) # Registers a View for persistent listening
alright
what is the log?
Tried import from discord.ext import commands
still the same π¦
should i paste the whole log
!paste @clever lotus
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.
you don't have storage
i have...
4.10 gb?
do i need to like
how do i make it install to my SD card
instead of windows
you're installing python on an SD card?
doesnt pop up anything
ctrl + shift + p doesn't?
yeah, i use the SD card
no, select interpreter doesnt
yeah, you need to install python extension first
won't it be slow?
OK i downloaded manually so i can move it to my SD
it runs just fine
alright
Send the code
where do i move the vsix
i don't really know
you could ask in #editors-ides, but that's why i didn't recommend installing it manually
otherwise it wouldve installed to C:\ and that barely has any space
well with the code in bot.py, will it work now?
@smoky sinew
also ok
so how do i get a valid URI?
what do you mean?
yeah
it should
hey, so I haven't been developing bots for like two years on the platform so I'm a bit outdated. so now that we have slash commands, does discord.py have the support?
i dont think i need one anymore since i got the bot working, i just need it to be... online
maybe thats what this requires
yes, it does with discord.py 2.0
that's for the "log in with discord" thing
you don't need that
to get the bot online, you need to run the code
do i need to debug
or can i just run
nvm i got python extension
oh i need to get the interpreter
ok i think i ran the code
cool, is the bot online?
press the run button then
Generally better to just invoke the interpreter directly than using the run button tbh
never trusted that thing
wdym invoke the interpreter
you should still set up the vscode python extension, run button or not
it's very helpful
he means to run python from the terminal
there's a terminal tab at the bottom of vscode
i dont see
Press CTRL + `
ok
That's the key to the left of the 1 key
type in <python path> <code file path>
you had some issues with the path earlier so if you set it already you can just use python instead of the path
i believe the python launcher is recommended on windows
that's why i said to go to "edit system environment variables" and edit the PATH variable
yes, that's what the path variable means
you should see a python path in there so just replace it with the other one
OK so edit
Anyone in here who can help me proper setup my pool connection for postgresql & asyncpg using a setup_hook?
no like where should i store these commands though
like you normally would?
async def process_log(log):
print(log.name)
if "chat_" in log.name: # Process chat into the DB
print(f'Processing chat for: {await get_guild()}')
with open(log.name, 'r', encoding='utf-16le') as f:
expected str, bytes or os.PathLike object, not TextIOWrapper
I've also tried pointing it directly to the file path too but nothing
!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.
you are probably doing something with f, so the code you gave stops just before the error
how would i *log them, sorry
it doesn't actually give me an error it just resets the loops and continues
in a text file, db, or something else?
a file would work, or maybe use the logging module
databases are good if you need to retrieve the info
doesn't logging only produce some console output
https://realpython.com/python-logging
this tutorial seems to be 4 yo, could you possibly see if it's still up to date?
yeah it's still functional, I don't think there has been any breaking change in logging module for a long time ( or since the beginning iirc )
how to detect if slash command is used
the standard library doesn't have breaking changes often
so you should be good
hey can anyone help because like when am using a slash command to send embed and i cant send 2 embeds in 2 seprate if statements
idk why
Send the code
simple question, can a bot send audio files like sfx the user can play/download directly in the client? if yes, do they need to be in a specific format?
ok wait
They'd have to download it
links = ["https://krakenfiles.com/view/PJvleyychY/file.html", "https://krakenfiles.com/view/k4cP4thaqE/file.html"]
@bot.slash_command()
@commands.is_owner()
async def send_leak_of(interaction: discord.Interaction,song_name: str):
if song_name == "test" or "Test":
embed2 = discord.Embed()
embed2.add_field(name="HERE IS YOUR FILE", value=f"[Example 1]({links[1]})")
embed2.set_thumbnail(url="https://images-ext-1.discordapp.net/external/5VmU7_EPijZkRIQ1hLuGbdK-OI4NjW15vr_ybeSsddc/https/cdn.discordapp.com/avatars/920827061516505139/a_728cd43fdf2c353c6bb1bb7451d8a5af.gif")
await interaction.response.send_message(embed=embed2)
elif song_name == "test2" or "Test2":
embed = discord.Embed()
embed.add_field(name="HERE IS YOUR FILE", value=f"[example 2]({links[0]})")
embed.set_thumbnail(url="https://media.discordapp.net/attachments/1070602145436545024/1076001220604469278/99f29b75491cac917b21cd5c212be17f.jpg?width=401&height=502")
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message("We have only 2 files rn, The owner is updation this command and soon there will be more leaked files:)")
here
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
its only sending the first if statement
That's the idea of if-elif-else-statements
how to detect if slash command is used
mhm yea but like if am doing test 2 its sending the test embed not the test2 embed
ok thanks it got fixes
fixed
You can print statement or smh like a logging feature that allows the bot to send a msg in a custom channel as well as running the whole cmd where it was actually ran
Or just use the slash command invoke event
!d discord.Member.edit as far as i know there is a nick kwarg
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the memberβs data.
Depending on the parameter passed, this requires different permissions listed below...
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
The way u r using will return User obj and if u use guild.get_member will return member obj
Check up.
Use guild.get_member instead.
guild.get_member(self.bot.user.id)
ah worked, thanks π
:-:
How do I make the bot react to its own message using slash command?
Can someone teach me how coolsowns work on a bot?
@bot.command()
@commands.cooldown(1, 10, commands.BucketType.user) # 1 use per 10s
async def ping(ctx):
await ctx.send("pong!")
@ping.error
async def ping_error( ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send("You are on cooldown!")
```smh like this
if you're talking about cooldowns on a command you need the @commands.colldown decorator
for on_message and other things use !custom-cooldown in #bot-commands
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
store that msg and use await message.add_reaction(emoji)
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
and why im eepy π
I use that but it doesn't work
Tho I'm using bot.tree.command()
Maybe that is why^^"
!d discord.app_commands.Cooldown
class discord.app_commands.Cooldown(rate, per)```
Represents a cooldown for a command.
New in version 2.0.
So I have to make a class?
nope I dont think so
@app_commands.command(name="drop_shards", description="drop shards")
@app_commands.Cooldown(1,10)
@app_commands.describe(amount="the amount you want to drop", element="Which element do you want shards from?")
async def drop_shards(self, interaction: discord.Interaction, amount: int, element: Literal['Fire', 'Water', 'Dark', 'Earth', 'Light', 'Lightning','Grass', 'Neutral']):
if amount < 0:
await interaction.response.send_message("Mehh provide a number over 0 smh")
return
else:
element = element.lower()
cursor.execute(f"UPDATE {element}_shards SET amount = amount +%s WHERE player_id =%s", (amount, interaction.user.id))
mydb.commit()
await interaction.response.send_message(f"Successfully added {amount} {element} Shards to your profile")```
And how would I do this if instead of prefix command it is a slash command with bot.tree?
Here apps command is same as bot tree right
And describe it is not mandatory
Right?
discord.app_commands.Cooldown is not a decorator
app_commands should be imported from discord
is there a way to retrieve all autocompleted choices that a discord command has?
async def channel_autocomplete(interaction: discord.Interaction, channel_id):
completions = {channels.name:channels.id for channels in interaction.guild.voice_channels}
return [discord.app_commands.Choice(name=channel,value=str(channelID)) for channel,channelID in completions.items()]
@bot.tree.command()
@discord.app_commands.autocomplete(channel_id=channel_autocomplete)
async def tagchannel(interaction: discord.Interaction, channel_id: str):
#How could I get the returned list of choices?
how do i get images or pfps using an api of website
like it would send random images or the only images which it needs to send only?
with a command
i do import it
shouldnt i put something like thsi
@app_commands.cooldown(1, 3600, commands.BucketType.user)
nvm my code doesnt work π
yeah i just realised xd
I tried it and it didnt, I think you should read it in the docs
It doesn't work like dat tho.
could u explain me how to add a cooldown on a bot.tree.command
@bot.tree.command(name="work",description="Earn money to upgrade your "
"hissatsus")
@cooldown(1, 3600, commands.BucketType.user)
async def work(interaction: discord.Interaction):
random_number = random.randint(1, 100)
d2=conn.cursor()
member_id=interaction.user.id
d2.execute("""
UPDATE game
SET money = money + ?
WHERE member_id = ?
""", (random_number, member_id))
conn.commit()
await interaction.response.send_message(f"You have added {random_number} $ to "
f"your "
"profile")```
this is ma code but it doesnt work^^'
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
@spice zenith
does app_commands apply to bot.tree commands?
Yes
@bot.tree.command()
@app_commands.checks.cooldown(....)
@tree.command()
@app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id))``` what does the key does?
and the i too
i know what rate and per does but not the rest
like key is for the type if cooldown
but what is lambda cooldown
!d discord.ext.commands.BucketType
class discord.ext.commands.BucketType```
Specifies a type of bucket for, e.g. a cooldown.
ah yeah i saw that before
It's like
if u wanna put
Guild cooldown
Then BucketType.guild
i wanna put it so a user can only use it once an hour so i thought it was just 1,3600
It will make something like after someone invoke the command, then no other in the guild can use it till cooldown finishes
There is couple of them
guild
user
member
channel
You should use member
If u use user, if the user trying this on other guild, he will be still in cooldown
While member cooldown is for guild only
Yes.
hmmm but i want so that u can only once regardless of the srvr every each hour
!e
y=lambda x: x+1
print(y(1))
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Uh
!e
def y(x):
print(x+1)
y(1)
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
whats this tho
You know functions right?
yeah
oh
ig this wont work right?
@bot.tree.command(name="work",description="Earn money to upgrade your "
"hissatsus")
@tree.command()
@app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id))
async def work(interaction: discord.Interaction):
random_number = random.randint(1, 100)
d2=conn.cursor()
member_id=interaction.user.id
d2.execute("""
UPDATE game
SET money = money + ?
WHERE member_id = ?
""", (random_number, member_id))
conn.commit()
await interaction.response.send_message(f"You have added {random_number} $ to "
f"your "
"profile")```
Try and check
Traceback (most recent call last):
File "C:\Users\jaime\PycharmProjects\BOT\EX BOT\main.py", line 1616, in <module>
@tree.command()
NameError: name 'tree' is not defined
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
if u just want to use tree:
tree=app_commands.CommandTree(bot)
Btw here i is
discord.Interaction obj xd
wdym
@bot.command()
async def unban(ctx, member:nextcord.Member=None):
if member == None:
em1 = nextcord.Embed(title="__**Unban Error**__",description="Member not found! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em1)
if member.id == ctx.author.id:
em2 = nextcord.Embed(title="__**Unban Error**__",description="You can't unban yourself! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em2)
def check_author(m):
return m.author.id == member.id
await member.unban(user=member, check=check_author)
em5 = nextcord.Embed(title="Unban Success", description=f"{member.mention}({member.id}) Got unbanned!", color=nextcord.Color.green())
await ctx.reply(embed=em5) ```
and it says that member is not found
when putting the id
@shrewd fjord now it works but i would like to make so it prints that u are on cooldown with when u can do it again if u are on cooldown but i have no idea on how to do that ig it is an except Exception but more than that im lost
.
You should use error deco

Idk what did i just type lmao
Wtf
Back after checking docs
You can use global cmd handler...
@bot.tree.error
async def on_app_command_error(interaction, error):
if isinstance(error, please check the docs but maybe app_commands.OnCooldownError):
await send(..)
Hm idk fr need to check docs
is there a way to make ur bot delete buttons without deleting the message content/embed
Tab key shifts right in Python IDLE. What is the left swipe hotkey?
hmmmm seems logic
Just edit the message and set the view argument to None
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
how do I use datetime to convert the bot creation time to the user's timezone.Like this: <t:1677157751:D>
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
you can get bot's creation time using bot.user.created_at
I know that, but how do I convert it to the user's timezone <t:1677157751:D>
^
hi, I'm having a problem with slash commands. I'm currently migrating from prefix commands to slash commands. I use discord.ext.commands.Bot with the decorator @app_commands.command. I have the following command to sync the slash commands:
@bot.command()
async def sync(ctx):
await bot.tree.sync()
It runs without errors, but does nothing, the slash commands don't show up on Discord. Any tips?
Are you using it in a cog
nope
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
the command still doesn't appear to show up after using this and re-syncing
Show the code
@bot.tree.command(name="test", description="test")
async def fj(ctx, target_user: discord.Member, role2: discord.Role, expiration: int):
try:
if ctx.channel == bot.get_channel(1045046421033848933):
[and a lot of code after it]
You'd have to sync it specifically to a guild so you don't have to wait 1hr until it pop up
yes, the last sync was done like this:
@bot.command()
async def sync(ctx):
await ctx.bot.tree.sync(guild=ctx.guild)
examples/app_commands/basic.py lines 22 to 28
# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
Command raised an exception: AttributeError: 'Context' object has no attribute 'tree'
ctx.bot.tree.copy_global_to(...)
I'm getting this error for some reason:
Command raised an exception: AttributeError: 'int' object has no attribute 'id'
Show the code along with the error
And the guild argument is expected to be an object with id attribute
!d discord.Object like this one
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.
async def sync(ctx):
ctx.bot.tree.copy_global_to(guild=1045046418387251301)
await ctx.tree.sync(guild=1045046418387251301)
The error:
line 70 in sync
ctx.bot.tree.copy_global_to(guild=1045046418387251301)
File "C:\Users\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 246, in copy_global_to
mapping = self._guild_commands[guild.id].copy()
AttributeError: 'int' object has no attribute 'id'
guild=discord.Object(theidhere)
thank you, this helped, but there's another problem
on the line ctx.tree.sync(...) ctx doesn't have a tree argument and I'm guessing I should use bot instead of ctx there right?
It will be
ctx.bot.tree.sync(...)
Yea, u can use bot too instead of ctx.bot
thank you, it works!!
what could I do if I need both the ctx and the discord.Interaction in a function? They both have to be the first argument
Why would you need both of them
because there is a countdown that starts, and when it ends (possibly days later) I can't send a message with interaction.response again
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
Or that
ooh thank you! so could I just do interaction.channel.send(...)?
Can you do an autocompletion like this wirh dpy?
With images? no
?
wdym
Nope
any clue why event interaction_create doesnt work when i click the buttons, i have GUILDS and GUILD_MESSAGES intents
yesterday it worked fine
i dont think any gateway intents are required for interaction events, but we need to see your code to give a better answer
Like it sends pfps from Pinterest
does someone know how to solve this error?
"In allowed_mentions.replied_user: must be either true or false:"
allowedmentions is basically a true or false of what you can and cannot ping
you can only reply to one user at a time, so it's pointless to make the distinction to only ping certain users in a reply
instead, you can control the users and roles you can ping in allowedmentions by passing a list of users to allowedmentions.users
https://discordpy.readthedocs.io/en/latest/api.html#discord.AllowedMentions.users
@forest oyster
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1677193566:f> (10 minutes) (reason: discord_emojis rule: sent 25 emojis in 10s).
The <@&831776746206265384> have been alerted for review.
!e ```py
my_list = ["a", "b", "c"]
print(my_list)
print("".join(my_list))
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | ['a', 'b', 'c']
002 | abc
Yeah might wanna be careful with that many emojis
rip
!unmute 707617200722149447
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
A screenshot is probably better
FWIW they have a 2d list
the process is mostly the same but slightly different
i mean just join the inner list items and then the outer list items
hi
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(command_prefix=commands.when_mentioned_or("!"))
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
'X-Auth-Token': auth_token
}
params = {'size': '10', 'page': '0'}
def get_mine_locations():
response = requests.get('https://rest-bf.blox.land/games/mines/history', headers=headers, params=params)
data = json.loads(response.text)
return [location for game in data['data'] for location in game['mineLocations']]
import requests
import random
def get_safe_spots(mine_locations):
# Create a set of all safe spots
all_spots = set(range(25))
mine_spots = set(mine_locations)
safe_spots = all_spots - mine_spots
# Choose 5 random safe spots
safe_spots_list = list(safe_spots)
random_safe_spots = random.sample(safe_spots_list, 5)
# Sort the mine locations by row then column
sorted_mine_locations = sorted(mine_locations, key=lambda loc: (loc // 5, loc % 5))
# Create the grid with emojis
grid = []
for i in range(5):
row = []
for j in range(5):
index = i * 5 + j
if index in random_safe_spots:
row.append('π©')
elif index in mine_locations:
row.append('π£')
else:
row.append('π¦')
grid.append(row)
return grid
def predict():
mine_locations = get_mine_locations()
grid = get_safe_spots(mine_locations)
for row in grid:
return grid
predict()
@bot.slash_command(name="minesplay_bomb")
@commands.has_role("Buyer")
async def bloxflip(ctx):
raid = predict()
embed = discord.Embed(title="Radiant Predictor", description=f"{raid}")
await ctx.respond(embed=embed)
im confused
what do i do to fix
paste your code using https://paste.pythondiscord.com to avoid spam, also should you be scraping a site using a user agent?
yes
why
if it's a user endpoint then you shouldn't scrape it at all
im confused
dw about it π
it can be against the server rules
i already gave help with that though
what do u do then
did you see this?
it worked inside the bot
i can help you with what problem you're having but i can't code your program for you
idk im confused as hell
!e @slate swan here is how I'd personally go about displaying a 2D list:
my_2d_list = [["row 1 col 1", "row 1 col 2"], ["row 2 col 1", "row 2 col 2"]]
print("\n".join([" | ".join(row) for row in my_2d_list]))
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | row 1 col 1 | row 1 col 2
002 | row 2 col 1 | row 2 col 2
also what's the point of this?
yeah that'll do
idk
imports
and you have to import numpy 5 times?
i do?
no, i'm asking why you would do that
About what?
bc i was bored
you were bored so you needed to import numpy 5 times?? i don't get it
FWIW I do idly do :w when I'm thinking, lol
broo
lol
you're not helping us understand your problem, both me and robin have provided solutions
its still like this kinda dumb
you already showed that screenshot 3 times too
show your updated code please
ok
let me
try
again
im dying
@sick birch @smoky sinew
π
@smoky sinew @sick birch
you don't need to ping me twice
ok
you're only joining one row together and returning immediately after
what do i do then

