#discord-bots
1 messages ยท Page 282 of 1
Print it out again and see
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
if "s" in time:
gettime = time.strip("s")
if int(gettime) > 2419200:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(seconds=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "m" in time:
gettime = time.strip("m")
if int(gettime) > 40320:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(minutes=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "h" in time:
gettime = time.strip("h")
if int(gettime) > 672:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(hours=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "d" in time:
gettime = time.strip("d")
if int(gettime) > 28:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(days=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
@timeout.error
async def say_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**You don't Have permissions to use this command**")
elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")
elif isinstance(error, commands.BotMissingPermissions):
await ctx.reply("**The bot does not have permissions to make this action**")โ
What you advice me to add or edit in this command
Why does your command break if i put sss, s or anything which is missing a integer, or 9s9
Also why can't I do 1s 55m etc...
Break?
There is bad argument error
I mean thats my point
I can be more specific about the duration, which you dont support
Who will type 10ssssss
Users will always break something
guys i lost my usb key where i run all my scripts, does smn know how can i get them back with computer memory or logs idk ..?
When them breake it the bot will reply to them to type it in the right way
Does BadArgument catch value errors?
I'll try
I also dont think that error catch works...
isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument) will always be true, because you're doing if condition or <tuple> so I think you've missed a isinstance
Btw, I'd recommend using https://pypi.org/project/humanize/ to parse durations, rather than attempting to do it yourself, it'll be a nicer user experience
Look at what happend
!e ```py
print("100sec".strip("s"))
print(int("100sec".strip("s")))
@night crater :x: Your 3.11 eval job has completed with return code 1.
001 | 100sec
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 3, in <module>
004 | print(int("100sec".strip("s")))
005 | ^^^^^^^^^^^^^^^^^^^^^^^^
006 | ValueError: invalid literal for int() with base 10: '100sec'
as broke the command but it easy to solve
Nah didn't broke
It was just offline
And I will solve the 10ssss thing
But didn't understand wdym by 1s 55m
Hi, I was making a discord music bot, and eveything is fine but when I try to make slash commands and I'm importing a discord_slash it's says it isnt installed but I installed everything.
this is my code:
import pytube
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
ffmpeg_path = "ffmpeg.exe"
ffmpeg_version_cmd = [ffmpeg_path, "-version"]
intents = discord.Intents.default()
intents.typing = False
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix='?', intents=intents)
its pretty empty beacuse i'm doing it from start again, if you want I can send the full code where the same issue also was. Thanks for all help!
(and pls ping me when you repling)
Why use an additional package when discord.py supports slash commands
We cant help anyways
!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 Need Discord Ticket Claim Script python
Anyone know if it's possible to silence the "This form is being submitted to XXXXX Bot" on modals? I'm running the bot on my own server. It makes sense why it's there, though!
No you cant remove it
Makes sense, thanks!
๐
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
if "s" in time:
gettime = time.strip("s")
if int(gettime) > 2419200:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(seconds=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "m" in time:
gettime = time.strip("m")
if int(gettime) > 40320:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(minutes=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "h" in time:
gettime = time.strip("h")
if int(gettime) > 672:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(hours=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "d" in time:
gettime = time.strip("d")
if int(gettime) > 28:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(days=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
@timeout.error
async def say_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**You don't Have permissions to use this command**")
elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")
elif isinstance(error, commands.BotMissingPermissions):
await ctx.reply("**The bot does not have permissions to make this action**")โ
Discord is ratelimiting you, try again later
i can fetch a message from a channel from my own bot, even with message content intent disabled right?
Yes, fetching messages is done over HTTP and intents only apply over gateway
okay thanks
anyone willing to help me combine some discord bots source codes .-.
technically you can always fetch a message object as long as your bot has permissions to read it, but you need message content enabled in the dev portal for fetch_message() to return content/embeds/attachments (other than DM/mention exceptions), regardless of what you set it in your code
@commands.command()
async def profile(self, ctx, member: discord.Member = None):
member = member or ctx.author
id = str(member.id)
data = collection.find_one({"_id": id})
if not data:
return
else:
userBal = data.get("bal")
userPokeDex = data.get("inv")
if ',' in userPokeDex:
pokemonList = userPokeDex.split(',')
pokemonCount = len(pokemonList)
elif userPokeDex==None:
pokemonCount=0
else:
pokemonCount=1
description = f"**Current Balance:** {userBal:,} PokeCoins\n**Pokemons Caught:** {pokemonCount}"
embed = discord.Embed(title=f"{member.name}'s Profile", description=description, colour=discord.Colour.orange())
embed.set_thumbnail(url=member.avatar or member.default_avatar)
embed.set_footer(text=f"{time.strftime('%I:%H %p', time.localtime())}")
await ctx.reply(embed=embed)
bot won't respond when the user's inv is None
well yeah because you're returning?
that part will invoke only if the user's id is not in the database
Ah, do you get an error then?
if userPokeDex was None, ',' in userPokeDex should have thrown a TypeError...
oh mb
hi im learning python to learn how to make discord bots. what other things do I need to learn to be proficent in discord bots?
apis and related principles, oop and asynchronous programming
perhaps a db too if u want to make any extensive bot
whats oop?
object oriented programming
You need help?
Lemme see
Nothing happens as in?
It doesn't send the embed?
Do u have an error handler?
Do u have an else statement in there?
Show the whole traceback
In the else statement, instead of writing print(error), do raise error
!e [1][1]
@sick birch :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | [1][1]
004 | ~~~^^^
005 | IndexError: list index out of range
He isn't doing any list indexing in the code given, so I think it's due to another reason
But u r not directly indexing it
I get that
Show the whole traceback after doing what I told
Robin showed you above
!e
list = ['a','b','c']
list[6]
@maiden fable :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | list[6]
004 | ~~~~^^^
005 | IndexError: list index out of range
It means you're trying to access an item in a list that doesn't exist
For instance, trying to get the 10th item of a list that only has 5 items
Can u show the code for on_command_error
nope, could be a pydroid thing
Most suitable explanation tbh ^
Try the same code on yr laptop
Issues can popup all of a sudden sometimes
Don't tell me the list was empty
Breh
Oh so like u cut and pasted the whole list outside the function?
Heh
That's cz u removed the random.choice line...
It isn't in the screenshot ๐คท
Weird but okay if it works
how do you make a parameter optional, idk if thats worded properly but an input field that isnโt required to be filled out
trying to make a bot that changers discord server pfp and it giving me async with outside async function syntax error dk why
async def serverpfp(session):
print("Changing server pfp...")
url = f'https://discord.com/api/v9/guilds/{guild_id}'
headers = {
'Content-Type': 'application/json'
}
async with session.patch(url, headers=headers, json=payload)
await session.guild.edit(name="testing rename and redit",
description="hi",
reason="test",
icon=icon,
banner=None)
how do i get it inside?
!e give it a default value ๐คท
def a(b: int = 0):
# ^^^ default value
print(b)
a()
a(1)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
async def serverpfp(session):
async with session.patch(url, headers=headers, json=payload)
await session.guild.edit(name="testing rename and redit",
description="hi",
reason="test",
icon=icon,
banner=None)
print("Changing server pfp...")
url = f'https://discord.com/api/v9/guilds/{guild_id}'
headers = {
'Content-Type': 'application/json'
}
``` like this? mb if its a dumb question one of my first times playing around with bots
yes
ok
that's still wrong, at this point you're most likely missing some python basics
my code:
https://sourceb.in/ByGWtr5qr2
my error:
2023-08-07 07:05:03 ERROR discord.ui.view Ignoring exception in view <TrashButton timeout=None children=1> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Delete the ticket' emoji=<PartialEmoji animated=False name='๐ฎ' id=None> row=None>
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 464, in trash
open_tickets -= 1
UnboundLocalError: local variable 'open_tickets' referenced before assignment```
ik i m doing something stupid so please help this stupid person
i managed to get the script running. rename works but didnt change server pfp
Totally not because you define the variable after the code where you need to use it
how do i create a clientsession object attribute for guild
like aiohttp one?
ye
why do u want on for guild make it for the bot or cog no?
im tryna make it change server pfp i added it i think but same error it renamed channel but didnt change the server pfp
@shrewd apex :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | None.guild_url
004 | AttributeError: 'NoneType' object has no attribute 'guild_url'
attribute dosent exist
async def serverpfp(session):
guild_url = f'https://discord.com/api/v9/guilds/{guild_id}'
url = f'https://discord.com/api/v9/guilds/{guild_id}'
headers = {
'Content-Type': 'application/json'
}
async with session.patch(url, headers=headers, json=payload)
await session.guild_url.edit(name="testing rename and redit",
description="hi",
reason="test",
icon=icon,
banner=None)
print("Changing server pfp...")
```
i tried creating one i think but got stuck
with open('duck.png', 'rb') as f:
icon_icon = f.read()
Anyone, can you give me sample discord bot for moderate and music in GitHub???๐ข
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
if "s" in time:
gettime = time.strip("s")
if int(gettime) > 2419200:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(seconds=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "m" in time:
gettime = time.strip("m")
if int(gettime) > 40320:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(minutes=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "h" in time:
gettime = time.strip("h")
if int(gettime) > 672:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(hours=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "d" in time:
gettime = time.strip("d")
if int(gettime) > 28:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(days=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
@timeout.error
async def say_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**You don't Have permissions to use this command**")
elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")
elif isinstance(error, commands.BotMissingPermissions):
await ctx.reply("**The bot does not have permissions to make this action**")โ
What the errors I should add to this command to be perfect?
i would just make a Converter for time and handle errors about it in the converter
A hands-on guide to Discord.py
Wdym by time converter
check the link 
how do i exactly get at using python to make a discord bot in the first place?
Do you already know python basics
ive watched a few videos so id like to think i have it down
i know how to use the discord dev portal and stuff
Do you know topics Like async programming and OOP?
Its needed in order to start making a discord bot
In a function rather than doing this
if something_bad:
await send("Too bad")
else:
await bruh1()
await bruh2()
You should
if something_bad:
await send("Too bad")
return
await bruh1()
await bruh2()
This greatly reduces amount of indents, improves code readability and makes your code logic simpler
And imo you're making too many unnecessary checks
!pypi durations-nlp just use this
nope, guess ive got to read up on that next then after i get python down
Finished writing my first ever discord bot
. Honestly, it was easier than I expected thanks to very well written documentation from discord.py
discord.py is one of the best documented modules out there
I saw a guy on fiverr who makes discord bots for 750 dollars
send url
If he doesn't get any orders he's just an idiot
can I send it here
I dont see why not
I don't think so
even I never had an order.... I'm an idiot!!
wtf
tbh disnake >>
140 orders
yeah nah
disnake has even a guide
140 orders 8 in queue
you can get a bot for only 1.1k!
what boosts your orders on fiverr are reviews so...
they are not even hard bots lmao
yeah but no you have to make false orders and reviews at the start
people have too much money
I've been there, no one orders from those who have no reviews
I want to start on fiverr tbh
idk where tho
average autistic users pov
that man doesn't even speak english
please give me the enough permissions to do the commands
that's tough
some people are too lonely
you gotta be kidding me rn
make a dict instead of replacing 26 times
3d screen
that is officially the most useful thing on discord
Nice idea
what is a partial interaction message? im just tryna get a message id from a message my bot sent
I did msg = await ctx.send(...)
msg.id
got it, needed to fetch the message
nah it was a partial interaction message
most of the attribute from discord.Message arent there
like the id
What library are you using
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
if "s" in time:
gettime = time.strip("s")
if int(gettime) > 2419200:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(seconds=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "m" in time:
gettime = time.strip("m")
if int(gettime) > 40320:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(minutes=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "h" in time:
gettime = time.strip("h")
if int(gettime) > 672:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(hours=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
elif "d" in time:
gettime = time.strip("d")
if int(gettime) > 28:
await ctx.reply("Timeout time can't be more than 28 days")
else:
newtime = datetime.timedelta(days=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out for " + time)
@timeout.error
async def say_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**You don't Have permissions to use this command**")
elif isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
await ctx.reply(f"Please use the command in the correct way \n `{prefix}timeout (member) (time)`")
elif isinstance(error, commands.BotMissingPermissions):
await ctx.reply("**The bot does not have permissions to make this action**")โ
How can I add timeout reason
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
The reason argument ๐คท
Ok
nextcord
from discord import app_commands
class button_view(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout = None)
discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify")
async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
if type(client.role) is not discord.Role:
client.role = interaction.guild.get_role(1138104211876356217)
if client.role not in interaction.user.roles:
await interaction.user.add_role(client.role)
await interaction.response.send_message(f"I have given you {client.role.mention}!", ephermal=True)
else: await interaction.response.send_message(f"You already have {client.role.mention}!", ephermal=True)
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default)
self.synced = False
self.role = 1138104211876356217
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
#await tree.sync(guild = discord.Objectt(id=))
self.synced = True
if not self.added:
self.add_view(button_view())
self.added = True
print(f"logged in as {self.user}")
client = aclient()
tree = app_commands.Command.Tree(client)
@tree.command(guild = discord.Object(id=1138103534101987348), name = "test", description = "role button")
async def button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view())
client.run("")```
You probably have an older version of discord py or using a fork
Run pip freeze
Yeah that's an old version
how do i update
python -m pip install -U discord.py
Add () after discord.Intents.default
๐คฆโโ๏ธ
tree = app_commands.Command.Tree(client)
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Command' has no attribute 'Tree'```
CommandTree not Command.Tree
slash command isnt showing
Did you sync it?
i should of i dont have a print
Could you show the sync?
from discord import app_commands
class button_view(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout = None)
discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify")
async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
if type(client.role) is not discord.Role:
client.role = interaction.guild.get_role(1138104211876356217)
if client.role not in interaction.user.roles:
await interaction.user.add_role(client.role)
await interaction.response.send_message(f"I have given you {client.role.mention}!", ephermal=True)
else: await interaction.response.send_message(f"You already have {client.role.mention}!", ephermal=True)
class aclient(discord.Client):
def __init__(self):
super().__init__(intents = discord.Intents.default())
self.synced = False
self.role = 1138104211876356217
self.added = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
#await tree.sync(guild = discord.Objectt(id=))
self.synced = True
if not self.added:
self.add_view(button_view())
self.added = True
print(f"logged in as {self.user}")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(guild = discord.Object(id=1138103534101987348), name = "test", description = "role button")
async def button(interaction: discord.Interaction):
await interaction.response.send_message(view = button_view())```
didnt mean to send everything
Is this all your code?
ye
You aren't even starting the bot.
discord.ui.button(label = 'verify', style = discord.ButtonStyle.green, custom_id = "verify") this should be decorator -> add @ before
i am lol
yea i forgot to add that
tree is app_commands.CommandTree
I just asked if this was all your code ๐ข
i see the aclient class like 3rd time ๐ตโ๐ซ
Although I'd recommend using commands.Bot instead of discord.Client if you want commands
i just want my slash cmds to work
For slash commands I recommend Client.
no need for Bot if not using prefixed commands
Well you need to sync them first.
i thought i already did
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
#await tree.sync(guild = discord.Objectt(id=))
self.synced = True
if not self.added:
self.add_view(button_view())
self.added = True
print(f"logged in as {self.user}")
``` you never sync
the only line that would sync it commented out
Why not in the setup_hook?
i copied it from his code
i can just make a sync command right
not mentioning it shouldnt be done in on_ready just saying why its not syncing up now
You could but then you will have both message and slash commands.
oh yeah ur right
Hikari auto syncs it ๐
idk how to sync my slash command i thought they were all good
just sync it in setup_hook
and how
disnake too!!
nextcord too 
'just move' move what exactly
the part that syncs the commands?
you sent this code.
the part that syncs the command
alr bro just keep saying the part
didnt you code it?
๐ฅถ
anyone here can help me run this discord bot file i will screenshare
why cant you run it
im trying to make the bot add a role to new users when they join my server
I have this event all setup but for some reason it doesnt add the role with no errors
!d discord.Guild.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel) or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread) with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread) instead.
New in version 2.0.
you fetch a channel using int not string
using string not int*
this part works its just not adding the role
the fetch works?
when someone joins it sends the message in the right channel
what verision are you on?
so yes. But I did the same thing for the role but it doesnt work
where is the role adding part?
bottom 2 lines
await fetch_roles()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the guild has.
Note
This method is an API call. For general usage, consider [`roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.roles) instead.
New in version 1.3.
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
await member.guild.add_roles(role)
ohhh oke
more like Role object
or could be discord.Object(id=role_ID)
Was boutta say just use snowflakes
this is what I did
its Member method not Guild
?

is it await member.add_roles(role)
You cannot add roles to guild only create them.
this didnt work
thats not what im doing

ikkk
show me the error when using that
@formal basin 
await member.add_roles(role) is not the same as await member.guild.add_roles(role)
hey guys ! do someone know a way to add a music system using slash commands to my discord bot ?
https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py
its not with slash commands but i guess you can convert it to use them
thx i'll check it later
bro this uses youtube_dl

Is there a way to make it so that for a slash command when you have a certain role, the output of the command is diff
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
If there a way to make it so for example if a user has a role called โ1โ they do a command and it gives them an output message of 1, but if he had a role called โ2โ the command gives them an output message of 2
Im thinking ifs and elifs also im a beginner to python so im still figuring stuff out
Alr ty
sooooo
take away the guild part and it works?
Try and see
Hey I need some help
the discord bot doesn't delete its message after it tells the user to not swear
import time
import discord
# Define the required intents
intents = discord.Intents.default()
intents.message_content = True
bad_words = ["fuck", "shit", "bitch"]
client = discord.Client(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('$hello'):
await message.channel.send('Hello!')
# Swears function to check and delete messages containing swear words
async def swears(user_say):
if any(word in user_say.lower() for word in bad_words):
response_message = await message.channel.send("Hey!, don't swear")
await message.delete()
time_to_delete = 5 # Specify the time in seconds after which the response message will be deleted
time.sleep(time_to_delete)
await response_message.delete()
await swears(message.content)
await swears(message.content)```
Here's the code. The delete code is near the bottom
and the bad_words list is at the top near the intents variable.
I am using the time.sleep
to make it delete after 5 seconds
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
delete_after kwarg
where would I put that
when you send
Alr
Hey! i needed some help. I want to start make a custom bot for discord. But i dont now where and how i can started. Where do i need to make mine scripts and where can i make mine bot? So much quistions....
Tag me if someone answer
in order to make a discord bot you need good knowledge of python
topics like OOP or async/await programming should be familiar to you
Uhmmm i dont now what your talking
i am a noob for making discords bots on progamma like this. I used always a simple app but i want to make it harder and better for me.
start learning async/await syntax and maybe OOP and you are good to go
if you know basics already
also decorators, just know what they are no need to know how to define one
how can i learn that? sorry for my dump quistions
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ok ty!
The resource page includes OOP.
thats the one i found on this list
And it's all you need.
not workin'
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)
come dm so
thats not how it works
like it work but its not playing music
Why did you link it then lmao
๐คซ
Because it's missing something.
no i pasted the code from the page and filled it with my infos
Correct but the code is just the interface of communication.
I can't tell more without being smitten by the Discord mods. But it's not yet complete.
it's the default answer to music player help
That's new, it was way stricter previously.
wdym
That people got slain by the !ytdl some years ago.
lol
There was also this one tutorial that a lot of people used that was just bad.
It was a nightmare.
code with swastik
literally his tutorial (idk if he copeid code or if it was from him, I just watched that tutorial)
dm if you can make a bloxflip bot i pay 10 dollars to 50 dollars
!rule paid
tf is bloxflip
Well it's not good practise.
10 dollars
ik, I no longer use json to store my data
I use it as my main programming language
id love that networking and microcontroller channels where as active as this one
i saw once activity stats and the discord-bots channel had the most activity
is it somewhere here
data should be stored either in .txt files on in discord channels lmao
idk
python general is unbeatable
there's no stop
i sent like 5 messages here
I have a botnet of discord bots, and encode the data in base64 on their usernames
when I need data I start the bot and make it send it's username to an api
cool
is there something worse than json for storing stuff?
dam how did i get it so right
I sent 860
txt files
Had indeed, because rapptz stopped.
is rapptz in here?
He has his own dpy server idk.
the discord.gg/dpy ?
no
Yeah he's the owner.
danny
just saw that
but hes not here
tf is this a new thing?
yeah
integrations can edit your profile and show information
this is incredible
?
try it out
this apply button is scary
trust it
yo what the
he got a point ngl
this C# right
yeah
@slate swan It has been in Discord since v8 appereantly.
if talking about api version then v10 is latest
ye
but looks like you cant make your own build override
Yep just saw you will get a 403
im alpha android tester and never seen this
Not alpha enough
whats before alpha then
Experiments settings have this
experiments settings?
Yeah found that one too
Vencord ๐ง
Yeah it's from the vid
it didnt work 
mhm
๐
My name isn't there, not proof, maybe I'll slip up once.
If I had it which I don't
๐ฟ
its a big file its complicated
!paste send it then
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
what do you mean its file
yeah so why dont you paste the main.py code to paste service
did you get it from github repo by any chance
its a discord bot yeah
i wanna see if it can run
What project structure do you guys usually do?
what project structure i just do everything in one file and have 20k lines

so send a link to it
then it is 2 files
yeah one for code and one for data
with open(".") as f:
what stops you from trying
sure thing
looks like there should be like config.py file with config varriables but its not present
judging from the Notice in readme This project is currently a work in progress and should not be utilized at this time. it is not finished
someone ran it
idk he wont show me
is something wrong with this command? It doesnt work
define doesnt work
what do you mean?
what do you mean what do i mean?
lol
no errors?
yea
do you have an error handler?
no, how can I make one?
well i was just wondering if it was throwing an error that was being consumed by an error handler
ah okay
can you show your full code minus your token
hmm i think hybrid_commands get command context instead of interactions
yup
try async def sync(ctx: commands.Context)
So anyone experienced with Python Discord bots who could help me?
I need to combine two commands, into 1 functio/command
Just ask your question
Do you want to come discord channel & help me?
Yes, but my code has value
Im not going to put it in here for 500k people to copy it
if you want to help, you want to help, if not thats fine
no ones taking ur code lmao
Sure there are
this discord channel sure is full of rude piss kids
Forgive me asking
try adding await bot.process_commands(message) to your on_message call
or change @bot.event to @bot.listen()
thankss, this worked
:D
is it also possible to "unsync" commands?
because there are some commands synced that i dont have in the code anymore
Why?
ah, do tree.clear_commands(), then sync, then sync again without clearing
ah thanks
Okie dokies. Im back for more abuse ๐๐ซ ๐คฃ
I have finished creatibg my ERC20 with the functions I need.
Next up is creating a Discord bot to have functions to interact with the contract to purform token purchases through discord.
What is the main interest in discord bots? Why do them ?
Many people are drawn to it because it's on a platform they're already familiar with, and you get to directly interact with your code and see it run
can you make home automation alert via a bot to you ?
or does it need to connect to a server
not sure what you mean by "alert via a bot to you", but if you just want to send messages to a discord channel (which can give you push notifications) you can do that without even writing a discord bot, a simple POST request to a webhook is all that's needed
https://discord.com/developers/docs/resources/webhook#execute-webhook
if you need real-time information from discord or certain information not provided by their API like member statuses, then you'd have to stay connected to their websocket gateway
Yeh just thinking of fridge door open (already get that) but say dog pooped or something ๐ . Thanks for the info.
@commands.guild_only()
@bot.hybrid_command(name="unban", description="Unban a user with a reason")
@app_commands.describe(member="The user ID to unban")
@app_commands.describe(reason="The reason for unbanning")
async def unban(ctx, member: int, reason: str):
# Check if the user invoking the command has the allowed role
allowed_role = discord.utils.get(ctx.guild.roles, id=MODERATOR_ROLE)
if allowed_role in ctx.author.roles:
try:
user = await bot.fetch_user(member)
await ctx.guild.unban(user, reason=reason)
await ctx.send(f"{user.mention} has been unbanned for {reason}")
except discord.NotFound:
await ctx.send("User not found.")
else:
await ctx.send("You do not have permission to use this command.")```
not sure why its saying that
it's funny but discord IDs are too big so you should annotate it as str
really?? lol alright
how to check if he string entered is not alphabtes? like a check?
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
thank you
just an if in your code should work
yup, i jjust needed to know the function! thanks a lot!
you're welcome
so i m getting this:
An error occurred while trying to ban the user: 403 Forbidden (error code: 50007): Cannot send messages to this user
but i am unsure if its my bots perms or my alts privacy.... the bot has all the intents and all perms from the dev portal, in the privacy of my alt the dms can be sent by anyone
It cannot DM a user it doesn't share a mutual server with
ahhhh okokok that was the problem
Anyone looking to work collaboratively on a Discord.PY bot? Iโm not looking to lead the project, only looking to help develop it.
Pm me if you need someone. (Iโm not charging)
๐ฟ ๐
You should use aiohttp for discord bots
Is this a good way to storage data for every User, Guild and Member?```python
Storage System
database = {'guilds':{}, 'users':{}}
class GuildData:
def init(self, guild_data:dict) -> None:
self.members = {}
self.dict.update(guild_data)
def as_dict(self):
data = self.__dict__
return data
class MemeberData:
def init(self, member_data:dict) -> None:
self.dict.update(member_data)
def as_dict(self):
data = self.__dict__
return data
class UserData:
def init(self, user_data:dict) -> None:
self.dict.update(user_data)
def as_dict(self):
data = self.__dict__
return data
def load_data():
for guild in bot.guilds: # Load GuildData + MemberData
print(guild.name, guild.id)
if guild.id not in database['guilds']:
database['guilds'][guild.id] = GuildData({}).as_dict() #{'members':{}}
guild.data:GuildData = GuildData(database['guilds'][guild.id])
for member in guild.members:
if member.id not in database['guilds']['members']:
database['guilds']['members'][member.id] = MemeberData({}).as_dict()
member.data:MemeberData = MemeberData(database['guilds'][guild.id][member.id])
for user in bot.users: # Load UserData
if user.id not in database['users']:
database['users'][user.id] = UserData({}).as_dict()
user.data:UserData = UserData(database['users'][user.id])
so that you can access the data like this: bot.get_user(2187412712386).data
I would be happy if someone would give their opinion on this :D
depends
I suppose you want it temporary right?
and why would you do that?
if someone leaves or joins a guild you're outdated
no, like i want to store the "database" in a file
why?
not yet
but why isnt it allowed?
that's cool
no xD i mean is it fine?
Depend on how you use the data.
I think it would be a missuse of space tbh
not all users will use the bot once
Discord does request that if the bot is no longer in the guild to remove the data.
Yes, I will add that, of course, but actually I was concerned with whether the concept is good ๐
Any reason why you would need to store it?
yes
But yeah I recommend using a database like postgres
Why? Just because you don't like writing SQL? There are alternatives to that
What alternatives?
ORMs, nosql databases
No, dataclasses are a better way if you want this kind of organisation
!e ```py
import dataclasses
@dataclasses.dataclass(repr=True)
class Member:
id: int
name: str
discrim: str
m = Member(1, "hello", "0123")
print(m)
@meager rock :white_check_mark: Your 3.11 eval job has completed with return code 0.
Member(id=1, name='hello', discrim='0123')
can a dataclass be transformed to json format?
Just make a method for that
https://github.com/externref/pinaka/blob/main/src/utils.py#L6-L9
I wrote a derivable for that
src/utils.py lines 6 to 9
class AttrsClassToPayload:
def to_payload(self) -> typing.Dict[str, typing.Any]:
attrs: list[str] = [a.name for a in self.__attrs_attrs__ if not a.name.startswith("_")] # type: ignore
return {key: getattr(self, key) for key in attrs}```
just replace attrs_attrs to __dataclass_params__ here
attrs ๐๐
It's so complicated ๐ฅฒ
!e
from dataclasses import dataclass
@dataclass(slots=True)
class A:
b: int
c: int
print(A.__dataclass_fields__)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'b': Field(name='b',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD), 'c': Field(name='c',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f3e2fa6c850>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=False,_field_type=_FIELD)}
They use a different attribute name hmm
I mean you can still use .__dict__ on it, but that will also include the internals like eq init and other methods
i think we have to switch channels to -> databases

class VerifyButton(discord.ui.View):
@discord.ui.button(label="ใ๐ฐ ใVerify.", style=discord.ButtonStyle.success)
async def button_callback(self, button, interaction):
await interaction.response.send_message("you are verified!")
@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())
I get this when i click the button
23-08-08 13:50:44 ERROR discord.ui.view Ignoring exception in view <VerifyButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='ใ๐ฐ ใVerify.' emoji=None row=None>
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "<string>", line 4, in button_callback
AttributeError: 'Button' object has no attribute 'response'
okay thanks
2023-08-08 14:03:50 ERROR discord.ui.view Ignoring exception in view <VerifyButton timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='ใ๐ฐ ใVerify.' emoji=None row=None>
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "<string>", line 4, in button_callback
File "/home/fady/.local/lib/python3.10/site-packages/discord/member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
class VerifyButton(discord.ui.View):
@discord.ui.button(label="ใ๐ฐ ใVerify.", style=discord.ButtonStyle.success)
async def button_callback(self, interaction: discord.Interaction, button):
await interaction.user.add_roles('verify')
@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())
sry
class VerifyButton(discord.ui.View):
@discord.ui.button(label="ใ๐ฐ ใVerify.", style=discord.ButtonStyle.success)
async def button_callback(self, interaction: discord.Interaction, button):
await interaction.user.add_roles('verify')
@bot.tree.command(name = 'verify', description = 'Makes the verify area in a spesific channel.')
async def test(interaction: discord.Interaction):
await interaction.response.send_message('Click the "Verify" button to get verifird.', view = VerifyButton())
yeah so .add_roles expects Snowflake but you gave it string
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
either get the role id and do discord.Object(id=YOUR_ROLE_ID) or if you only have the name use discord.utils.get helper method
thx
https://discord.com/channels/267624335836053506/965291480992321536
check pinned messages here
ty
can you send please the message link ?
thanks
2023-08-08 14:13:22 ERROR discord.app_commands.tree Ignoring exception in command 'purge'
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "<string>", line 13, in purge
File "/home/fady/.local/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
flags.ephemeral = ephemeral
File "/home/fady/.local/lib/python3.10/site-packages/discord/flags.py", line 87, in __set__
instance._set_flag(self.flag, value)
File "/home/fady/.local/lib/python3.10/site-packages/discord/flags.py", line 198, in _set_flag
raise TypeError(f'Value to set for {self.__class__.__name__} must be a bool.')
TypeError: Value to set for MessageFlags must be a bool.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: Value to set for MessageFlags must be a bool.
@bot.tree.command(name = 'purge', description = 'Deletes a set amount of messages from this channel.')
@app_commands.describe(amount = 'How many messages should we delete(max = 1000, min = 1)?')
async def purge(ctx, amount: int):
if amount < 1:
await ctx.send('The amount must be grater than 1.', ephemeral = True)
return
elif amount > 1000:
await ctx.send('The amount must be less than 1000.', ephemeral = True)
return
await ctx.channel.purge(limit=amount)
await ctx.response.send_message(f'Succsessfuly deleted {amount}.', ephemeral = 'True')
it deletes the messages
but it doesnt semd the "Succsessfuly deleted {amount}." message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
i dont understant
what do i need to do ??
023-08-08 14:21:22 ERROR discord.app_commands.tree Ignoring exception in command 'purge'
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "<string>", line 13, in purge
File "/home/fady/.local/lib/python3.10/site-packages/discord/interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "/home/fady/.local/lib/python3.10/site-packages/discord/webhook/async.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
@bot.tree.command(name = 'purge', description = 'Deletes a set amount of messages from this channel.')
@app_commands.describe(amount = 'How many messages should we delete(max = 1000, min = 1)?')
async def purge(ctx, amount: int):
if amount < 1:
await ctx.send('The amount must be grater than 1.', ephemeral = True)
return
elif amount > 1000:
await ctx.send('The amount must be less than 1000.', ephemeral = True)
return
await ctx.channel.purge(limit=amount)
await ctx.response.send_message(f'Succsessfuly deleted {amount}.', ephemeral = True)
looks like the response has been deleted
how about you do ctx.channel.send
async def swears(user_say):
if any(word in user_say.lower() for word in bad_words):
response_message = await message.channel.send("Hey!, don't swear")
await message.delete()
await response_message.delete(delay=5) # Delete the response message after 5 seconds
await swears(message.content)
await swears(message.content)``` When the user swears it's supposed to delete the bot message 5 seconds after it posted the message of not to swear. But instead it posts that same message 5 times.
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
delete_after kwarg ^
Bro im new to discord bots
Idk what you're talking about
"Delete_after kwarg"
Bro like Idk what that does
if you dont understand what that means you shouldnt be making a discord bot project
you need intermediate knowledge about python to make one
??? The whole point of making a discord bot is to learn
its not a good project to learn trust me
Also this explains nothing.
Whats a good project then
!kindling
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
I hate that site
if you would click the link it would make sense
why?
delete_after (float) โ If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
New programmers often need small projects to work on as they hone their skills. This is a list of project ideas that beginners can tackle.
im trying to send an embed as a dm to a user but i get an error saying that i can't
code: embed = discord.Embed(title="text", color=000000) embed.add_field(name = None, value=f"text") await user.send(embed=embed)
what's wrong with the code
What error?
Probably just means you literally can't send a message to them, dms closed, no shared server, etc.
Yes
the way i did should work right
Can you send normal messages?
yea it is
wait how do you turn on dms to all members for bots
like so they can accept dms
what
the dm was to a bot
how do you allow a bot to accept dms from all users
do you need to be in a server with the bot
to dm the bot
how do i install subprocess w/ requirements.txt ?
Subprocess is stdlib though?
what
like what do i put to install it with requirements.txt cuz i use pterodactyl for hosting the bot
You don't, subprocess is part of python, it's built in
!d subprocess
Source code: Lib/subprocess.py
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
os.system
os.spawn*
``` Information about how the [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess) module can be used to replace these modules and functions can be found in the following sections.
okay
but like its for running 2 bots on the same hoster
and i wanted to find how to do that
This wouldn't be an issue if you used a proper host (a VPS)
and is there free vps out there ?
and what system do i choose ?
Sure, aws, oracle
and like can i install pterodactyl ?
Where are you starting the task?
Why would you need to?
because i'm running bots on it
what
like if i install windows on it it will not run 24/7
yes it will
the vps
oh rlly i didnt know that
so now i just set up a windows virtual machine and it wil stay on forever ?
If you don't implement it, no
Why are we talking about virtual machines now?
idk i need to install windows on aws so i need to set up a vm ?
Oh you mean that
Fyi people don't usually use windows for servers, usual Linux distros like debian
Yes
okay but i'll use windows im more comfy with it
that's fine
i have only 1gb of ram ?
As a whole or dedicated for bot?
What
๐
on the VM
Well did you modify the amount of ram to allocate when setting up the instance?
there wasn't a section for taht i searched
well, there is
dont have it there
ยฏ_(ใ)_/ยฏ
does discord.py slash commands use the http api?
nope, it uses the gateway
are there any libs which use the http api for slash commands?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 849, in _invoke_with_namespace
if not await self._check_can_run(interaction):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 987, in _check_can_run
return await async_all(f(interaction) for f in predicates)
File "/home/container/.local/lib/python3.10/site-packages/discord/utils.py", line 705, in async_all
elem = await elem
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/checks.py", line 407, in predicate
raise CommandOnCooldown(bucket, retry_after)
discord.app_commands.errors.CommandOnCooldown: You are on cooldown. Try again in 95.41s
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
await self._call(interaction)
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1252, in _call
await self.on_error(interaction, e)
File "/home/container/zagzag.py", line 1122, in on_app_command_error
await interaction.followup.send(error, ephemeral=True)
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1805, in send
data = await adapter.execute_webhook(
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
command = interaction.command.name
channel2 = client.get_channel(1112053260879147130)
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.followup.send(error, ephemeral=True)
else:
button = Button(label="support server", url="")
view = View()
view.add_item(button)
embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
embed.add_field(name="",value="Reasons why you might have gotten this error")
embed.add_field(name="Reason 1 ", value=""
"Make sure the bot role is is on the top. Server settings > Roles > Drag the bot role (zagzag) to the top")
embed.add_field(name="Reason 2", value=""
"Make sure the bot has the right permissions. The permissions this bot needs: ``send messages``, ``read channel history``, ``time out members``, ``kick members``, ``ban members``, ``manage server``, ``manage messages``, ``attach files``, ``add reactions``, ``manage nicknames``")
embed.add_field(name="", value="If you have Done all the steps above and the bot and you still get this error join the support server. ")
await interaction.followup.send(embed=embed, view=view)
await channel2.send(f"{command} command used by {interaction.user} but an error occured")
traceback.print_exc(limit=None, file=None, chain=True)
the error doesnt send
There is no followup webhook because you haven't responded
Use response.send_message
@bot.tree.command(name = 'kick', description='Kicks a user from this server.')
@app_commands.describe(user = 'Who do you want to kick?', reason = 'Why do you want to kick them?')
@commands.has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, user: discord.User, reason: str = None):
await user.kick(reason=reason)
await interaction.response.send_message(f'Succsesfuly kicked {user} by {interaction.user.mention}!', ephemeral = True)
```
it doesnt check for the permissio
Welp the method u are using is for prefix commands
is there a way here???
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...

im aware of hikari
!pip hikari
the RestBot provides a HTTP interface
Hikari 
pls help
just remove the 7th line
you don't need two clients/bots
you only run one anyway
and you can remove line 5 too
don't need to enable members intent when you already have all intents
wdym SelfBotManager
is it a self bot that manages or a bot that detects self bots
@sweet steeple
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
We wont help with self bots
im tryna make a detector
i think im too bad at python to even start making that tho
my server got raided by bots so
not sure how you can detect self bots
except if it's not a bot but sends embeds
that's a self bot for sure
Didn't Discord fixed that already?
i guess not
i got raided 3 days ago โ ๏ธ
mfs kicked
800 memebrs in 2 minutes
yeah
Why do you even give some random people kick permissions
i figured that out
Some kid logged my community manager
How did someone even get the account's both email and password
token logged โ ๏ธ
Do people just share their Discord account's token as a habit
It's probably best not to roll your own security solution if you need to use it for real
Don't do that either, there are plenty of reputable anti-raid bots on the marketplace
free?
Probably
you can make discord bots in pretty much any language
is there a discord driver for lua?
Have anyone made a Discord bot in BF yet?
probably
Yes, discordia
html
thats not programming language ๐ฅธ
Well Robin said just language, not programming language.
๐ฅธ
can i host discord python bot with ubuntu server ?
yeah
how ?
but i can't install python3-pip
dam
how can I start using modals
this server really needs less moderation bru
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
just start using them i guess
Can I use TextChannel objects and Role objects?
and like can i run 2 bot on the same server ?
yes
inside a modal?
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 46, in <module>
exec(f.read())
File "<string>", line 15, in <module>
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 1975, in decorator
return Command(
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 666, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 833, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 792, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
fady@debian-hffn1at:~/Documents/Code/public/FlareMod$
This is my code
Yes
@app_commands.command(name="embed_message", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
app_commands.Choice(name="๐ด Red", value=0xff0000),
app_commands.Choice(name="๐ต Blue", value=0x0000ff),
app_commands.Choice(name="๐ข Green", value=0x00ff00),
app_commands.Choice(name="๐ฃ Purple", value=0x883af1),
app_commands.Choice(name="๐ก Yellow", value=0xffe34d),
app_commands.Choice(name="๐ Orange", value=0xff8000),
app_commands.Choice(name="๐ค Brown", value=0x845321),
app_commands.Choice(name="โซ๏ธ Black", value=0xffffff),
app_commands.Choice(name="โช๏ธ White", value=0x000000),
])
@app_commands.checks.has_permissions(administrator=True)
async def embed_message(self, interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
await interaction.response.defer()
if title!="" or message!="":
embed = discord.Embed(title = title, description = message, color = color)
if image!="":
embed.set_thumbnail(url=image)
if url!="":
embed.url=url
await interaction.followup.send(embed=embed)
else:
await interaction.followup.send("You must enter at least one title or message", ephemeral=True)
@embed_message.error
async def on_embed_message_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)
is this code inside a class?
Oh
i remember times when you could have dropdown inside
then why you have self inside?
idk
me neither
but why do i get that error
cause you have self
also if you use @app_commands.command this decorator outside Cog class you will need to add this command manually to bot
okay
@app_commands.command(name="embed", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
app_commands.Choice(name="๐ด Red", value=0xff0000),
app_commands.Choice(name="๐ต Blue", value=0x0000ff),
app_commands.Choice(name="๐ข Green", value=0x00ff00),
app_commands.Choice(name="๐ฃ Purple", value=0x883af1),
app_commands.Choice(name="๐ก Yellow", value=0xffe34d),
app_commands.Choice(name="๐ Orange", value=0xff8000),
app_commands.Choice(name="๐ค Brown", value=0x845321),
app_commands.Choice(name="โซ๏ธ Black", value=0xffffff),
app_commands.Choice(name="โช๏ธ White", value=0x000000),
])
@app_commands.checks.has_permissions(administrator=True)
async def embed(interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
await interaction.response.defer()
if title!="" or message!="":
embedmsg = discord.Embed(title = title, description = message, color = color)
if image!="":
embed.set_thumbnail(url=image)
if url!="":
embed.url=url
await interaction.followup.send(embed=embedmsg)
else:
await interaction.followup.send("You must enter at least one title or message", ephemeral=True)
@embed.error
async def on_embed_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)
it dosent sync
what did i just say?

okie
so i have a tasks.loop its kinda complicated, but as soon as 1 thing gets stuck the whole loop doesnt run anymore, what is the problem?
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 46, in <module>
exec(f.read())
File "<string>", line 17
embedmsg = discord.Embed(title = title, description = message, color = color)
IndentationError: unexpected indent
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Test
Test\nTest
it didnt make a new line
@bot.tree.command(name="embed", description="Create a embed message")
@app_commands.describe(title="The title of your message", message="Your message", color="Embed color", image="Add an image to your message (with image's url : http(s)://...)", url="Add an url to your message (http(s)://....)")
@app_commands.choices(color=[
app_commands.Choice(name="๐ด Red", value=0xff0000),
app_commands.Choice(name="๐ต Blue", value=0x0000ff),
app_commands.Choice(name="๐ข Green", value=0x00ff00),
app_commands.Choice(name="๐ฃ Purple", value=0x883af1),
app_commands.Choice(name="๐ก Yellow", value=0xffe34d),
app_commands.Choice(name="๐ Orange", value=0xff8000),
app_commands.Choice(name="๐ค Brown", value=0x845321),
app_commands.Choice(name="โซ๏ธ Black", value=0xffffff),
app_commands.Choice(name="โช๏ธ White", value=0x000000),
])
@app_commands.checks.has_permissions(administrator=True)
async def embed(interaction: discord.Interaction, title: str, message: str, image: str = None, url: str = None, color:int = 0xff0000):
await interaction.response.defer()
embedmsg = discord.Embed(title = title, description = message, color = color)
if image != None:
embed.set_thumbnail(url=image)
if url != None:
embed.url=url
await interaction.followup.send(embed=embedmsg)
@embed.error
async def on_embed_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(f"{interaction.user.mention}, you don't have the required permission(s) to use this command.", ephemeral=True)```
yeah but it was sperimental, they rolled it back after some time
yeah i felt it i had already made a functionality with it and then they removed it xd
discord developer idea: let's roll back dropdown in modals, let's do activities, super reactions and other shit instead
i dont want to send anything, but i want to complete the interaction, otherwise it shows an error taht the interaction failed, is send_autocomplete the right function to use
no but i belive you can delete it
is there any other thing thathas a box and you write in it?
real
dropdown modals doesn't generate discord money
dropdown modals only for nitro members

dont give discord ideas pls
Guys i have a problem with my vps
unfortunate
like i've figured out how to run a bot on it but when i close the browser he stops running
what company is it?
aws
make a support ticket then
Use screen or make some cron job or whatever, use Google
That's clearly pointless
!d discord screen
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.
bruh
It's a command, use Google
use nohup or sum
or screen yeah
use diva hosting
free ?
maybe you can use an autocomplete?
yes
sounds legit
I have read cp as c++
free only for first hour
yes
so you need to create new accounds each hour
perfect
@vale wing i wish I could use bobux to pay an host, tbh most websites and companies should recognize that as a method of payment
you need to be in there discord server for it to be free
Fr
However course of usd to bobux is unknown
Payment method:
- PayPal
- Credit Card
- Bobux
- Gift Card
ill dm you their discord server
Well bobux is more important than usd anyway so it doesn't care
bruh the discord link on the website doesn't even works
this website is just to get your ip
or to get data directly from your application
Imagine when we monetise we randomise it too 
@slate swan i fixed the problem
we need premium features
i have no idea what was it but cool
๐ซก
Sure coming together with site but I haven't thought of them yet
Well, reduced cooldwns and other things
Better lootbox in daily and votes
stocks visualization on website i see that 
Yeah basic features + some premium commands
this chat is now our HQ
its about discord bots indeed 
can't wait the time when we'll need to shard @vale wing
and can't wait the time when we'll need to do clustering
(that time will never come)
Guys I am trying to get my discord bot to run a script for me in discord. anyone know if it is even possible?
Yeah
could you help me to understand this?
!source e
Run Python code and get the results.
That's for general python script running
thank you.
when you even need to
For interacting with bot code during runtime see this, might be not the finest piece but alright
so to make my script work in discord. what do I exactly need to do?
ext/system.py line 179
async def _exec(self, inter: disnake.ApplicationCommandInteraction, code: str):```
I have been watching tutorials for couple of hours, I am not familiar with python
you need to read how @unkempt canyon does it in its source code
Bobux bot promotional strategy be like
Uh oh
yeah
If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:
- basics (variables, loops, math, basic types)
- simple data structures (dicts, lists)
- modules and libraries
- functional programming
- object-oriented programming
- async programming principles
Encouraging learning, just not from discord bot
Well I have a discord bot with few working commands already done
when you see that the Bot takes too much time to respond to commands or when the resources of your host are near 70/80% even though the Bot is under normal load
asynchronous code is powerful but it has his limitations!
Bobux eats 200mb
ive made my first bot when i was popo in coding
hm?
Still not recommended
200 micro bytes
Well not even 300 guilds plus we're using only the intents that we need
mine like 16 bc of ai and 500 commands that i am changing in slash commands
16 GB
So exenifix, this script Im trying to get to work in discord is some kind of encrypting software? that can encrypt and decrypt messages
What encryption method
Caesar Cipher method op
I found it in youtube ๐
yeah
!d string.ascii_lowercase
string.ascii_lowercase```
The lowercase letters `'abcdefghijklmnopqrstuvwxyz'`. This value is not locale-dependent and will not change.
My eyes
your eyes what
letters = 'abcdefghijklmnopqrstuvwxyz'
ah where is that

@cloud dawn sorry for being annoying but update system when
never
YES FINNALY I FUCKING MADE THE DISCORD AUTH WORKINH
so, is there any easy way to get this as command to my discord bot?

