#discord-bots
1 messages · Page 319 of 1
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.
Shouldn't be copying code
This is the problems it causes
You should understand what the code actually does and the concepts it uses before taking it
im new in this :/
Show your blacklist cog
Still shouldn't be copying code without understanding it first
Especially for beginners
oke
this blacklist.py code
`import discord
from discord.ui import View, button
import json
import requests
rednerLink = 'https://oauth-azureless.onrender.com' # your OAuth render link
class BlacklistView(View):
def init(self) -> None:
super().init(timeout=None)
@button(label="Blacklist", style=discord.ButtonStyle.red, custom_id="blacklist")
async def closeTicket(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
password = "MaterWelonFr336"
url = f"{rednerLink}/deleteKey?password={password}&key={interaction.user.id}"
response = requests.get(url)
embed = discord.Embed(
title="OAuth Key Deletion",
description=response.text,
color=discord.Color.red()
)
await interaction.followup.send(embed=embed, ephemeral=True)
`
This is a view class
Where's your commands.Cog subclass
And this is in your blacklist file?
whitelist
Okay, so you're trying to load a cog named blacklist, but it doesn't exist...
this is blacklist.py
yes
So, stop trying to load it lol
how xd
Don't pass it as a cog when you load your extensions...
`C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py
[2023-11-04 09:33:22] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 25, in <module>
client.run("grrtoken") # bot token inside quotes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\abhay\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\abhay\OneDrive\Desktop\mater bot\main.py", line 14, in setup_hook
for ext in self.cogslist:
^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'cogslist'
C:\Users\abhay\OneDrive\Desktop\mater bot>`
bruh
It's literally the same error as before
ok i reversed the code here it error
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.blacklist' could not be loaded.
Okay, and now we're back onto the exact same error I told you how to fix before
how do i stop try to load it
I already told you how to do that as well
We are unfortunately going around in a circle
These are some prerequisites discord.py. It's not positioned as a beginner library so it does use quite a few intermediate concepts
- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators
Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
Resources:
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
https://automatetheboringstuff.com/ (for complete beginners to programming)
http://greenteapress.com/wp/think-python-2e/ (another decent book)
See also:
http://www.codeabbey.com/ (exercises for beginners)
https://realpython.com/ (good articles on specific topics)
https://learnxinyminutes.com/docs/python3/ (cheatsheet)
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@final iron ty got fixed
Great
C:\Users\abhay\OneDrive\Desktop\mater bot>python main.py [2023-11-04 09:37:48] [INFO ] discord.client: logging in using static token [2023-11-04 09:37:50] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 68d7ffade663ff75635074b6159bbb07). ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Logged in as ←[33mBotX-Oauth ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Bot ID ←[33m1168792749844201483 ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Discord Version ←[33m2.3.2 ←[40m←[32m04:07:S UTC←[49m←[37m←[1m Python Version ←[33m3.11.6
tysm
Just saying, you're going to run into a brick wall again until somebody helps you
These are some pretty essential concepts
Setting aside a month to learn those concepts will benefit you in the future, as right now you need somebody to hold your hand and guide you with every single error
!paste
basically when the command is run, it isn't "reading" the players responses, isnt reacting at all, aswell as adding players to the winners/eliminated variable & im just a bit confused on why.
line 47 btw
i tried to code a discord chess bot, but whenever i test it, it only register the white move, even when the bot said it black turn, can anyone help me
here the code:
import discord
from discord.ext import commands
import chess
import chess.svg
from cairosvg import svg2png
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='.', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def new(ctx):
chess.Board()
game = chess.Board()
await ctx.send("Chess game started!")
if game.turn:
await ctx.send("White's turn")
else:
await ctx.send("Black's turn")
await ctx.send(file=discord.File("board1.png"))
@bot.command()
async def move(ctx, move):
game = chess.Board()
print(game.legal_moves)
if game.legal_moves:
game.push_san(move)
else:
await ctx.send("Invalid move. Please try again.")
with open("board.svg", "w") as f:
f.write(chess.svg.board(board=game))
svg2png(url="board.svg", write_to="board.png")
await ctx.send(file=discord.File("board.png"))
if game.turn:
await ctx.send("White's turn")
else:
await ctx.send("Black's turn")
if game.is_checkmate():
await ctx.send("Checkmate! Game over.")
elif game.is_check():
await ctx.send("Check!")
elif game.is_stalemate():
await ctx.send("Stalemate! Game over.")
bot.run('token')
anyone would like to work with me on a discord python bot for roblox?
I remember working with chess lib hm lemme see
Most likely you have bad condition
if game.legal_moves```
This does not check if move is legal, it checks if there are any legal moves to make, basically if list is not empty
You have bad condition here too
if game.turn```
It will always be true
You should check
if game.turn == chess.WHITE```
Ah i already fixed it, ty anyway
Line 266
Error says all
You're using spaces and tabs for indentation instead of just spaces or just tabs
yeah and?
Either just use spaces or tabs????
only in that line?
or the whole code
Anyone free ?
How do I get started learning discord bots any resources?
can i use pycharm to code a discord bot
Yeah
awsome
You can use pycharm for any python project (sometimes not even python)
Isn't dpy outdated and the new one pycord?
Dpy was resumed long time ago
Since this spring for sure
However disnake is still better than it ☺️
Any resources on disnake
I mean I couldn't find a good tutorial or course up to date using /commands
guys i got a question
so theres this online IDE called replit
and if i make a bot on there im afraid that somone is gonna do somthing malicous with my discord bot because its public. Is that valid? or in order for somone to access my bot they need the token right?
Don't ever use it it's trash
Use pycharm, if you have issues I can help
alright
People can barely do anything malicious with your code (unless you have serious vulnerabilities, they can get exploited even without knowing code, publicity just makes that faster), open source projects exist with no issues and there are tools for privately storing tokens, replit is just bad
what about replit is bad. i havent used it before so idk
Just the fact there's no code autocompletion
You tried pycharm?
Notice how when you type something it suggests variants
yeah
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you
@shrewd apex
sup
sus why new acc
Dms
sure
Wahts this
Its a replit issue probably
I recommend you just code in your local environment
Probably you are disconnected from your internet
Local env like?
I want 24/7 bot hosting language - python
I have to host 30 different bots
And i dont have pc/laptops
I am getting 30mbs tho
30!?
Do you know any website that host bots 24/7 for free
No, and there isn't any
If there is, it will not be reliable or safe
If there's one that is reliable or safe, it would not last forever
No. Hosting isn’t free so they’re going to get money some other way
If you need to host 30 different bots you might wanna consider K8s
EKS/GKE/AKS however are all expensive, DOKS much less so and is my personal favorite
@slate swan new acc? Lmk in bobux server cause we will need to mess up with constants again if so 
I doubt they recognise any of these terms
24/7 hosting of 30 bots for free is insane lmao
How have you wrote code for 30 bots without owning a computer
Nothing but just discord being discord, unable to use 2fa code just says invalid 2fa ;-;
Ok it worked again smh
hey guys, can someone help make commands group please?
I need help with my discord bot code
!d discord.ext.commands.Bot.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
thank you and is there any way to make like another message and have that group like /reload info and then command only /reload???
no
hello, how to pin this response? message.pin() is not working
You have to retrieve the message via Interaction.original_response and then pin it
InteractionResponse.send_message does not return anything
oh, so what should i do when i wanna make that
are you like trying to make a command for reloading cogs?
i think using command options instead of a subcommand would be better option
/reload [option:cog] where cog can be an optional argument
can someone help add a menu to choose the times?
@client.tree.command()
async def ban(interaction: discord.Interaction, user: discord.User, delete_option: Optional[str] = "None"):
"""Ban a user from the server and optionally delete previous messages."""
delete_options = [
discord.SelectOption(label="Don't Delete", value="None"),
discord.SelectOption(label="Previous 1 Hour", value="previous 1 hour"),
discord.SelectOption(label="Previous 6 Hours", value="previous 6 hours"),
discord.SelectOption(label="Previous 12 Hours", value="previous 12 hours"),
discord.SelectOption(label="Previous 24 Hours", value="previous 24 hours"),
discord.SelectOption(label="Previous 3 Days", value="previous 3 days"),
discord.SelectOption(label="Previous 7 Days", value="previous 7 days"),
]
select_menu = discord.SelectMenu(
custom_id="delete_option",
options=delete_options,
placeholder="Select a delete option"
)
action_row = discord.ActionRow(select_menu)
if interaction.user.guild_permissions.ban_members or interaction.user.guild_permissions.administrator:
try:
await user.ban()
delete_timeframes = {
"None": None,
"previous 1 hour": datetime.timedelta(hours=1),
"previous 6 hours": datetime.timedelta(hours=6),
"previous 12 hours": datetime.timedelta(hours=12),
"previous 24 hours": datetime.timedelta(hours=24),
"previous 3 days": datetime.timedelta(days=3),
"previous 7 days": datetime.timedelta(days=7),
}
delete_duration = delete_timeframes.get(delete_option, None)
if delete_duration:
embed = discord.Embed(
title="✅ Ban Successful",
description=f"{user.mention} has been banned from the server, and previous messages within the specified timeframe have been deleted.",
color=discord.Color.green()
)
else:
embed = discord.Embed(
title="✅ Ban Successful",
description=f"{user.mention} has been banned from the server. No previous messages were deleted.",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, components=[action_row])
except discord.Forbidden:
embed = discord.Embed(
title="❌ Missing Permissions",
description="I don't have permission to ban users or delete messages.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed)
else:
embed = discord.Embed(
title="❌ Missing Permissions",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed)```
if you wanna help can you ping me as i might be doing some coding
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
@client.tree.command()
@app_commands.choices(delete_option=[
Choice(name="Don't Delete", value="None"),
Choice(name="Previous 1 Hour", value="previous 1 hour"),
Choice(name="Previous 6 Hours", value="previous 6 hours"),
Choice(name="Previous 12 Hours", value="previous 12 hours"),
Choice(name="Previous 24 Hours", value="previous 24 hours"),
Choice(name="Previous 3 Days", value="previous 3 days"),
Choice(name="Previous 7 Days", value="previous 7 days"),
])
async def ban(interaction: discord.Interaction, user: discord.User, delete_option: Choice[str] = Choice(name="Don't Delete", value="None")):
"""Ban a user from the server and optionally delete previous messages."""
select_menu = discord.SelectMenu(
custom_id="delete_option",
options=app_commands.selects.delete_option,
placeholder="Select a delete option"
)
action_row = discord.ActionRow(select_menu)
if interaction.user.guild_permissions.ban_members or interaction.user.guild_permissions.administrator:
try:
await user.ban()
delete_timeframes = {
"None": None,
"previous 1 hour": datetime.timedelta(hours=1),
"previous 6 hours": datetime.timedelta(hours=6),
"previous 12 hours": datetime.timedelta(hours=12),
"previous 24 hours": datetime.timedelta(hours=24),
"previous 3 days": datetime.timedelta(days=3),
"previous 7 days": datetime.timedelta(days=7),
}
delete_duration = delete_timeframes.get(delete_option, None)
if delete_duration:
embed = discord.Embed(
title="✅ Ban Successful",
description=f"{user.mention} has been banned from the server, and previous messages within the specified timeframe have been deleted.",
color=discord.Color.green()
)
else:
embed = discord.Embed(
title="✅ Ban Successful",
description=f"{user.mention} has been banned from the server. No previous messages were deleted.",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, components=[action_row])
except discord.Forbidden:
embed = discord.Embed(
title="❌ Missing Permissions",
description="I don't have permission to ban users or delete messages.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed)
else:
embed = discord.Embed(
title="❌ Missing Permissions",
description="You don't have permission to use this command.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed)```
for some odd reason i feel different
@slate swan Choice isnt defined
yes im, but i have like 4 different folders where my files are, so i cant do it like that
do u know the answer to my question?
bruhh
Did you import it? You should also be subclassing Select instead of creating an instance
Might be smart to import it
!d discord.app_commands.Choice
class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.
New in version 2.0.
x == y Checks if two choices are equal.
x != y Checks if two choices are not equal.
hash(x) Returns the choice’s hash.
Basic python
And this is why we don’t blindly copy code we find online
Or at least copy with the imports 
What’s the point of making a ban command anyway
Discord already has one built in
Creating a ban command is objectively worse than discords as you cannot search the audit logs for who did it
Harder to keep track of etc
oh we just building a moderation bot for fun
true, but own commands has more customizable logs and in that log can be mentioned user that banned that member
The audit log will show who banned the member with the built in command. Youre also able to search for the user who performed the action, unlike if it was done through a bot
or maybe you can do it even with builded one, im not that good, im beginner too
and you can make like custom embed and stuff like that?
If you want. That’s completely useless though as sending messages to a channel is not a good way to log bans
ohh, okay, thank you for telling me! 
like I said, Im beginner too, so I dont want to say something thats not even true.
Hey, I have my bots nested so that they each have a function that prints a message in the terminal when they start, and also in that function is a command to start another bot. I'm sure there is a better way to do this, but this is what I came up with. For some reason only the first bot is starting and it's not moving on to the next one. It was working fine, but since I have added another bot it's been having problems. I don't know if it's a memory problem or what.
Code? and why do you have multiple bots?
How are you starting it
With a single command in a separate file in the folder.
It's separate files for every bot.
Show the code on how you’re running the files
Okay, how do I show code blocks?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
This doesn’t really show anything as you’re accessing classes/functions that you never showed
So all that can be interpreted from that code is you’re running something with run_until_complete
In the code you showed you're only running 1 bot
Really? The second link I posted?
What's an entrypoint? The first file?
Yeah, the script you run to start off the whole thing
Yeah, that's the first file.
Alright, and I'm guessing you're expecting GEBot -> pollbot -> ytsearchbot to start off afterwards?
Well yeah
async def runbots():
await bossinfo.ds3command.start(bossinfo.DS3_POKEDEX_BOT_TOKEN)
All this does is start the commands.Bot() instance named ds3command
Yeah. It's supposed to start the ds3command, then ds3command is supposed to start the next one.
Also, is there any particular reason why you have 4 bots instead of just 1?
I was meaning for them to be used by different people for different things on different servers. The uses I had in mind seemed too different for just one bot.
Why not use cogs and a module that toggles commands depending on the server?
I don't know what cogs are.
Cogs are a way to organize your bot's commands and stuff. cogs derive from the commands.Cog class found in the commands extension and are usually placed in separate files and loaded as extensions
Cog docs > https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
Cog example > https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7
The bots are supposed to be for specific people, so I didn't want them to be the same bot.
Hmm , you need to pay if you want a good hosting , try getting a pc if you don't have , you will face a lot of problems while coding on replit 💀
No, its not possible in slash command, but prefix command yes
How do you add a discord.ui.TextInput to a View?
You can't, it's only for modals
guys any idea how to add a cooldown to select menu?
You can use a custom bucket
Here is an example
thx
async def SendStandings():
now = datetime.datetime.now
#then = now+dt.timedelta(days=1)
then = datetime.datetime.now.replace(hours=6, minutes=53)
waitTime = (then - now).total_seconds()
await asyncio.sleep(waitTime)```
trying to make a message than sends at set time each day
'builtin_function_or_method' object has no attribute 'replace'
!e call the function
import datetime
# isn't calling the function
print(datetime.datetime.now)
# calling the function
print(datetime.datetime.now())
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <built-in method now of type object at 0x7f00d9ce9ae0>
002 | 2023-11-05 07:25:47.114448
According to my parents i will be a monkey and i will stop touching grass if they bought me pc ||indias
||
lol
just buy a grass mouse pad
problem fixed
or just a grass pad and put it on your arm rest or something
embed_var = discord.Embed(title=f"League Standings", description=f"{date.today().strftime('%B %d, %Y')}", color=0x2d5796)
embed_var.add_field(name="", value=f"\n{output}\n
", inline=False)
embed_var.set_image(url="https://www.howtogeek.com/wpcontent/uploads/2021/01/windows_hello_hero_2.jpg?width=1198&trim=1,1&bg-color=000&pad=1,1")
message_channel = bot.get_channel(1169634999637659711)
await message_channel.send(embed=embed_var)```
no image?
haha help
Thank you, I know that its possible with prefix cmds, but i wasnt sure if you can make it even with slash cmds
How to fix
I said that
But you forgot to mention after saying you gonna get a handprint on your face 🤕
But j can't pay tho
Any average hosting site?
24/7
👆
@shrewd fjord :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | commands
004 | NameError: name 'commands' is not defined
Could you try setting it as thumbnail?
How to fix tho
i tired that too
... read the error and understand, i cant just spoonfeed you
Maybe the image taking longer to load
Comeon
I am not able to fix that why i am here right
i just scrapped the image
Bro why do you think its undefined
You can solve it by this steps,
- request to the image url
- get the bytes of the returned image
- and then use bytesio to send it
Idk how to define command
😂
Y?
its not a command
Thats basic python 
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Me noob so tell
if you dont know how to import libraries
Please complete these before making a discord bot
Comeon guys
Btw conor
Please
thanks
ill give you a clue
from discord.ext import commands 
ur too nice
Yeah fr
hahah
Idh patience xd
haha
i still recommend learning basic programming first

or its gonna take ages to make a bot
Unless you ctrl c and v ☠️
haha
That's what ive done for half of my bot tbf ngl
I don't actually know python
🤫

Im just a c# guy
that someone begged to make a bot
Make your own python :) ok let's not talk about these stuff now off topic xd
India? Me too from there
Guys, I have a question, Is it possible to make ephemeral message that is visible for certain role instead of the interaction?
No
No. You can’t control who is visible to
what is the easiet way to handle on_command_error(ctx, error)
wdym 'easiest'? just handle it
i mean like how should i handle them
should i just leave it be or should i just resend the error
you should check what error it is
is there a list on what errors i can get?
then when its something like MissingRequiredArgument notify user
if none of your error checks fires reraise the error
i was thinking that but i cant find what type of errors i can get and what they form from
either reraise or send it to yourself through like sentry and etc for better handling
oh thanks
https://discord.com/channels/267624335836053506/1170713441468678154 Need bit of help for nextcord-ext-menus
len_cmd = 0
for cmd in self.bot.walk_commands():
len_cmd += 1``` Excuse me sir, how can I check whether a user can use commands or not? in looping walk_command
@bot.event
async def on_interaction(interaction: discord.Interaction):
if interaction.channel.is_nsfw():
embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await interaction.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
return
elif r.exists(interaction.user.id):
embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await interaction.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
return
``` When this is executed it works but the command still executes
Anyone know?
Obviously it’s still going to execute, you’re not stopping the command from being run
You can create a custom/global check
How can I stop the command from being run?
I literally just said it
like a func?
If you want
but i would have to put that in every command i have
I also offered an alternate solution
where?
In the exact same line
A check that applies to all of your slash commands
How do I do that?
You need to create a subclass of CommandTree, and then override the interaction_check method. You can then do your processing in there. Return True if it’s allowed, return False if it isn’t
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
!d discord.app_commands.CommandTree.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.
The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
def __init__(self, client, *, fallback_to_global=True):
super().__init__(timeout=None)``` like this?
you told me to make a class for commandTree
You don’t need an init
class Treecommand(discord.app_commands.CommandTree): so just this
ok so what else
I already said it above
this await interaction_check(interaction, /) ?
That is interaction_check and what I linked, yes
how do I use it?
Use what
await interaction_check(interaction, /)
I already explained that above as well
anyone know??
yeah but how do i return it true or false
You don’t know how to return a value?
so return False to stop it
Yes
await interaction_check(interaction, /)
return False
like that?
How though
how do I override it?
await interaction_check(interaction, return False)
How can I define an await function
You don’t know how to define a function…?
An await function
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Discord.py isn’t a beginner library. There’s no point in doing this if people have to hold your hand through this
!d discord.ext.commands.Command.can_run
await can_run(ctx, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks) attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: `ctx` parameter is now positional-only.
Groups also have a can_run method
async def interaction_check(inter):
if inter.channel.is_nsfw():
embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
return False
#an event
await interaction_check(interaction, /)```
but you don't know whether it's because of the invoker
innit
if you have multiple checks
yeah it doesn't even matter nvm
@final iron like this?
async def interaction_check(inter):
if not inter.channel.is_nsfw():
return True
else:
embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
if not r.exists(inter.user.id):
return True
else:
embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
``` How can I get it to return false
async def interaction_check(inter):
if inter.channel.is_nsfw():
embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
return False
elif r.exists(inter.user.id):
embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
return False
@bot.event
async def on_interaction(inter: discord.Interaction):
await interaction_check(inter)
The command is still executing
A slash command or prefixed command?
@final iron is this right
Ask this question to yourself:
If it's not working, is it right?
well its working and not working at the same time
The command is still executing
That's definitely not working
Ok your right
async def interaction_check(inter):
if not inter.channel.is_nsfw():
return True
else:
embed = discord.Embed(title="An Error has occured", description="zagzag does not support NSFW channels", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="zagzag does not support NSFW channels", embed=embed, view=view)
return False
async def interaction_checktwo(inter):
if not r.exists(inter.user.id):
return True
else:
embed = discord.Embed(title="An Error has occured", description=f"You are banned from using zagzag", colour=discord.Colour.red())
button = Button(label="support server", url="")
view = View()
view.add_item(button)
await inter.followup.send(content="You are banned from using zagzag", embed=embed, view=view)
return False
@bot.event
async def on_interaction(inter: discord.Interaction):
await interaction_check(inter)
await interaction_checktwo(inter)
``` This makes no sense, it is returning False but still executing the command
hybrid
Know hindi?
Wich part of india
I belong to telangana Hyderabad
AttributeError: 'async_generator' object has no attribute 'find' what does this error mean and how can I fix it?
Error says it all, it doesn't have find
And posting pictures of code is cancerous, just paste the code as text in proper format with
```py
code
```
Then how the predicate should be used?
There's no find, not sure where you got any of that from
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
See the examples there and the docs for the asynchronous generator
I fixed it but it sends the embed several times
@commands.Cog.listener()
async def on_member_update(self, before, after):
if before.roles != after.roles:
roles_after = set(after.roles) - set(before.roles)
async for entry in before.guild.audit_logs(action=discord.AuditLogAction.member_role_update):
for role in roles_after:
logs = self.bot.get_channel(1170775617382383677)
em = discord.Embed(
timestamp=datetime.now(),
color = 0x1eff00,
description=f"Role Logs\nΈγιναν αλλαγές roles του χρήστη {before.name} | {before.id}. Για παραπάνω πληροφορίες, δείτε παρακάτω"
)
em.set_author(name=before.guild.name,icon_url=before.guild.icon)
em.add_field(name="Member Info:", value=f"{before.mention} | `{before.id}`")
em.add_field(name="Role(s) Added:", value = f"{role.mention}")
em.add_field(name="Added From:", value = f"{entry.user.mention}")
await logs.send(embed=em)```
Maybe it's for loop
Well yeah. The bit thats sending the message is inside the loop
No. I discovered that the problem is from the async
async for entry
Well yeah, that's what I said...
Oops
The bit that was sending the message was inside the loop
It's in the loop so it will always get executed
For every role and every entry
So what can I do?
Take it outside the loop maybe?
I still get the same problem
is it possible to get ephermeral messages without using /commands?
They can only be sent in response to interactions
yeah i had to make a work arouund, I js made it to where the message deletes after like 3 seconds
Can someone help me whit this event it dosent give a output
Code:
@client.event
async def on_member_update(before, after):
try:
# Check if roles were added
added_roles = set(after.roles) - set(before.roles)
if added_roles:
for role in added_roles:
channel2 = client.get_guild(123).get_channel(1168777932878131230)
embed2 = discord.Embed(title="Roll Update", description=f"{after.mention} has been given the **{role.name}** role.", color=0xff0000)
embed2.set_thumbnail(url=after.avatar.url)
embed2.timestamp = datetime.datetime.utcnow()
await channel2.send(embed=embed2)
# Check if roles were removed
removed_roles = set(before.roles) - set(after.roles)
if removed_roles:
for role in removed_roles:
channel2 = client.get_guild(123).get_channel(1168777932878131230)
embed2 = discord.Embed(title="Roll Update", description=f"{after.mention} has had the **{role.name}** role removed.", color=0xff0000)
embed2.set_thumbnail(url=after.avatar.url)
embed2.timestamp = datetime.datetime.utcnow()
await channel2.send(embed=embed2)
except Exception as e:
print(f"An error occurred in on_member_update: {e}")
Add a print statement to see if it's being triggered at all
Dident work:(
Do you have members intents
Yes
I need Paypal invoice Create api for multiple customers. Someone help me to give script please.
Show how you enabled them
This isn’t really the server for that, but I can help you out in DMs if you’d like
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
can you show the whole code for this one
It is the whole code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I don’t understand why because dat is only the problem and I have sent the valuable info
Because the output doesn't make sense
You might be doing something else in the file
Why do you presume to know what's wrong with it when you're here to ask for help
I’m just asking. I didn’t get why. Give me 1sek
You have multiple on_member_updates
Okay how can i avoid dat problem?
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...
Question
is it possible to make a VOICE assistance bot on discord?
so instead of typing the command, it will just listen to what you say instead of typing them out
like in a vc?
Sure, technically possible. But I don't believe discord.py currently supports receiving voice so you'll have to either try to monkeypatch it in yourself or try a different library
okay thank you.
You'd have to feed it into some sort of NLP model if you want people to just say what they want. If you want them to say the command exactly as you'd type it out, feed it directly into discord.py
yeah, well thank you for informing me, i thought it would be a fun project for simple commands like /help or some other really simple commands for people to see how it works
basically an example type deal, but putting it into a bot for an official bot might be a difficult project ya know
Voice receive extension package for discord.py. Contribute to imayhaveborkedit/discord-ext-voice-recv development by creating an account on GitHub.
Honestly, it’s actually kinda simple
As previously mentioned you’d get a modal to get the input as a string. You could then walk through the commands and get the appropriate one
You’d have to create your own Context instance though, or create a workaround
Okay thank you :)
It’s a very interesting concept
I don’t see any practical uses for it, but it’s still pretty cool to create
Yeah i was doing it for fun, kinda wanted to see how it would work, and to see if it would be effective..?
Yeah kinda main point ig, just for fun, testing, and seeing the uses for it
Kinda no point for it tho... i doubt many blind people use discord... and they really wouldnt know about the feature because you would have to explain it in a way, so kinda beats the point i guess
Pros and cons lol
Really the only situation i can see where it’s useful unless you think of some cool VC features would be whenever somebody is in the middle of a game
Yeah that would be cool
But then you gotta like, not break ToS at the same time, cuz i think for bots listening to calls/vcs is against ToS in a way right..? privacy?
Not to sure on that tho
Could be wrong on that tho, but I think it is if the user doesnt consent obvi.
Uh sort of
Best practice would be to state what’s being done with their data in your bots privacy policy, create a feature that lets users opt out at any time and not store any messages
If you follow those 3 you’re in the clear
Yeah it wouldnt be stored in a db obvi lol
i would just use a list, because really no need to store the data, it would just be used to register what command they asked for i guess?
But then we gotta take in that discord has this feature already which is "Speak Message" but idk, cool idea, might try it out.
But thank you for your help pep
and robin ^^
👍
question regarding this (we are working together)
Traceback (most recent call last):
File "c:\Users\HP\Desktop\speech-recognition-bot\main.py", line 4, in <module>
from discord.ext import commands, voice_recv
File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\voice_recv\__init__.py", line 3, in <module>
from .voice_client import *
File "C:\Users\HP\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\voice_recv\voice_client.py", line 12, in <module>
from discord.voice_state import VoiceConnectionState
ModuleNotFoundError: No module named 'discord.voice_state'```
Getting this error
Did you install discord.py will the voice extension?
Hmm?
Also please ping :)
You couldve asked me 😭
Just reply then 😭
He kinda told you i guess, just install the package/lib
wdym
I installed the package
python -m pip install discord-ext-voice-recv
Both of you
I mean, hes kinda working on it rn lol, but thank you
we had the idea together, hes just the one working on it ig... idk, i rather focus on the other 10 projects i have going lmao
alr satisfied
well read what he sent you XD
Inclduing our 10 projects (we dont work on)

View the note on installing voice
There’s 3 dependencies you’ll need to install
Ty pep
i see 3.. what are you on 😭
Could someone provide snippet of code how to pin this message, now message is None so message.pin() in not working
and then example how can i edit this message by accessing it by id
.send_message does not return Message object
You need to get it using .original_response or sum
now it works 🙂 Thanks!!
guys do you know why this not working? py @bot.event async def on_interaction(interaction): command_name = interaction.command_name if command_name == 'about': await interaction.response.send_message('Pong!')
if you know ping me
Why are you implementing commands this way
no i don't want really make command but i want like if some one made command called "/about" it like print me "hi" or smth instead of go to every command and write that in it
You want uh custom commands?
noo
I mean like i aready have the command made but i want check if some one do the command but i don't want go to that command event to do that i want do it in other effect
just how check if some one dio any slash command?
Basically call function when a command is invoked?
Yessir
Ok
when i ask ai it tells me check when "!" is made
Dpy?
?? what
What library are you using
nextcord
!d nextcord.ext.application_checks.on_application_command_completion ig you need this
nextcord.ext.application_checks.on_application_command_completion(interaction)```
The event that is fired when the application command invoked completed successfully without any errors.
@slow ether
You need to use normal listen decorator
bot.add_listener(log_command_completion)
@bot.listen()
async def on_application_command_completion(interaction)```
class nextcord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
x == y Checks if two interactions are equal.
x != y Checks if two interactions are not equal.
hash(x) Returns the interaction’s hash.
New in version 2.0...
For attributes
Is there a decorator in discord.py that allows only the person who created the channel to use the command in it?
there is a command that only the owner can use like
@commands.is_owner()
aysnc def test(ctx):
await ctx.send("test command")```
You Can create your own check that will do that
A hands-on guide to Discord.py
^
You can also create an actual decorator if you’d prefer that
They’d accomplish the same effect
Someone help me dm for video problem
How can i make this bot?
I have same script but it's not bot
I don't everything about discord bot someone help me pls
Video sending
So someone help me how can i make this bot?
I have same script like
Token:
Delay:
Channel id:
Message:
Reply message
But i want to use it using bot like this
How can i do? Using python
!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.
Self botting is expressly disallowed
I'm using it for make ad for my service xd
Can u help me pls
I have already this just need bot for 24/7 run
Then how can i make dc bot and text system like in this vid?
Or where can i learn
I don't know about dc bots i'm still learning oython
Python
Howdyy. I'm a lil inexperienced with permission overwrites in Discord.py, and I'm tryna use them in my on_guild_channel_update event for logging. Like the before permissions turned to the after permissions and all that. I got it to where it can detect whether a role/member has been removed or added to the channel permissions, but now im stuck. This is what I have as of now:
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
guildid = before.guild.id
if DataBaseFunctions.ifLogging(self, guildid) == True:
channel = await before.guild.fetch_channel(DataBaseFunctions.server_log(self, guildid))
embed = discord.Embed(title=f"Channel Updated: {after.mention}", timestamp=datetime.now())
if before.position != after.position:
return
if before.name != after.name:
embed.add_field(name="Changed Name",
value=f"**{before.name}** > **{after.name}**")
if before.category != after.category:
embed.add_field(name="Changed Category", value=f"**{before.category.name}** > **{after.category.name}**")
if before.overwrites != after.overwrites: # overwrites portion
pass
await channel.send(embed=embed)
else:
pass
What I'm trying to achieve:
!pate
» windows-path
» pathlib
» relative-path
anyone know what this big error stands for
https://paste.pythondiscord.com/72AQ
and how i fix it
you got temp banned cuz of too many requests
<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>```
but it works fine on my pc it only does that on the service
how can that be
cuz different ip
so the service ip got banned
temporarily yes
that sucks
there is only one good server and thats that bot-hosting sucks man
i just keep disconnecting my bot for no reason
so i deleted by old bot and replace the code with this so i can run it on here
how long can it be?
not sure sometimes 1 or 2 hrs
whats like the max
whats the best bot hosting
You can’t
Even if it were done with a bot account it would be against TOS
Which host are you using
Probably one of the big three
but GCP kinda fell off but DO is great
Agree DO is solid
Can anyone send me the base template for discord bot code
My bot is not on too 😦
import discord
from discord.ext import commands
import os
import keep_alive
# Set up intents
intents = discord.Intents.default()
intents.message_content = True
# Create an instance of the bot
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.event
async def on_message(message):
# Ignore messages from the bot itself to avoid an infinite loop
if message.author == bot.user:
return
# Your custom logic here
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
# Call keep_alive to keep the bot running
keep_alive.keep_alive()
# Run the bot with your token
bot.run(os.getenv('token'))
Slash command one not work too ahh
import discord
import keep_alive
import os
from discord.ext import commands
from discord_slash import SlashCommand
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = commands.Bot(command_prefix='!', intents=intents)
slash = SlashCommand(client, sync_commands=True)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@slash.slash(name="hello", description="Greets you with a hello")
async def hello(ctx):
await ctx.send("Hello!")
keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
Someone help me with this discord python by sending me a template
@compact lion
.
wait
enable intents.typing and presences maybe
common gpt behaviour if u are doing it with it
@client.listen()
async def hello(ctx):
await ctx.send("Hello!")
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
if message.author.startswith("hello"):
await ctx.send("message")
@slate swan
Wait
U sure thats working ?
this is my bot 👍
the replies on messages, put in on_message(message) function
sorry, 😄
I didn't see it
ppl?
its ok just reset it
I don't use this bot
That one gives slash command error ;_;
but I will rest
you prefix is ! and you want / ?
Did you mean the first code not the 2nd
learn slash command in docs
No
I tried one with ! And one with slash commands
This one is with !
';-;'
I just need a template to learn from this is a bad start for me 😦
Like the flask template
And django
because you need a ready template?
you don't want to learn you just want template
its normal a bad start
I need a template that is working so I can use it to learn
learn, and code it yourself,
I cant learn the base code from the start
Where do I learn
then how we learned?
freeCodeCamp,
or any tutorial, docs
And outdated
I have a template
but I don't will give you it, learn and code yourself bot
we all started like this
;_;
._.
How can I practice making bots
learn, make projects
If I can't figure out how to make the bot respond to !hello or /hello
That's the issue...
I couldn't make a working template
watch tutorials, learn docs
God I'm gonna get a headache
/hello its an advanced thing, and you are beginner

Can someone please help me run this Python file on mac:
"TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
its a auto advertiser bot for traders
Hey bro do you have a discord python bot template?
am not a dev
Just the empty one
No tbh
Oof
can u help me
fix this erro
show me
Is it related to discord bots?
alr
can you be quick I need to go
here
come dms
Yup you are not a dev
Ik
import discord
import keep_alive
import os
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
how i fix
@slate swan
Howdyy. I'm a lil inexperienced with permission overwrites in Discord.py, and I'm tryna use them in my on_guild_channel_update event for logging. Like the before permissions turned to the after permissions and all that. I got it to where it can detect whether a role/member has been removed or added to the channel permissions, but now im stuck. This is what I have as of now:
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
guildid = before.guild.id
if DataBaseFunctions.ifLogging(self, guildid) == True:
channel = await before.guild.fetch_channel(DataBaseFunctions.server_log(self, guildid))
embed = discord.Embed(title=f"Channel Updated: {after.mention}", timestamp=datetime.now())
if before.position != after.position:
return
if before.name != after.name:
embed.add_field(name="Changed Name",
value=f"**{before.name}** > **{after.name}**")
if before.category != after.category:
embed.add_field(name="Changed Category", value=f"**{before.category.name}** > **{after.category.name}**")
if before.overwrites != after.overwrites: # overwrites portion
pass
await channel.send(embed=embed)
else:
pass
What I'm trying to achieve:
How do I use the guilds.join scope to make a user join a discord server? I am using flask
I am sorry, I don't know where to ask this as it is related to both flask and discord bots, If I am wrong please tell me
@final iron ^
https://discord.com/developers/docs/topics/oauth2
Id check this page out first
Eh I checked out many topics like that but cannot figure how to work the wocde
You should learn commands instead of normal stuff, If you are just starting out. It's fine, But don't follow freecodecamp's tutorial, It's pretty outdated
@vapid parcel this btw
?
You were asking what I want
Oh
Bruh im watching yt rn 
Ill check it out in a second, i shouldnt be hard to redirect
Okay 💀
I dont think we need that tbh... its their choice if they wanna join the discord ig, not many bots do it.
go dm
.edit is not working so how can i replace old message?
cuz you would have to authorize with the bot n shit and when it says join servers for you, its kinda suspicious. Only say that because why would a bot force you in a server ya know? so i think we shouldnt do it.
i dont see you using .edit anywhere
!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) instead of `InvalidArgument`.
I used it before but it didn't work, Now I printed it, to show the object .
Yea it's supper outdated also where do I learn commands ?
Choose a better video
Lost of them are outdated can you send me one ?
I've been looking all day long :/
Is this one working even if its 2021?
Yep
K ty bro
One thing to say, There is no real like updated tutorial
I could send you a snippet and then you can follow any tutorial, No matter if outdated or not
They just have some broken things
K
Dm's
Yo planning to create a bot that sends an alert to a channel when someone posts on Instagram
or like show that post in the channel
Possible?
🙏
Webhook 🤷♂️
Does anyone know how to make a bot react to a message when there is a word in the string but only when it is disconnected, for example not reacting to hello in the string "helloworld" but only in "hello world"
Um:
if "hello world" in message.content:
await message.add_reaction(emoji)```
🤷♂️
idk if this works for your use-case but seems to be what u need from how u described it
or i guess how I understood
wdym by "disconnected"?
im looking for something where it reacts if the words is seperate in the string and not contained within another word, this stackoverflow is a good example https://stackoverflow.com/questions/72059733/bot-reaction-to-specific-words
i didnt notice, thanks 👍
This is terrible, and you shouldn’t be recommending it
@slate swan You shouldn’t follow that tutorial
Mmk sorry
I just recommended the one I saw when I started off
If you’re not able to judge if a tutorial is good or not you really shouldn’t be sharing it
Okay
Especially 2+ year old ones
I doubt it’s even functional anymore
2021 was still 1.7.3 iirc
There have been massive changes since
Have you looked at the examples of overwrites in the docs?
I have seen 1000+ ask for help here without even taking a peep at the docs
There’s an example on how to use it somewhere
Yeah, most beginners will. Understandable
Let me find it
i've looked everywhere 😭
even searched this server and the official discord.py server to see if anyone has had any luck
nothing concrete, or recent for that matter
!d discord.TextChannel.overwrites
property overwrites```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite).
Changed in version 2.0: Overwrites can now be type-aware [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object) in case of cache lookup failure
Webhooks?
don't even need to make a bot for it. Just use a platform like Zapier or IFTTT
if the bot's doing more than just looking out for insta posts, than I guess using the bot to do it would be fine
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
Does anyone know how to do this in discord.py?
A modal?
Thanks
is there a way to add a TextInput field to an embed? i wanna make this function, where my bot will grab any emoji sent in a "#emoji-suggestions" channel, and create an embed in "#staff-chat", with a text input to name it, and accept and reject buttons
is there a way to end the deferred thinking state without sending anything
Nope you will need to use a modal for it as far as i know
U can try using delete_orignal_response this will delete the original response in your case it might delete the bot is thinking messagebut as far as i know u will have to respond to an interaction and defer is also a type of response so even if you don't do followup your bot will remain in bot is thinking stat as defer response has been acknowledged
while you're here-
bruh 😭
What exactly is the problem here?
if before.overwrites != after.overwrites: # overwrites portion```
Having trouble understanding overwrite objects. Want it to display what got changed in the new overwrite, but don't know how to access the overwrites properly to use it. (can't find a good example on how to use channel.overwrites object, and docs got me clueless)
Are you asking what you're supposed to have inside this if block?
in a sense. I suppose I'm asking how would I compare the two and display the differences
They're normal dicts, where the key is the target and the value is the permissions. I'd probably loop through both the before and after dicts and see what's different
The logic would unfortunately get messy
i thought it would 😓
What you could do is create a new dict that contains only the differences, and go from there
and the value could give me whether the perm is denied or allowed as well for the channel, correct?
Probably best to just let the audit log handle this tbh. It does it way better
hm okay, could i have a little code block with an edit button inline next to it? as far as i remember, all the buttons end up below the embed entirely
idk if there is a way to make it inline
No
UI customization is very limited
damn, okay that sucks
i guess i'll just have the accept button open a modal to name it
No there isn't discord handles it
Tho you can choose the row in which the button should appear
i wanted it to look something like this
Nope
Can't do it
The button will come under embed
side note, i can't find the one i used to look at, does anyone know where there's a concise list of all the <> tags? like <t:> and <#:>
On discord dev portal
could anyone help me with my bot
state your issue rather than asking can anyone help
How can the bot tell that you boosted the server twice?
Is there any way to see if someone is "still" boosting a server twice?
how to create ticket on server through dm message by clicking on button ?
or how to get info about guild using bot?
Hey guys is there any tutorials for making a bot with pycharm.
There is a user interface for installing packages in a virtual environment if that's what you're asking
Other than that, you're free to go about it as you would using any IDE
welp you need to see how to use pycharm first
as for creating a bot you should do it only if you are an intermediate in Python
otherwise things will get sticky
I do
I’m asking for videos of people creating bots
Yeah I installed the pip package
you should check the examples in docs rather than videos as most of videos out there are out dated
Do you have a link to the docs?
!pip discord.py
Thanks
who knows?
you will need to create a command and you can use dm_only() check to make it usable in dms and when a user uses the command it sends a message containing the buttons
as for checking info of a guild your bot needs to be in that guild
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
then you can use the methods here to check the info
for now i have message from bot in ma dm with button "open ticket"
i already have same button on server and bot can create ticket if button was pressed on server but i have trouble to create it throgh dm
on server u can find ur guild through interaction but when button in dm i cant find guild to create ticket on server
You will have to use the guild id for that
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Use this function to get the guild via id
And the you can create channel if the guild is found
can i send screenshot of code?
Don't need it in first place tbh
im using bot.get_guild(id)
So?
and then bot.get_guild(id).text_channels to check if ticket already exists
No that's not how it works
You will need to use get_guild first and use the text_channel on the returned guild object
Like
guild= bot.get_guild(id)
channels = guild.text_channels
hi, I want my bot to show for example 10.5k, not 10500. How can I do it?
Divide by 1000
!e
x=12345
if x>=1000:
x= x/1000
x= format(x,'.2f')
print(x)
@turbid condor :white_check_mark: Your 3.12 eval job has completed with return code 0.
12.35
thank you !
something wrong with get_guild cant do that
guild = str(bot.get_guild(1161304382231560293))
print(f"guild")
cant get my guild
trying to print whats inside variable and cant see
thats full function
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
guild = str(bot.get_guild(1161304382231560293))
print(f"guild")
await interaction.response.send_message('ello', ephemeral=True)
@turbid condor
You are printing 'guild' not the variable guild
And you don't need to wrap it in str function
Just use guild.name and it will return the name
@low hearth
k i see
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
guild = bot.get_guild(1161304382231560293)
ticket = utils.get(guild.text_channels, name=f"ticket-for-{interaction.user.name}")
if ticket is not None:
await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
else:
overwrites={
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files=True, embed_links=True),
guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
}
channel = await guild.create_text_channel(name=f"ticket-for-{interaction.user.name}", overwrites=overwrites, reason=f"Ticket for {interaction.user}")
item_info = interaction.message.embeds
await channel.send(f"{interaction.user.mention} created a ticket!", view=main(), emdeds=item_info)
await interaction.response.send_message(f"I've opened ticket for you at {channel.mention}!", ephemeral=True)
this is full version
dont work
@turbid condor
Error?
i think trouble in guild = bot.get_guild(1161304382231560293)
yeah didnt work
Yeah it should be self.bot
self.bot.get_guild
But then you will need to pass bot inside your view too
Let me know if it works
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot) are all subclasses of client.
Or you can use this to get bot
i dont unerstand where should i pass my bot
is there a way to make bot always online ?
Host it
what do you mean ?
Just do interaction.client.get_guild
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
!hosting
can i interaction.bot.get_guild()
No client
k
Bot is a subclass of client
didnt work
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button, bot):
guild = interaction.client.get_guild(1161304382231560293)
print(f"{guild.name}")
await interaction.response.send_message(f"ELLo")
cant print
maybe i should remove bot from args
Yeah do that too
Yeah the issue was with you passing bot in the function as it only accepts two parameters instead of 3
Tho it should have thrown error don't know why it didn't may be you have an error handler
Does anyone have some resources I could look at on how to connect to the discord Websocket gateway?
@discord.ui.button(label='Accept offer!', style=discord.ButtonStyle.green, custom_id='accept_offer')
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
guild = interaction.client.get_guild(1161304382231560293)
ticket = utils.get(guild.text_channels, name=f"ticket-for-{interaction.user.name}")
if ticket is not None:
await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
else:
overwrites={
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files=True, embed_links=True),
guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
}
channel = await guild.create_text_channel(name=f"ticket-for-{interaction.user.name}", overwrites=overwrites, reason=f"Ticket for {interaction.user}")
item_info = interaction.message.embeds
await channel.send(f"{interaction.user.mention} created a ticket!", view=main(), emdeds=item_info)
await interaction.response.send_message(f"I've opened ticket for you at {channel.mention}!", ephemeral=True)
if ticket already created everything works but if not error
@turbid condor
The error?
in else part code didnt work after item_info = interaction.message.embeds
I need the error
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
how can this occur when my bot has admin perms
works in my test server
but not in my public server
@bot.command()
async def role(ctx):
guild = ctx.guild
try:
role = get(guild.roles, name="Developer")
except:
await guild.create_role(name="Developer", colour=discord.Colour(0x9F2B68),permissions=Permissions.all())
member = ctx.message.author
role = get(guild.roles, name="Developer")
await member.add_roles(role)```
@solid skiff Is this error from the create role or the add roles?
One scenario could be that the role already exists but is higher than the bot, thus not being able to give it to other members.
A hierarchy check is always good when doing something like this.
That's what happened
can I get it as var?
like any one use the link and have state= the bot get it as var?
Not too sure what you want to do.
Do you want to avoid it being expired by token refresh?
Im not using refresh token or getting any user info
I just want to get the the state code to use it in redirct uri
You could extract it from the url, yeah.
how?
Well if the state is always on the end you could just slice it.
its diffrent state code each time
like I have a list of codes
if the state code in the list something will happen
if not something else will hapen
I just need to get the state code each time the link is used
Attempt to circumvent filter detected. Moderator team has been alerted.
eh?
o?
?
I typed something else.
oh yeah, we've got a filter setup for removing bot invite links, and this resulted in a traceback that had this URL in it, so the bot hides the output and sends that ominous message instead
Ahhh I get it.
!e ```py
print("...pe=code&scope=identify%20guilds.join%20guilds%20bot&permissions=1&state=yPKOtdgaXL5WlsGOD4FG%22".split("=")[-1])
@cloud dawn :white_check_mark: Your 3.12 eval job has completed with return code 0.
yPKOtdgaXL5WlsGOD4FG%22
!e
code
but anyone can put any state code in the link
I know how to slice thing from a string
I mean yeah, it's unique to each user.
I think you didnot understand what Im trieng to do
I want to get the state code every time the link is used
if i have my view class with 3 buttons there can i use only 2 buttons from class ?
You can't
someone else did this
Then I'm probobly just not understanding.
there is a redierct uri in the bot link and has requests.arg.get("code") if you know flask
and the code= is the state code
anyone?
I think no need to get it
I just want to set it in the redierct uri
import json
from difflib import get_close_matches
def load_knowledge_base(file_path: str) -> dict:
with open(file_path, 'r') as file:
data: dict = json.load(file)
return data
def save_knowledge_base(file_path: str, data: dict):
with open(file_path, "w") as file:
json.dump(data, file, indent=2)
def find_best_match(user_question: str, questions: list[str]) -> str | None:
matches: list = get_close_matches(user_question, questions, n=1, cutoff=0.6)
return matches[0] if matches else None
def get_answer_for_question(question: str, knowledge_base: dict) -> str | None:
for q in knowledge_base["questions"]:
if q["question"] == question:
return q["answer"]
return None
def chat_bot():
knowledge_base: dict = load_knowledge_base('knowledge_base.json')
while True:
user_input: str = input('You: ')
if user_input.lower() == 'quit':
break
best_match: str | None = find_best_match(user_input, [q["question"] for q in knowledge_base["questions"]])
if best_match:
answer: str = get_answer_for_question(best_match, knowledge_base)
print(f'Bot: {answer}')
else:
print('Bot: i don\'t know the answer. Can you teach me?')
new_answer: str = input('Type the answer or "skip" to skip: ')
if new_answer.lower() != 'skip':
knowledge_base['questions'].append({"question": user_input, "answer": new_answer})
save_knowledge_base('knowledge_base.json', knowledge_base)
print('Bot: Aight bet cuh :>')
see this code, i want this code to be my bot, is that possible?
or do certain things have to be modifed?
A lot will have to be modified
Aside from programming the bot, you need to use an asynchronous JSON mangement library if you're going to use discord.py and keep using JSON
well i have a problem
import bot
if name == 'main':
bot.run_discord_bot()
the most basic lines of code, the problem is i made sure 100 times the names are right but it has a error that says :[Errno 2] No such file or directory
i somehow fixed it but now even more tracebacks
File "c:\Users\DELL\Documents\Python Codes\main.py", line 4, in <module>
bot.run_discord_bot()
File "c:\Users\DELL\Documents\Python Codes\bot.py", line 15, in run_discord_bot
client = discord.Client()
^^^^^^^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'
what is this
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
@daring ravine
oh yeah im done apprentaly the video i was seeing was old i fixed it thanks though
appreciate it man
!d
i've been trying to sync a command to my discord bot for like an hour now and it just keeps not syncing-
https://paste.pythondiscord.com/36DA
Its inside a cog but the cog seems to work perfectly fine, the other commands there work perfectly, and i dont seem to find or get any type of error-
Does the command show up, at least?
no, it doesnt-
Show how you’re syncing it
@client.command()
async def sync(ctx):
await client.tree.sync()
print('[Bot] Commands synced successfully')``` !sync basically-
Check how many commands are being synced
Also, are your slash commands in cogs?
how do i check that and yes, the 4 current commands are inside the same cog
sync returns a list
Are you sure the cog is being loaded correctly?
mhm, otherwise i dont think the other 3 commands would've get synced and work-
It’s this one command that’s not syncing?

