#discord-bots
1 messages ยท Page 231 of 1
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.
oh im sorry here is the full code. i have already passed that
import discord
import sqlite3
import time
import django
import twitchAPI
import bs4
import logging
import logging.handlers
import os
import datetime
import keys
# connect to sqlite3 db
sqlite3.connect("pyTourney.sqlite")
# set the bots intents
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.typing = True
# Login to discord api
client = discord.Client(intents=intents)
# check for existing logfile and rename if true
now = datetime.datetime.now()
logfile = "discord.log"
logfilebak = f"{logfile}.{now.month}-{now.day}-{now.hour}-{now.minute}"
logencoding = 'utf-8'
loghandlermode = 'w'
loglevel = logging.DEBUG
if os.path.exists(logfile):
print(f"discord.log exists, renaming existing logfile to {logfilebak}")
os.rename(logfile, logfilebak)
# enable logging
loghandler = logging.FileHandler(filename=logfile, encoding=logencoding, mode=loghandlermode)
discord.utils.setup_logging(handler=loghandler, level=loglevel, root=True)
# tell you when bot is ready to start work
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# listen for keywords and respond
@client.event
async def on_message(message):
if message.author == client.user:
print(f'{message.channel.name}{message.author.name}{message.content}')
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')
# tells the bot to run
client.run(keys.bot_token)
seems fine to me
is it giving you an error?
no errors just not printing the message content to my console. the goal for now is to be able to type anything into a specific channel and have the bot print it to my console. once i can do that i can move on to my end goal
you aren't printing anything to the console though
i am though
if message.author == client.user:
print(f'{message.channel.name}{message.author.name}{message.content}')
return
so i enable all the intents on the developper portal qnd i add
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
but it says the exact same error
how i do that
intents keyword argument
omg im a idiot
as demonstrated in the example
nested ifs are such a stupid pain sometimes
@client.event
async def on_message(message):
if message.author == client.user:
print(f'{message.channel.name}{message.author.name}{message.content}')
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')```
these arent nested
i do a ctrl c + ctrl v ?
no
so its giving me the exact info if its matching the the startswith portion
so my issue was i had my print statement returning in the if statement all i had to do was move it outside of the if statement
@client.event
async def on_message(message):
print(f'{message.channel.name},{message.author.name},{message.content}')
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')```
now its working perfectly!!!
thanks for the second set of eyes
it's league of legends
i am too so dont feel bad lmfao
๐ฉ
okay i solved that problem
now it says that an improper token has been passed
did you get the token from the dev portal?
not the client id/client secret
might want to try regenerating it if so
yes
i put it between ""
its probably the problem
what
i put the token between ""
guys can someone help me make a basic discord bot with a couple feautres
all i need is it to have 2-4 commands
while i have your brain maybe you can help point me in the direction with this. when i type anything other than the 2 commands it errors out but works fine if i have just a single command
if not message.content.startswith('$hello', '$dead'):
await message.channel.send(f'Hello {message.author.name}! Only the following commands can be used in this channel. $hello, $dead')
heres a super simple template you can work off of but youll need to setup the bot on the discord developer site and get your bot token
import discord
# set the bots intents
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.typing = True
# set the bots token
bot_token = 'YOUR TOKEN GOES HERE'
# Login to discord api
client = discord.Client(intents=intents)
# tell you when bot is ready to start work
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# listen for keywords and respond
@client.event
async def on_message(message):
print(f'{message.channel.name},{message.author.name},{message.content}')
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')
# tells the bot to run
client.run(bot_token)
figured this one out on my own so nevermind! just had to change it to if not message.content == '$hello''$dead':
If anyone could give me help on how i can save an intventory system in aiosqlite
await cursor.execute("CREATE TABLE IF NOT EXISTS inventory (user INTEGER, items LIST)")
I want to make it User ID and then the items which is a dictionary
and im confused on how to make the items a dictioanry
?
you could have user_id, item_id, quantity in one table
OH
and item_id, item_name, etc in another
ok ty ty
so ive got a new issue where im getting confusing info in google... i want to make sure the bot is only responding to commands in a specific channel
@client.event
async def on_message(message):
print(f'{message.channel.name},{message.author.name},{message.content}')
if message.author == client.user:
return
if message.channel.name == 'offlines-bot':
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')
if not message.content == '$hello''$dead':
await message.channel.send(f'Hello {message.author.name}! Only the following commands can be used in this '
f'channel. $hello $dead')```
from what ive read comparing message.channel.name to a string should work but all its doing is keeping the bot from responding at all now
I would recommend you use the commands extension instead of manually parsing everything
how to make blue text in Title ? this method doesnt work like bellow
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
url kwarg ^
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix='!', intents = intents)
@client.command()
async def ping(ctx):
await ctx.send('Pong!')
@client.event
async def on_ready():
print('The bot is active now and logged in as {0.user}'.format(client))
client.run('Token Here')```
I am trying to run the prefix with this, but its not running, can anyone tell me whats wrong here?
You need message content intent
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("!hello"):
await message.channel.send("Hellooooo!")```
Something like this?
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.
ohhh
is there a way to disable a button inside a command?
so i have a function ``` async def main_function(arg):
....
....
return thing1,thing2
@client.command()
async def function(ctx):
thing1,thing2=await main_funtion(someting)
embed=discord.Embed(title='name',color=color)
embed.add_field(name="someting1",value=thing1)
embed.add_field(name="someting2",value=thing2)
``` when i call !function it says RuntimeError: Event loop is closed , i believe the error is in the way i call async main function, how do i fix it(feel free to ping)
this is full error message Traceback (most recent call last):
File "C:...\lib\asyncio\proactor_events.py", line 116, in del
File "C:...\lib\asyncio\proactor_events.py", line 108, in close
File "C:...\lib\asyncio\base_events.py", line 750, in call_soon
File "C:...\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed
you believe that's the error?
Try doing some programming 101 stuff.
Add a print() on every single line lol see what prints, what doesn't. If nothing is printing
i fixed it
ah nice (:
chat gpt did to be precise
it needed asynco loop
like this
loop = asyncio.get_event_loop()
thing1, thing2 = await main_function(someting)
embed = discord.Embed(title='name', color=color)
embed.add_field(name='someting1', value=thing1)
embed.add_field(name='someting2', value=thing2)
await ctx.send(embed=embed)
loop.close()
Now for my question:
In on_interaction listener, is there a way to stop command from continuing, or maybe pausing it?
Such as
@commands.Cog.listener()
async def on_interaction(self, interaction):
if not userRegistered(interaction.user):
stopCommand()
registerUser()
asyncio.sleep() ?
judging from your code, are you trying to register a user before further processing of their interaction?
correct. take a Balance command for instance.
I need all of the on_interaction to happen before the balance starts
for pycord, override the on_interaction method in your Bot class and do it before running process_application_commands()
https://github.com/Pycord-Development/pycord/blob/v2.4.1/discord/bot.py#L1166-L1167
discord/bot.py lines 1166 to 1167
async def on_interaction(self, interaction):
await self.process_application_commands(interaction)```
oh lol my name was PyCord before that library came out, sorry for confusion.
I use NextCord, but that should still work
it might not
yea, weird. i don't use process_application_commands()
oh nevermind they do the exact same thing
https://github.com/nextcord/nextcord/blob/v2.4.2/nextcord/client.py#L1999-L2000
nextcord/client.py lines 1999 to 2000
async def on_interaction(self, interaction: Interaction) -> None:
await self.process_application_commands(interaction)```
oh and a caveat is that views and other listeners are still dispatched concurrently
also, wouldn't on_interaction have to happen first for this to work?
i put print() commands at start/end of both functions
what is balance? a slash command?
correct
@nextcord.slash_command()
@cooldowns.cooldown(1, 5, bucket=cooldowns.SlashBucket.author)
async def balance(self, interaction:Interaction, user:nextcord.Member=None):
how did you override the on_interaction handler?
oh, that's a good point.
it's a listener in one of my cogs.
does it need to be part of my bot class?
ya, not a listener
interesting. i thought they were equal 
the handler and listeners do get called at the "same" time, but Client.on_interaction is the one that dispatches your slash command, so thats where you want to put your pre-registration code
actually a before_invoke hook of some form might be a more preferable choice if thats available
or maybe it wouldnt, before_invoke gets called after checks have been run
well regardless nextcord seems to have that option as a global hook
https://docs.nextcord.dev/en/stable/ext/commands/api.html#nextcord.ext.commands.Bot.application_command_before_invoke
shit. i was only looking at available cog listeners ๐ฎ
wow the description of it just matches my case almost perfectly
import discord
TOKEN = os.getenv('Token')
client = discord.Client()
@client.event
async def on_ready():
print(f'Logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'Hi bot':
await message.channel.send('Hello human!')
client.run(TOKEN)```
is this code right?
?code
!code
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.
do i need to turn on all intents?
only the ones you need
ok
do discord modals have a limit of 5 fields?
Yes
i got this error, can someone help me? (im learning python)
ERROR discord.client Ignoring exception in on_voice_state_update Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 441, in _run_event await coro(*args, **kwargs) File "main.py", line 145, in on_voice_state_update if before.channel.name == channel_name: AttributeError: 'NoneType' object has no attribute 'name'
@bot.event
async def on_voice_state_update(member: discord.Member, before: discord.VoiceState, after: discord.VoiceState):
channel_name = f":unlock:ใป๐ฒ๐๐บ๐๐๐บ ๐ฝ๐ {member.name}"
if after.channel != None:
if after.channel.id == 1094531305632436304:
temp_channel = await after.channel.clone(name= channel_name)
await member.move_to(temp_channel)
if before.channel.name == channel_name:
if before.channel != None:
if len(before.channel.members) == 0:
await before.channel.delete()```
thats bad
means before.channel is None
so what can i do to fix it?
how can i fix this
make sure before.channel is not None before trying to access .name
before means the voice state before the changes, the issue could be that the user wasnt connected to the vc before
also..
the error tells you
after is the voice state after the changes, e.g. the user that wasnt in the vc joined
where does any come from?
see how intents are passed here
I use internet
but why do you have 2 clients running
o yea
what should a normal command's context be type hinted with
edit = one sec
There is interaction.data which returns the raw interaction data as a dict
commands.Context
Could someone help me with application_command_before_invoke
https://docs.nextcord.dev/en/stable/ext/commands/api.html#nextcord.ext.commands.Bot.application_command_before_invoke
It says I can use it from other cogs... but how ;-;
I need to call a function from my main class before every application command runs
thnx
It says I can use it from other cogs... but how ;-;
what
the docs doesn't mention it
guys how can I make commands
if i have a modal with a default_value it doesnt trigger the callback when i press submit, can someone help me?
how can I fix this? The error message says after "UnboundLocalError: local variable 'aaa' referenced before assignment" ```py
aaa = "None"
bbb = "None"
button1 = Button(label="Streamer", style=discord.ButtonStyle.green)
button2 = Button(label="Referee", style=discord.ButtonStyle.green)
b3 = Button(label="test", style=discord.ButtonStyle.green)
async def streamer_callback(interaction):
aaa = aaa.replace("None", f"{interaction.user}")
desca = f"The {one.mention}`{one.name}` are going against the {two.mention}`{two.name}`. \n\n" + f"Streamer : {aaa}" + f"\n Referee : {bbb}"
a = discord.Embed(title='Test', description=desca)
print(interaction.user)
button1.disabled = True
await interaction.response.edit_message(embed=a, view=view)
How do you detect if a message object is a voice message and how do yo get its content ?
how can i set on_member_join event only for a specific guild ?
just use an if statement??
pretty sure a voice message is just an mp3/ogg attachment
oh yeah my baddd ๐น
sorry
@smoky sinew what's the parameter to get the guild id ?
Hey guys, what's the best way to set up permissions for each server to execute commands in a customizable way? I want to make a bot that can be used on multiple servers, but I don't fully understand how to do it yet. I've only tried using a database, but I'm afraid I'll run into limitations...
Perhaps the disnake library can help with this, or I'm not sure...
does anyone have a non outdated video for discord bots in python ? how to make one ? just to get started ?
parameter of what
A database is the right way to go here.
what kind of permissions? in discord.py you can use the @commands.has_permissions and @commands.bot_has_permissions decorators
if you want them to be assignable by the server owner then yes i would use a database for that
Okay, can you provide an example of a database? Or at least what columns with which parameters should be created?
How do I convert an ogg file to MP3 asynchronously in memory. 
I have tried to use pydub combined with asyncify but idk
(meanwhile, me here using pydub and moviepy synchronously and saving things on disk)
no clue
i would just use ffmpeg if i were you
you could run it separately from the bot event loop

import os
import discord
from pystyle import Colors, Colorate
from pystyle import Box
from pystyle import Center
from luxor import luxor
from discord.ext import commands
from discord import app_commands
class Test(commands.Cog):
def __init__(self, luxor):
self.luxor = luxor # sets the client variable so we can use it in cogs
# @commands.Cog.listener()
# async def on_ready(self):
# # an example event with cogs
#
# @commands.command()
# async def command(self, ctx):
# # an example command with cogs
@commands.command()
@luxor.tree.command(name="help")
@app_commands.describe()
async def help(interaction: discord.Interaction):
hembed = discord.Embed(
title="Luxor", color=0x313338
)
hembed.add_field(name="Bot Help", value="*Please reference to our discord server.*", inline=False)
hembed.add_field(name="Commands", value=("""blah"""))
await interaction.response.send_message(embed=hembed)```
Need some assistance using cogs with app commands.
import os
import discord
from pystyle import Box
from pystyle import Center
from dotenv import load_dotenv
from discord.ext import commands
from discord import app_commands
from pystyle import Colors, Colorate
# Hardcoded until I figure out WTF is going on with .env
luxor = commands.Bot(command_prefix="-", intents=discord.Intents.all())
async def main():
for f in os.listdir("./cogs"):
if f.endswith(".py"):
luxor.load_extension("cogs." + f[:-3])
await luxor.run("you thought")
# Color Options
# black_to_white, black_to_red, black_to_green, black_to_blue,
# white_to_black, white_to_red, white_to_green, white_to_blue,
# red_to_black, red_to_white, red_to_yellow, red_to_purple,
# green_to_black, green_to_white, green_to_yellow, green_to_cyan,
# blue_to_black, blue_to_white, blue_to_cyan, purple_to_blue,
# yellow_to_red, yellow_to_green, purple_to_red, purple_to_blue,
# cyan_to_green, purple_to_blue```
Your cog file needs a setup function that will load the cog to the bot when the file is loaded, something like: ```py
async def setup(bot):
await bot.add_cog(Test(bot))
Hi. I'd recommend against using pystyle.
Pystyle authors are known malware developers. In the past, they also infected the pystyle package itself by adding a malicious dependency.
When people started spreading message of it being malicious, they claimed their pypi account got hacked... But you can never be sure whether they won't do anything like that again.
Also, a lot of new malicious packages they try to release (ie: they release them but they get removed fast, hence "try") also use pystyle source as filler code so the package looks real if you don't check the setup.py
Alright.
async def setup(luxor):
await luxor.add_cog(Test(luxor))```
?
Yeah that should be fine
Just dies.
Do you have luxor.run(...) somewhere?
not in a cog.
main file
Where is main being called?
here
oh wait
tracemalloc
never awaited
Also I think you have to sync app commands after loading the cog for them to show up
huh?
sync it?
this is the ready cog
import os
import discord
from pystyle import Colors, Colorate
from pystyle import Box
from pystyle import Center
from luxor import luxor
from discord.ext import commands
from discord import app_commands
class ready(commands.Cog):
def __init__(self, luxor):
self.luxor = luxor # sets the client variable so we can use it in cogs
def clear():
os.system('cls')
# @commands.Cog.listener()
# async def on_ready(self):
# # an example event with cogs
#
# @commands.command()
# async def command(self, ctx):
# # an example command with cogs
status = "In Visual Studio Code..."
@commands.Cog.listener()
async def on_ready(self):
await luxor.change_presence(status=discord.Status.idle, activity=discord.Game(name=f"{status}"))
try:
commands = await luxor.tree.sync()
clear()
print(Colorate.Vertical(Colors.purple_to_blue, Center.XCenter('''
โโโ โโโ โโโโโโ โโโ โโโโโโโ โโโโโโโ
โโโ โโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโ โโโ โโโ โโโโโโ โโโ โโโโโโโโโโโ
โโโ โโโ โโโ โโโโโโ โโโ โโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโ
โโโโโโโโ โโโโโโโ โโโ โโโ โโโโโโโ โโโ โโโ''')))
print(Colorate.Horizontal(Colors.white_to_green, Center.XCenter("\nStatus - Connected")))
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter("\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")))
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter(f"User - {luxor.user}")))
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter(f"Commands - {len(commands)}")))
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter(f"Servers - {len(luxor.guilds)}")))
print('')
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter("Invite:")))
print(Colorate.Horizontal(Colors.white_to_black, Center.XCenter(f"https://discordapp.com/oauth2/authorize?&client_id={luxor.user.id}&scope=bot&permissions=8")))
print(Colorate.Horizontal(Colors.purple_to_blue, Center.XCenter("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")))
except Exception as error:
print(error)
def setup(luxor):
luxor.add_cog(ready(luxor))```
Could you maybe enlighten me on how to use the attachment object as a file for pydub.
I have tried reading it, passing it as it is. I have tried a lot of stuff over the hours with no luck.
I was actually looking at your cog example.
lmao
bot loads.
commands don't work.
@austere prairie did you give up on me
By the looks of it, fix your indentation
Not very helpful, there's 0 code errors.
I moved the run outside of the main function
but now it's not registering the main function
Cogs are classes. Anything you want needs to be in the cog itself not merely the file
?
Mobile code formatting is showing all of your code to be outside the class, therefore outside the cog
Could I screenshare to you mudkip
sure

your indentation is all wrong here
could you provide a small example using a custom name for the client and app commands
# @commands.Cog.listener()
# async def on_ready(self):
# # an example event with cogs
#
# @commands.command()
# async def command(self, ctx):
# # an example command with cogs
Like you did here but with app commands.
i don't think i wrote that
simple cogs example in discord.py. GitHub Gist: instantly share code, notes, and snippets.
simple cogs example in discord.py. GitHub Gist: instantly share code, notes, and snippets.
scroll down

it doesn't even have intents ๐
Maybe help this poor soul out 
i don't use pydub
i haven't heard of that before also
could you uhh
That's not the part i need help with tho
d o that
what custom name
any litterally
did you scroll down
it can be mudkip
bruhh
what
don't use that gist
I just wanna know how to treat a discord attachment as a file
you just replace the one in the example with your own name
Why do you use bot though
because it's a bot
what ๐

you put
@commands.command()
async def command(self, ctx: commands.Context) -> None:
pass```
if it was a app command
the example is not for app commands
the example was to demonstrate extensions
and cogs
if you want i could make another example for app commands though
Please ๐ญ I just want a separate folder for commands.
yeah it can save it as bytes
On July 27, 2021, Discord announced that effective May 2022, bot developers will be forced to migrate their bots to use slash commands
that's why it says file-like object instead of file
that doesn't mean you can't still make them
they've just locked message content behind an intent
and you shouldn't use discord.Intents.all() because once your bot reaches 100 servers you're going to have to apply for the privileged intents
Then what does read do ๐
discord.Intents.default() and message content intent if you're using commands.Bot
or even better use discord.Intents.none() and specify only the intents you want to use
!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.
read reads the attachment content as bytes
save writes the attachment content to an io.BufferedIOBase or to a file
or nah
no it doesn't take parameters
Ah
Ok
so on that example
so basically
cogs are useless? and use extensions
wait no brain
extensions is the folder
ok
yes that is the most common way to use cogs and extensions
Using them in unison
ok
so app commands with cogs?
instead of ```@commands.command()
async def command(self, ctx: commands.Context) -> None:
pass
```
also wtf is ctx
context for what??
A basic slash command example for discord.py v2.x. - bot.py
๐ญ
MY BRAIN HURTS SM
i can barely keep up with your questions
I'm just trying to get one working command with this shit 
don't bother with context if you're using app commands
context is information about where and who ran the prefix command
wtf is that even for bro 
OH
Like when you get user
so like ctx.user.id
inside a normal command
ctx.send_message(f"who sent this: {ctx.user.id}")
pretty much
don't have one
this is so weird to me
what is
cause I was like doing
@client.tree.command(name="download")
@app_commands.describe(pack=cmddesc)
@app_commands.checks.has_any_role(762044720762716190, 762044945233739816, 762045678426914906)
async def dl(interaction: discord.Interaction, pack: str):
pack = pack.lower() # choice``` Your code is so different.
what's the
also
ur code straight copy paste
am I using the wrong discord.py or something?
oh remove the await at the end
o lol
guild = client.get_guild(1074296554149654580)
role = guild.get_role(1098306389237055579)
member = guild.get_member(921314333567352862)
await member.add_roles(role)
AttributeError: 'NoneType' object has no attribute 'add_roles'
get_member can return none if the member isn't in cache
async def try_member(id: int, /, *, guild: discord.Guild) -> discord.Member:
return guild.get_member(id) or await guild.fetch_member(id)
use something like this @slate swan
Yeah better
what is the / * for
positional-only and keyword-only arguments
or simply do
guild.fetch_member(id) ?
yes but that's not often necessary
fetch_member always makes a request to discord's API
Nah, over-complicate at all costs.
get_member gets it from cache
avoiding api requests is best if you can
if you can get it from cache, you should
ringadingadinga
how to put member in cache ?
@smoky sinew
seconds = 86400 if delete_messages else 0
what in the python??? explain how this works wtf
don't you have to
if (condition) wtf
no??
what does ( mean
(condition) is the same as condition
the parenthesis are unnecessary
yes?
wtf
so
seconds
then if condition (basically if true)
that hurts me to read omg wtf
imma take python course ๐
im used to c++ bro

@smoky sinew
await member.add_roles(role)
^^^^^^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'add_roles'
i did fetch members but didnt work
await try_member*
that's not important
Just wondering in general.
Most for a perspective of age to experience.
Are you 20's 30's
if you want to talk about it go to my discord
oki
I did
rather than just deleting the comments
take a look again, you changed it
oh nvm i see
i meant to put the command after
whats the diff
also why are they repeated..
cause I have no idea how this works still.
and it should be intents=intents not intents=discord.Intents.default()
is it possible to get user's roles in the guild with discord oauth2
your code shawty
oh
try using the guilds.members.read scope
then you can access this endpoint
I'm using it in a cog
I know how to do app commands
I needed to know how to do it in a cog
it's the same thing
In an extension, this would be @app_commands.command() instead.
you put it above the description line
so I thought u meant description
AttributeError: 'Client' object has no attribute 'command'
token leaked 4k
I feel like your brain hurts speaking to me. Lol
it's ("commands.help",) with the comma
I removed it
also you shouldn't be separating each command in its own file that's not really what extensions are meant for
same error
and it's bot = commands.Bot
o
bots have prefix commands, clients don't
and you don't need to import app_commands in the main file, only in the extension file
o
File "C:\Users\lux\Desktop\luxor\luxor.py", line 29, in <module>
bot.run("token")
File "C:\Python\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Python\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\Python\lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Python\lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Python\lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\lux\Desktop\luxor\luxor.py", line 27, in setup_hook
await bot.load_extension(extension)
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'c' could not be loaded.```
no idea
what is extensions equal to right now
commands.help
just show your two files
what's the point then.
and it's @app_commands.describe not description
I just wanted each command to have afile
you should be using separate cogs/extensions for different categories of commands like moderation fun etc
ah
or well you could probably get more specific than that
but it should be a few commands per
File "C:\Python\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Python\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\Python\lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Python\lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Python\lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\lux\Desktop\luxor\luxor.py", line 27, in setup_hook
await bot.load_extension(extension)
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.help' raised an error: AttributeError: module 'discord.app_commands' has no attribute 'description'
x10
can you at least read what i'm saying
Don't be rude muddy.
Traceback (most recent call last):
File "C:\Users\lux\Desktop\luxor\luxor.py", line 29, in <module>
bot.run("token")
File "C:\Python\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Python\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\Python\lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Python\lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Python\lib\site-packages\discord\client.py", line 621, in login
await self.setup_hook()
File "C:\Users\lux\Desktop\luxor\luxor.py", line 27, in setup_hook
await bot.load_extension(extension)
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Python\lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.help' raised an error: TypeError: unknown parameter given: member```
omfg
you removed the parameter from the describe decorator but it's probably still in your command
It's in there.
idk what you changed
from discord.ext import commands
from discord import app_commands
import discord
class Help(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self) -> None:
pass
@app_commands.describe(
member="The member to ban.",
reason="The reason for banning them.",
delete_messages="Whether to clear their messages in the past day."
)
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.command() # bot.tree.command # outside of cogs
async def ban(
interaction: discord.Interaction,
member: discord.Member,
reason: str,
delete_messages: bool = False
) -> None:
embed=discord.Embed(
title="Wasif is gay.",
description="Potatos",
color=0xFF5733)
await interaction.response.send_message(embed=embed)
@commands.command()
async def command(self, ctx: commands.Context) -> None:
pass
async def setup(bot) -> None:
await bot.add_cog(Help(bot))
# In an extension, this would be @app_commands.command() instead.
# All slash command arguments need to have type hints. (e.g. str, int, discord.Member, etc)
huh
it's all there bro.
was that after you ran the command
No
on start
File "C:\Users\lux\Desktop\luxor\commands\help.py", line 21, in Help
async def ban(
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 2121, in decorator
_populate_descriptions(inner._params, parameters)
File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 276, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: member
top part
@smoky sinew u give up??
i think you forgot to save your code
u forgot self param in callback too btw
its saved
??
they didn't forget it they just didn't know they needed it
true
what the problem???
No problem
what is the problem in this help https://github.com/torvalds/linux
No problem
no problem
guys help me pls
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.
@fiery hare
Hello! could i make slient message by discord bot?
i can but with normal user like @slient
but when i try put it in discord bot it just send it lol
like this
this not silent message
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
silent kwarg
Does it allowed_mentions=None?
i can't see silent
and what is allowed_mentions=None do??
check here
o
ok then
ok done
ah why it now ask me for this?
it was working a???
does discord change it???
or do i need update nextcord or what
are you using discord.py or nextcord
zeffo asked you to update discord.py
i use both
i did then after i run my code it start this error
nope still not working
Both??
yes
Why
all my import from ast import Interactive from typing import Literal import discord from discord.ext import commands from time import sleep import random import nextcord from nextcord import File, ButtonStyle from nextcord.ui import Button, View import os import asyncio
ah check import
What would that explain
wtf
you can't use both
o
ok i will choose nextcord
now how delete the other one?
pip3 uninstall discord.py?
ah
when i delete import nextcord
i got 200 errors
when i delete discord.exe
it only get 2 errors lol
discord.exe ?!
oop sorry from discord.ext import commands
but it give me this 3 errors
here bot = commands.Bot(command_prefix = '!', intents=discord.Intents.all())
and here @commands.has_permissions(administrator=True)
2 times here
how fix them?
class nextcord.ext.commands.Bot(command_prefix=(), help_command=..., description=None, *, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, ...)```
Represents a discord bot.
This class is a subclass of [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") and as a result anything that you can do with a [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.GroupMixin "nextcord.ext.commands.GroupMixin") to provide the functionality to manage commands.
a? class?
lmao
This channel is for discord bots, you can make a help channel to ask this: #โ๏ฝhow-to-get-help
ok thanks
ok how fix this
Same way
I saw this cool feature in dank memer
And i wondered how they made that graph. I did research and learnt about MatPlotlib which works but does not have a nice design. Due to this i tried to find other ways of doing it
Which way is the best, currently im thinking of Pillow and mapping the values to a y coordinate
!pypi matplotlib perhaps
Use matplotlib lib to generate it and pillow to show it to the end user
Maybe try pyqtgraph
wait?
you can edit the image using PIl how ?
since all i want from the graph
is just a value on left hand side
and the graph line
using it
i created
but how do i remove the box outside it and al lthe values
i just want the graph
Search how to hide the tick labels, you'll find something online
im confused with pasting
i have background
and i have
graph which is transparent background
and when i paste these
the logo just disappears
im confused as to why logo just disappears
and the graph is transparent it is not overlapping it?
this is background
and im pasting the transparent graph over it
and somehow the logo disappears
What colour
Show the code
Can I add buttons in the bot in this engine
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
here
click where you see 3.10.6
Try py -3.10 -m pip install nextcord
yes
let me see
wait 1 sec i will photo other one
i will ping
guys
How can I add buttons in the bot discord
on replit
what is this
example usage of buttons
k thank
hello guys,
I need a help to access the class variable(self.something) in my cog class.
is that possible in any way?
class MyClient(commands.Bot):
def __init__(self, intents: discord.Intents,
something):
super().__init__(intents=intents,
command_prefix='$',
activity=discord.Game(name="api"))
self.something = something
class UserProfile(commands.Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
@discord.app_commands.command(name='profile', description='Fetches the profile')
@discord.app_commands.describe(member="mention the user")
async def profile(self, interaction: discord.Interaction, member: Optional[discord.Member]):
// here I want to use self.something
member = member if member is not None else interaction.user
await interaction.response.send_message(f'ok I got {member.display_name}')
interaction.client.something
or
self.bot.something
it's not working
error?
yeah
on using self.bot.something
2023-04-23 17:14:58 WARNING root Failed to load extension: Extension 'bot.cogs.controllers._profile' raised an error: AttributeError: 'MyClient' object has no attribute 'something'
on using interaction.client.something
discord.app_commands.errors.CommandInvokeError: Command 'profile' raised an exception: AttributeError: 'MyClient' object has no attribute 'something'
what error?
you didn't add the attribute then , where did you add it?
make sure the files saved and stuff
I did
show the part of code where you add it
umm means?
the line...
I got it
it's working now
thanks a lot bro
I have an issue where my code does not work when I put it into an async function
But I need to use async to await sending a message to a channel
to get the guild id
open your cmd window
and write pip install discord.py
import discord
class InviteTracker(commands.Cog):
def __init__(self,client):
self.client = client
@commands.Cog.listener()
async def on_member_join(self, member):
inviter = await self.get_inviter(member)
if inviter is not None:
inviter_name = inviter.name + "#" + inviter.discriminator
total_invites = await self.get_total_invites(inviter)
embed = discord.Embed(
title=f"โ
ใป{member.name} joined.",
description=f"They were invited by **{inviter_name}** who now has **{total_invites}** Total invites.",
color=discord.Color.green()
)
await self.client.get_channel(1093657090100305940).send(embed=embed)
async def get_inviter(self, member):
invites = await member.guild.invites()
for invite in invites:
if invite.inviter == member:
return invite.inviter
return None
async def get_total_invites(self, inviter):
invites = await inviter.guild.invites()
for invite in invites:
if invite.inviter == inviter:
return invite.uses
return 0
def setup(client):
client.add_cog(InviteTracker(client))```
Bot dont send message
Without error
member intents enabled? And what's your discord.py version?
ty for the help again
Help!
import discord
from discord.ext import commands
Set up your bot client with the command prefix
client = commands.Bot(command_prefix='/')
Event listener for when the bot is ready
@client.event
async def on_ready():
print('Bot is ready!')
Command for the /say command
@client.command()
async def say(ctx, *, message):
await ctx.send(message)
Replace 'TOKEN_HERE' with your bot's token
client.run('TOKEN_HERE')
https://media.discordapp.net/attachments/955353201446621225/1099652873907867678/image.png i was able to include it into my bot
looks clean ๐
tyty
.
with?
Code
import discord
from discord.ext import commands
Set up your bot client with the command prefix
client = commands.Bot(command_prefix='/')
Event listener for when the bot is ready
@client.event
async def on_ready():
print('Bot is ready!')
Command for the /say command
@client.command()
async def say(ctx, *, message):
await ctx.send(message)
Replace 'TOKEN_HERE' with your bot's token
client.run('TOKEN_HERE')
.
:
what help do you need with it
I cant fix the error.
what is the error
Wait a sec pleas
!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.
what the code of common embed color ?
what do you mean by that?
this line on left side - whats the code of color to make it merges with all embed
Intents enabled version 1.7.3
how can i get the guild for on_member_join event ?
guild = client.get_guild(id of your guild)
no but i want to get the guild id of the server where a new members spawned
guild = client.get_guild(member.guild.id)
kinda this
okay thx
Why not just member.guild 
it accepts only id not guild object
because he needs get id
it can be name also
I mean, why getting the guild using get_guild while you can just get it from the member.guild property

ah correct i did not notice they are talking about event
import discord
class InviteTracker(commands.Cog):
def __init__(self,client):
self.client = client
@commands.Cog.listener()
async def on_member_join(self, member):
inviter = await self.get_inviter(member)
if inviter is not None:
inviter_name = inviter.name + "#" + inviter.discriminator
total_invites = await self.get_total_invites(inviter)
embed = discord.Embed(
title=f"โ
ใป{member.name} joined.",
description=f"They were invited by **{inviter_name}** who now has **{total_invites}** Total invites.",
color=discord.Color.green()
)
await self.client.get_channel(1093657090100305940).send(embed=embed)
async def get_inviter(self, member):
invites = await member.guild.invites()
for invite in invites:
if invite.inviter == member:
return invite.inviter
return None
async def get_total_invites(self, inviter):
invites = await inviter.guild.invites()
for invite in invites:
if invite.inviter == inviter:
return invite.uses
return 0
def setup(client):
client.add_cog(InviteTracker(client))```
Bot dont send message
Without error
The only issue I see is that your functions are defined after your command.
I'm not sure if python works the same as C++ but I'm pretty sure in general coding languages you have to define before?
What
async def get_inviter(self, member):
invites = await member.guild.invites()
for invite in invites:
if invite.inviter == member:
return invite.inviter
return None
async def get_total_invites(self, inviter):
invites = await inviter.guild.invites()
for invite in invites:
if invite.inviter == inviter:
return invite.uses
return 0```
Try moving these before your listener
@old ibex hey, by any chance do you know aiosqlite
I've used it with node.js.
have you gotten this error before?
aiosqlite is a python lib how u used with node?
Kk i will try
where are you closing?
Could you show that I don't see the commit line
oh waitI see now
That error is basically saying the database your trying to commit to is closed.
how tho?
also you're not using a try
and finally
it's just straight through
what is this even for?
u need to open the cursor inside the callback using async with also
It's so hard for to read
so basically repeat the cursor again
no spacing ๐
yes
its indented
I meant between sections
i copied and pasted
That makes more sense.
made a function that fetches the most common color on the bot profile picture. i call it right on setup_hook: should i annotate it as Optional? i wrote it on a way that this is not needed, because checking for None is really annoying when i'm pretty sure that this attribute will not be None when it is accessed. i'm looking at you, Client.user
https://github.com/Rapptz/discord.py/blame/v2.2.2/discord/client.py#L613
since dpy 2.0 its guaranteed to be set before setup_hook() is called, but given that its undocumented you might not know if they'll change it later
in this case i'd try to structure the code such that one check helps the type checker infer user as not none as far as it can
perhaps a property and write a assert statement or a typecast
assert seems more appropriate tbh
@bot.slash_command(name="methodslist",
description="CMD used to display methods list")
async def methodslist(ctx):
for method in os.listdir(f"users_data/{ctx.guild.id}"):
method = method + "\n"
await ctx.respond(
embed=discord.Embed(title='', description=f'{method}', color=0x50468a))
i want to make an embed respond with all file names
what should i add ?
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
You can use this instead of manually iterating and adding to string
gimme syntax pls ๐น
@meager chasm :white_check_mark: Your 3.11 eval job has completed with return code 0.
a, b, c
but
look
there is something like that
it can be 0 file like 100 files
i don't know how much files there will be
So
Os.listdir gives you all of them
Although it would be preferable to use pathlib (especially if you're looking to get files from sub-directories as well)
Any who have discord.py music bot and can send me code?
@tall temple :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 4
002 | folder = pathlib.Path(f"users_data/{ctx.guild.id")
003 | ^
004 | SyntaxError: f-string: expecting '}'
kk
and how should i handle a command that was not found? using a global eh here
!e
@bot.slash_command(name="methodslist",
description="CMD used to display methods list")
async def methodslist(ctx):
folder = pathlib.Path(f"users_data/{ctx.guild.id}")
await ctx.respond(embed=discord.Embed(
title='', description = f"{'\n'.join(folder.iterdir())}", color = 0x50468a))
@tall temple :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 6
002 | title='', description = f"{'\n'.join(folder.iterdir())}", color = 0x50468a))
003 | ^
004 | SyntaxError: f-string expression part cannot include a backslash
Is it possible to add buttons to welcome messages
Cause im kinda lost. My welcome message needs async def on_member_join and my buttons need async def button(ctx):
Sure, it's just a view
Im literally lost while doing it
hey have you a code for music bot , for play in infinity my code no play in infinity
@dense jackal
class MyView(discord.ui.View):
def __init__(self) -> None:
super().__init__()
@discord.ui.button(label="Click me!")
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
...
async def on_member_join(member: discord.Member) -> None:
view = MyView()
channel = bot.get_channel(123)
await channel.send("Welcome to the server!", view=view)
Hopefully that example clears up a bit
Whatโs the interaction where when you click on the button, it redirects you to #rules
@sick birch
Is that a thing?
I don't remember that being a thing
Unless you mean just a link button
I saw a server where when you click on the button, it sends you on a page
Was it gray?
I have another question
You know the default welcome message of discord? We can send stickers via a button. Is it possible to recreate that with an interaction
Not that I know of
So what are the possible interactions
https://discord.com/developers/docs/interactions/receiving-and-responding#responding-to-an-interaction
its not all that fancy, except modals ig
by sending a link / uploading an attachment sure
How can we do so a user can interact only once
for a view your bot will forget how to respond to it after a restart by itself, but you can trigger that early by using the View.stop() method
and you can edit your button with .disabled = True so it cant be clicked again
Can we also do so its not clickable after like 2 mins
yeah, using a timeout
though if you want to visually disable the button, your view will need the initial message so it can edit it
then you only need to pass timeout=120 to your view's constructor
the default timeout is 180s
To my class MyView(discord.ui.View): ?
Oh wait I got a better idea
I want the button to be clicked only once
And then it goes failed
Only one interaction (not per members) one interaction
how you would normally do it with OOP
oh i thought thats what you wanted earlier, view.stop() prevents any button callbacks from running afterwards
Earlier I wanted one interaction max per user. Now I want one interaction max.
ok so I did this
def __init__(self) -> None:
super().__init__()
@discord.ui.button(label="Click to welcome the new user!")
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.response.send_message("Bond was created just now uwu test")
button.disabled = True
button.label = 'Bond was created!'
await interaction.response.edit_message(view=self)
...```
and it still doesn't work
โ
depends on the library and what its for, if its just discord.py there are separate approaches if its a slash command / prefix command
e.g. ```py
bot = commands.Bot(...)
@bot.tree.error
async def on_tree_error(interaction, error):
if isinstance(error, app_commands.CommandNotFound):
await interaction.response.send_message(...)
else:
raise error
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(...)
else:
raise error```
you responded with send_message already so await interaction.message.edit(...) is the only viable option for editing the view
heloo
So i saw this line of code:
@bot.command()
async def myfunc(ctx, *, var)
I'm aware that var is going to be user-defined args(?) but what are ctx and * for?
ctx is the message context, so the bot knows who invoked the command and provides some useful methods such as replying to the user
- marks the argument
varas keyword-only so everything the user puts after the command will go to that argument
^ see also
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#keyword-only-arguments
(its special behaviour provided by the library, in a normal python context the * means all parameters following it are keyword-only)
import discord
import uuid
from discord.ext import commands
# Initialise les intents pour le bot
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
# Initialise votre liste de tickets
tickets = {}
# Gรฉnรจre un ticket unique pour chaque demande
def generate_ticket():
return str(uuid.uuid4())
# Crรฉe un nouveau ticket lorsque l'utilisateur envoie une commande "!newticket"
@bot.command()
async def newticket(ctx):
# Gรฉnรจre un identifiant unique pour le ticket
ticket_id = generate_ticket()
# Crรฉe un salon pour le ticket
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True),
ctx.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
ticket_channel = await ctx.guild.create_text_channel(f'ticket-{ticket_id}', overwrites=overwrites)
# Ajoute le ticket ร la liste des tickets
tickets[ticket_id] = ticket_channel.id
# Crรฉe un bouton pour fermer le ticket
close_button = discord.ui.Button(label='Fermer le ticket', style=discord.ButtonStyle.red, custom_id='close')
# Crรฉe une vue avec le bouton de fermeture
view = discord.ui.View()
view.add_item(close_button)
# Envoie un message avec l'identifiant du ticket et la vue contenant le bouton de fermeture
await ctx.send(f"Votre ticket a รฉtรฉ crรฉรฉ avec l'identifiant {ticket_id}.", view=view)
# Ferme le ticket lorsque l'utilisateur clique sur le bouton "Fermer le ticket"
@bot.event
async def on_button_click(button: discord.ui.Button, interaction: discord.Interaction):
if button.custom_id == 'close':
ticket_id = int(interaction.message.content.split()[-1][1:-1])
# Code pour fermer le ticket avec l'identifiant ticket_id
channel_id = tickets.get(ticket_id)
if channel_id:
channel = interaction.guild.get_channel(channel_id)
await channel.delete()
del tickets[ticket_id]
await interaction.response.edit_message(content=f"Le ticket {ticket_id} a รฉtรฉ fermรฉ et le salon a รฉtรฉ supprimรฉ.")
else:
await interaction.response.edit_message(content=f"Le ticket {ticket_id} n'existe pas.")
# Affiche un message dans la console lorsque le bot est prรชt
@bot.event
async def on_ready():
print(f'{bot.user.name} est connectรฉ ร Discord et prรชt ร รชtre utilisรฉ !')
# Dรฉmarre votre bot
bot.run("")```
My bot does not create ed ticket but has no error and no reaction when I make the order
thank you!
gotcha
it seems one of my problems with looking for tutorials for discord.py bots is trying to find 'what does this particular code is called in the docs'
what library are you using? if its discord.py, on_button_click isnt an event that exists, and you should be subclass View/Button instead
example: https://github.com/Rapptz/discord.py/blob/v2.2.2/examples/views/persistent.py
oui c'est discord.py
i use this code ?
ya i wouldnt call dpy resources as being in a great place right now, there's a lot of information out there that got outdated as the library received breaking changes, not to mention ones demonstrating bad practices
Ah lord!
I use easy_pil and when someone joins with no pfp, my welcome message doesnโt send.
Im wondering what I need to change to make it work
Probably because you have to use display_avatar instead of avatar
Later ill help u
Do you guys know how to draw pixel art using turtle
what do i have to do to get the same result ?
do you mean how to fix the error, or how to implement a code executor?
the code executor is snekbox
it's a web service
that's a safe code evaluator
or do you want an admin-only unsafe command that runs in the bot itself
what exactly do you mean
lemme show u
@bot.slash_command(name="methodslist",
description="CMD used to display methods list")
async def methodslist(ctx):
folder = pathlib.Path(f"users_data/{ctx.guild.id}")
await ctx.respond(embed = discord.Embed(name = "test" , description = '"\n".join(folder.iterdir())' , color = 0x50468a))
i want to make a list in the embed desc. of all files names in a specific directory @rugged shadow
oh alr
maybe you could store iterdir's result in a variable and just join them in the description
oh, lemme try
@rugged shadow like that ?
@bot.slash_command(name="methodslist",
description="CMD used to display methods list")
async def methodslist(ctx):
folder = pathlib.Path(f"users_data/{ctx.guild.id}")
fl = folder.iterdir()
await ctx.respond(embed=discord.Embed(
title="test", description=f'{"\n".join(fl)}', color=0x50468a))
u dont need the fstring
@slate swan
what do you need help with?
in the dev portal?
go to https://discord.com/developers/
select the application you want to enable it for
select 'Bot' on the sidebar and select them under 'Privileged Gateway Intents'
these are all the privileged intents
you're welcome
can you send them here?
content ...
content, not contant
there's a typo
if message.contant.startswith("$hello")
contant=>content
no, just replace contant with content
keep going
what's the error now?

why are you doing {0.client}?
you're passing in a Bot object
which doesn't have a client attribute
get rid of the .client part
doesn't it do that by default?
just {0}
Same problem
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
i want to add 4 tab spaces in my embed
its bot.user
before the - archimedes name
somone help
whats your code right now? Are you using triple quotes?
iirc u can have spaces if you use \n instead of triple quote
@bot.command()
async def quote(ctx):
"""Sends a random quote"""
url = 'https://api.quotable.io/random'
response = requests.get(url)
data = response.json()
author = data['author']
content = data['content']
embed = discord.Embed(title="Quote", description=f"{content}\n - {author}", color=discord.Colour.random())
embed.set_footer(text=f"Information requested by: {ctx.author}")
await ctx.send(embed=embed)
get rid of space before \n
ok what differ it will make
its going to
just try :)
then just give more spaces after \n
ok
no differ
current code
sry idk how to
sec
ok
hi im using tree.py app_commands stuff in my discord bot
and there is this one command i want to remove....so the issue is, i removed the code from a file and used the same code in another file.....however the command got registered from the first file....and now there are two commands with same name
how do i remove command from tree.py
hows it possible?
u cant register two commands
idk ๐
ok
im so confused-
do \n then copy paste this
like
wait
i forgor its for normal msges only
okay so this is the first command i had made, then i removed its code and made another file in which i coded a new ping command
but that other ping command isnt showing
and when i use that ( โ๏ธ ) ping command, it shows me this error
tree.py is a file name ? or a function
ื
Akshad use this dot above after \n xd
no its not a file name
ื
did u sync commands?
mm yea i think
....
see see
from code?
'\n
i have an index file
then an env file
then a folder
this ?
Done ! Thx 
ื \n
in that folder are all my slash commands
how do u sync your commands?
\nื
@sturdy fractal
\nื
bros sending new lines
bruh what is this ? u sure it will add 4 spaces
this unicode characters ๐
put this lil dot and give as much space u want
after that dot
i had a feature in my lappy to get that type of chars but forgot how

