anyone wanna work this out for me? I have a function that does a ton of maths and takes 0.012 seconds to finish, once it finishes it saves an image which takes 0.017 seconds. I could render a new image every single time and send it in bytes which is faster but maybe 10-20% of the time people need an old image, so the rendering is completely unnecessary. is it worth saving the image?
#discord-bots
1 messages · Page 72 of 1
it would on it's face be faster to just render images every time but processing is more expensive than disk space
maybe temporarily caching it in memory as bytes?
you know that didn't even occur to me
Do you have message content intents?
Ive done discord.intents.all()
Worked for 1.7.3, but someone said it was different for 2.0
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/lol/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 2055, in on_message
await message.reply(embed=embed)
UnboundLocalError: local variable 'embed' referenced before assignment
how to solve?
embed is not defined before you try to send it
what to do now?
show code
Define embed before you use it
what object... int and str are objects as well
if you were using disnake for example you'd have to do
embed = disnake.Embed(title="this is an embed")
await message.reply(embed=embed)
types :hehe:
idk what the object would be classified as, it's a file for disnake file = disnake.File("/asdfasdf.png")
@client.event async def on_message(message): await client.process_commands(message) if message.content.startswith(f'<@{client.user.id}>'): embed = discord.Embed(color=0x2f3136, title=f".", description = f"**:arrow_05: Hey,I Am . A Multipurpose Bot Which Protect Your Server From Getting Wizzard\n\n :arrow_05: My Prefix Is** +") await message.reply(embed=embed)
this if message.content.startswith(f'<@{client.user.id}>'): is not returning as true in this case then
well then its would be disnake.File ...
event working properly but throwing error in console
!e print(isinstance(1, object))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!d inspect.iscoroutine
inspect.iscoroutine(object)```
Return `True` if the object is a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) created by an [`async def`](https://docs.python.org/3/reference/compound_stmts.html#async-def) function.
New in version 3.5.
@silk fulcrum
when i print out type i get <class 'disnake.file.File'>
what
still have no idea what i'd put here in a dataclass
disnake.File?
yep, its same ....
thats like using discord.ext.commands.bot.Bot instead of discord.ext.commands.Bot
thats the full path of the class
disnake***
i'll try this 
disnake or this snake 🐍
python snake***
Ignoring exception in on_message Traceback (most recent call last): File "/home/runner/lol/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 2055, in on_message await message.reply(embed=embed) UnboundLocalError: local variable 'embed' referenced before assignment
this is error
@client.event async def on_message(message): await client.process_commands(message) if message.content.startswith(f'<@{client.user.id}>'): embed = discord.Embed(color=0x2f3136, title=f".", description = f"**:arrow_05: Hey,I Am . A Multipurpose Bot Which Protect Your Server From Getting Wizzard\n\n :arrow_05: My Prefix Is** +") await message.reply(embed=embed)
this is code
btw you can turn on your type checker to see if you are typing stuff correctly or not...
mypy or pyright etc
Why are my cmds sending twice? Also, for prefix cmds also became a lot slower? (10-20+ Secs before it responds)
Happened when I migrated from Replit to VS Code.
Here's the error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Alliah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\bot_base.py", line 578, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Alliah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 914, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Alliah\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 181, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
Was working fine when I was still on replit. But I transferred to VS Code cuz replit too buggy 
do you have a on_message listener with process_commands?
Idk about process_commands but I do have an on_message listener
show code
""" Topic """
@commands.command(name="topic")
async def topic(self, ctx):
Responses = ("Random list of topics here")
embed = disnake.Embed(title="", description=f":BA: {random.choice(Responses)}", colour = disnake.Colour.random())
embed.set_author(name=f"Requested by {ctx.author.nick}", icon_url=f"{ctx.author.display_avatar}")
await ctx.send(embed=embed)
await ctx.message.delete()
okay so storing the disnake.file object did not work
hi
with BytesIO() as image_binary:
img.save(image_binary, "PNG")
image_binary.seek(0)
player.cache_image = disnake.File(fp=image_binary, filename="image.png")```
msg is not defined? you're using interaction
how is python supposed to know what msg is when you haven't defined it? consider why this is working
!paste
File "/home/container/.local/lib/python3.10/site-packages/nextcord/client.py", line 499, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 901, in on_interaction
closeticket = Button(label="Lösche den ticket", style=ButtonStyle.blurple)
UnboundLocalError: local variable 'Button' referenced before assignment
error
pls help
you're redefining Button
Hello, is it possible in the discord modal (modal window) to make it possible for a person to attach a picture
no, they are called "Text"inputs for a reason.... you can ask them to upload an image on discord and provide the image url tho
Okay. Thanks!
you can actually get uploads through slash commands which make it easier
Bro i didnt copy anything what are you talking about
Ong
oh btw
could u tell me now on which server you host ur bot?
Oh thanks :)
@slate swan
Cause ur bot responds so fast mine legit takes like 3 secs to respond
i removed it, still isnt working :(
have you imported button
yep
show your import line
why did you ping me for that
Alright. This fixed itself. I didn't know what the problem was but yeah. But now, I've got another issue I'm trying to fix
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: InteractionTimedOut: Interaction took more than 3 seconds to be responded to. Please defer it using "interaction.response.defer" on the start of your command. Later you may send a response by editing the deferred message using "interaction.edit_original_message"
Note: This might also be caused by a misconfiguration in the components make sure you do not respond twice in case this is a component.
I got this error when I ran a slash cmd within a cog containing API Requests
is the Api reuqest made with Requests? (use aiohttp, requests is blocking the event loop of your bot)
!pypi aiohttp
I'm using aiohttp
i might actually switch to disnake if it gives such detailed errors so much better than dpy uknown interaction
dpy needs better examples docs etc they need to get more descriptive
🚶♂️asked you to do that 2 months ago
yessir
disnake >>> dpy
well maybe next rewrite
lol
then you need to defer the interaction and then edit the original message
What does that mean, Sorry lol.
Kinda new to programiming, generally
the warning says exactly what you need to do
So postpone the interaction and edit the msg?
indeed
before making the request with aiohttp write
await interaction.response.defer()
after the request aiohttp add
await interaction.edit_original_message(embed=embed)
# this rn works as a nornal .send method
it extends the time to respond to the interaction from 3 seconds to 15 minutes
AH, alright. Will test this out
deferring an interaction you'll see NameBot is thinking...
btw this traceback is the same as the disnake ones
Noted. WIll try figuring out the rest. Thanks guys! I'll ask for more if I get stuck or smth lol
kk
@glad cradle
how to create good looking embeds in discord?
add a tab to await message.reply(...)
Yup. It worked. Thanks a lot!
you're welcome
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 107, in callback
embed = discord.Embed(description= f"""Время в войсе: {discord.utils.utcnow(tdict[interaction.user])}""", colour=0x2F3136),
NameError: name 'tdict' is not defined```
how to identify this name in the command ?
how do I move a global variable to another file ?
@commands.Cog.listener()
async def on_voice_state_update(self, interaction: discord.Interaction, member, before, after):
interaction.user = member.id
if before.channel is None and after.channel is not None:
print('1')
t1 = time.time()
tdict[interaction.user] = t1
elif before.channel is not None and after.channel is None and interaction.user in tdict:
t2 = time.time()
print('0')
print(t2-tdict[interaction.user])```
@glad cradle I was told what was wrong, I'm already thinking about how to move the global variable to another file
how
make a bot variable out of it
how ?
tdict could be bot.tdict or self.bot.tdict
and you can access it in other files too
or... is that not the variable you want to move? as I read it yes
anyways, just use the var as a botvar
@cold sonnet
class User(discord.ext.commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.tdict
@commands.Cog.listener()
async def on_voice_state_update(self, interaction: discord.Interaction, member, before, after):
interaction.user = member.id
if before.channel is None and after.channel is not None:
print('1')
t1 = time.time()
self.bot.tdict[interaction.user] = t1
elif before.channel is not None and after.channel is None and interaction.user in self.bot.tdict:
t2 = time.time()
print('0')
print(t2-self.bot.tdict[interaction.user])```
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 696, in _load_from_module_spec
setup(self)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 188, in setup
bot.add_cog(User(bot))
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 124, in __init__
self.bot.tdict
AttributeError: 'Bot' object has no attribute 'tdict'
The above exception was the direct cause of the following exception:```
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 684, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 11, in <module>
from index import discord
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\index.py", line 19, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 756, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 701, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.osnov' raised an error: AttributeError: 'Bot' object has no attribute 'tdict'
During handling of the above exception, another exception occurred:```
```Traceback (most recent call last):
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\index.py", line 19, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 756, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\cog.py", line 686, in _load_from_module_spec
del sys.modules[key]
KeyError: 'cogs.osnov'```
self.bot.tdict
is not how you define a variable
set it to something like self.bot.tdict = {} in your __init__ function
Bro! You can need update discord.py 1.7 upgrade to discord.py 2.0. Install pip install+git https://github.com/Rapptz/discord.py
don't need to install from git anymore
discord.py 2.0 is on pypi 😄
pip install discord.py is enough now
My since 4 months but this didn't update discord.py 2.0
Take chill bot
I already have version 2
Oh, can help me? "How to join vc but didn't work?"
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
that doesn't seem like v2....
Oh
!d discord.VoiceClient
class discord.VoiceClient```
Represents a Discord voice connection.
You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").
Warning
In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
make a command that makes a bot join a VC and play the blue lobster jump scare at 200 DB
should i only use slash commands now? or should i include implementations for both a normal prefixed command + slash command?
preference?
is it possible to make a bot that will be similar in functionality to getting hypescuad in discord?
how to fix
you don't have to spam
oh mb i thought it didnt send
discord.AsyncWebhookAdapter doesn't exist ig
yeah
hm....
migrating.html says "WebhookAdapter class has been removed and the interfaces based on it (AsyncWebhookAdapter and RequestsWebhookAdapter) are now considered implementation detail and should not be depended on."
the code stopped working on py 2.0
are you sure? because it seems like you are using dpy 1.7.3
do pip show discord.py
how do i downgrade my py
yes
what does pip show discord.py say?
i upg my py and the code stopped working so my new py is the probelm
ttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'```
What is WebDriver?
I know webdriver from selenium
but i don't think that is it
it is that
hm... I don't think this is related to this channel's topic
@finite falcon So, I do not recommend to downgrade to dpy 1.7.3, that is just a bad idea, too many reasons.
About solving your problem: what exactly have you done to upgrade to dpy 2.0? and did you change any code when upgrading to it?
how do i downgrade
tell me how to please ik what im doing
i can always upg after lol
Doesn't seem so. But okay, if you are sure, then: pip install discord.py==1.7.3
ty code works now
is it possible i can 2.0 and 1.73 on the same computer
uhm, yes
venvs
Whats the max character limit for a discord modal paragraph (long)?
das a lot
it can be reduced
I got mine to set to 1k
dont its annoying lol i did it once
import discord
from discord.ext import commands
import requests
from bs4 import BeautifulSoup
intents = discord.Intents(messages=True, guilds=True, message_content = True)
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def solana(ctx, arg):
try:
float(arg)
except:
await ctx.send("Should be a number")
return
if '.' not in arg:
arg = int(arg)
else:
arg = float(arg)
url = 'https://www.coingecko.com/pl/waluty/solana'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'lxml')
url2 = 'https://www.bankier.pl/waluty/kursy-walut/forex/USDPLN'
page2 = requests.get(url2)
soup2 = BeautifulSoup(page2.content, 'lxml')
pricezl = soup2.find('div', class_="profilLast").text.replace(',','.')
pricesol = soup.find('span', class_='no-wrap').text.replace('$', '').replace(',', '.')
result = round(arg * float(pricesol) * float(pricezl), 2)
embed=discord.Embed(title="Twoje {x} solan jest warte {result}zł".format(x=arg, result=result), color=0xd81adb)
embed.set_author(name="Kalkulator Solan")
embed.set_footer(text="RavdesAIO")
await ctx.send(embed=embed)
bot.run(a)
How could i make a fix to basically run command if someone write !Solana or !SOLANA? basically what comes to my mind is lowercasing this string after '!' but idk how i could access that 'Solana' string after ! cause it isnt argument is there way to do that guys?
Try
bot = commands.Bot(command_prefix='!', intents=intents, case_sensitive=False)
does it work
one guy suggested to set it to true value
but also doesnt work
This one worked thanks for help anyway @full lily
cool
hey im tryna make a giveaway command and i would like to know how i can make my duration into an epoch timestamp so i can display my embed like this
code:
@bot.slash_command(guild_ids=[TESTING_GUILD_ID], description="Giveaway Command")
async def giveaway(interaction: nextcord.Interaction, channel: GuildChannel = SlashOption(channel_types=[ChannelType.text], required = True), prize: str = SlashOption(description="What will the prize of the giveaway be?"), time: str = SlashOption(description="How long will the giveaway last?", required=True),):
duration = humanfriendly.parse_timespan(time)
i have a different question but in slash commands you have to put a guild id is there a way i do not have to do that
like how do i make it all guilds that bot is in can use it
!d nextcord.utils.format_dt
(if you really want to do it manually you can use the datetime.datetime.timestamp() method to get the unix representation as a float)
nextcord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
what library are you using? you shouldnt be required to provide any guild id for your command
ik this is the wrong channel but uh can someone help me w this wouldn’t it jus be print(“Hello”) print(“World”)
@cold sonnet ur the best helper so i’m pinging you
you just need to not provide guild= in sync() and command() so it becomes a global command and syncs global commands
😳
o :/
just that?
ye but say one of my slash options is time: and i type 5m for 5 minutes, how can i make it so it generates an epoch timestamp for 5 minutes in the future?
also the synchronization should be done in setup_hook (or even better as a message command) since on_ready() can fire multiple times across the day
you have to use input()
so how would i be able to get this badge in a bot
sync slash commands globally
it tells you to use input() twice to save two words
so if i do this i get badge?
start with datetime.datetime.now(), add your timedelta to it, and then format it using the utility function
yes
aight
first_word = input()
o ok cool
this is how you do it once
a
how to do it twice
do I spoonfeed? I don't know what to do this is a bit too basic
nah it's in the rules homework has to be explained
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
bro please i’m sped 😭😭
do you know how to make a variable
what were you doing in class 😭
you make a variable like
a = something
but something has to be something
so something is now input()
he was playing clash of clans
but you have to make two variables so you have to make
a = input() and b = input()
gf
and then print the two
cuz when you do input() the program waits until you type something in the console
and saves it to a
fr
so at
a = input()
if you type Hello,
a will be Hello
so like
like print(a) prints what you first typed in
a = input(Hello) b = input(world)
no
then
I mean that also works
now you just need a space between the two you would do
print(a + " " + b)
or
print(a, " ", b)
it would be the same output I just don't know how strict that exam thing is
so you should have three lines of code now,
a = input()
b = input()
print(a + " " + b)
I managed to write a book about three lines of code
would i put Hello World in the “”
no
this is your whole code
you run this program, then you write
Hello
in the console, press Enter, write
World
then press Enter
and it prints Hello World
a = input()
b = input()
print(a + " " + b)
spoonfeed in the right channel bozo
does it have to type Enter a word:
bro I wrote a whole essay
I saw, I'm joking
😭

I hope not
probably yes
seff probably submitted already
@strange carbon I'm worried
your the best fr
tysm also nextcord.utils.format_dt(a, style=) could u tell me how to use the styles part as I have no clue
k but does the output have to be the exact same
the documentation has a table showing the different styles you can use
you just simply give it the character that corresponds with the style you want
this? o alrr
90% of bots are verified?
rip 90% of verified bots
tysm for your help
technically the exercise was done
idk what she wants but what you sent worked
that's great
no, real verified bots supports slash commands, i mean they had more than 6 months to adapt, the time was sufficient
how many bots are incredibly old and just left up on servers tho
btw discord will kill moderation bots
uhm why?
@commands.command()
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx, amount=11):
amount = amount+1
if amount > 101:
em = discord.Embed(color=discord.Colour.random(), description="I can not delete more than 100 messages")
await ctx.send(embed=em)
else:
await ctx.channel.purge(limit=amount)
em2 = discord.Embed(color=discord.Color.random(), description="Successfully cleared messages")
await ctx.send(embed=em2)``` **Why can everyone use this command I added `@commands.has_permissions(manage_messages=True)` to use command, but it doesn't work can someone help?**
None of my commands work at all, at least not the ones using @client.command(), but the others work?
"the others" are based on on_message and on_raw_reaction_add
Yes i have intents on
I also have access to message.attachments, so its not the message.content
tried to restart my bot now i get this message ?
Traceback (most recent call last):
File "main.py", line 189, in <module>
bot.run('mybottoken')
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 668, in run
return future.result()
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 647, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 611, in start
await self.connect(reconnect=reconnect)
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 552, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
doesn't need any privileged intents
but i dont need them.. none of my commands require any intents
why are you requesting them if you dont need them?
I wasnt, just saw my message from discord fixed it, it was message content
kek
Why? Its not really hard to compile a point on why to get the intent?
discord's ID are too big to be simple integer, you should take IDs as str and convert them in your function
yes.
?
discord is trying to address privacy concerns, i seriously doubt they're handing out unfettered access to message content to random bots for lame reasons
probably you're using a prefix commands, in this case you need message contents intent
any errors?
this whole channel is gonna be about prefix commands for a while i bet 
i seriously doubt they're handing out unfettered access to message content to random bots for lame reasons
guess you havent seen most verified bots?
That actually worked, cheers!
I would have never figured it out otherwise
Man i hate that the backspace and enter keys are so close together on this laptop
by "most verified bots" do you mean the biggest bots on discord?
?
more than 50% of all verified bots are getting message content intents
i'd like to see any evidence of that
Proving my point?
i can tell you right now i applied for them with a bot that has over 1k servers and it got denied, and it was for a decent reason
Dont you think maybe it was a problem of not proving a valid point?
If you gave good reasons i wouldnt doubt discord cares
the reasons dont even need to be good lmao
with slash commands and modals most verified Bots doesn't really need message content intent
Thats not really the point of the discussion but that was one of the points of the message content intent being privileged for verified bots as app commands are user friendly and much other reasons
Nah no prefix commands
Seen verified bots that use the intent while they break TOS with it so i wouldnt doubt it lol
have you got a line at the top of your code that is something like intents = discord.Intents something
send the intents definition of your code
already has been
It's been "none of my commands work no errors" and "intents is a required argument??? what does it mean" for the past few weeks
no doesnt need any intents but i fixed it now
how to wait for a message and then get the content of the message?
How do i set permissions again
@client.event
async def on_message(message):
Then just message.content
already scared when I see
"how do I make it so... "
try printing users
outside of the for loop of course
yeah you didn't get any users so it doesn't go into the for loop
wait
either there's just no row where id is user.id or
#databases message this could go wrong
I think it's not just asyncpg
yeah it's not, please read that message
Why is await client.close() not working, i have a print right before it and its printing so i know its being ran, but the client surly doth not close.
can someone tell me whats this problem
@cold sonnet bro u know anything about this?
nah I don't know about client.close
Kk
ok
will that read data from the file >
but line.strip() returns a list
so it would be lots of lists in a list
I don't quite get that logic
oh it's not split sorry
I just want the bot to read data from a text file, if the data is already present then it doesnt do the command. If it isnt present it does the command
switched them up
Is there a more nuclear option then await client.close() ? all i want to do is instantly kill the entire python script, i imagine there are many ways
the way you do this is
with open...:
users = []
for line in f:
users.append(...)
not to overcomplicate
then you can continue
what??
what
You should use something asynchronous like aiofiles and you can always use readlines()(a coroutine in aiofiles)?
yeah readlines would've made sense
@cold sonnet its not working the command still exectues even though the data is in the text file
I don't mean async wouldn't have
then the data is not exact
have you tried printing the outcome to see what you have?
now I'm wondering what elements you get when you iterate through a File
what?
like what the __iter__ dunder returns?
yes it does
quite accidentally there's no issue with that part then
f isnt defined making this statement incorrect
atleast from my side, Pxin probably had it all planned
I didn't write it out just put a placeholder cuz I'm on phone
Still causes issues
Yeah you just add that error to your error handler
Or just wrap that code in a try except block if you don’t want it to apply to all commands
embed = discord.Embed(
title=f"`{} BTC`".format(btc_to_usd(amount)),
description=f"Please send that amount to the following address `address goes here`\nOnce done send the transaction ID here",
color=0x2f3136
)
await mm_channel.send(embed=embed)
txid = await bot.wait_for('message', check=myCheck)
txid = txid.content
doesnt send embed
CogTicketsRecrutement.my_modal
why are you nesting classes either way?
hey look it's the friendly neighborhood grammar police 👀
Grammar is good to keep consistent in programming, say for an example everywhere in my code I write huose instead of house and I didn't realize until I spelt it right later. I'd have to change a bunch all the old occurrences (granted, you can replace all easy with editors)
its probably the french spelling of recruitment
oh nvm I was looking at the translated version instead of the french dictionary
Yea probably I didn't even realise the code was in french too
vars shall be English
python is inclusive 😄

is nexcord same as as dpy
\what
!e print("nextcord" == "dpy")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
there you have it

You probably have multiple instances of your bot running
hey @fresh iron please censor or don't include inappropriate words in screenshots here
????????
wtf are you on about mina
i only have one
it was the bot or webhook name
async def on_member_join(): not working, when a user joins nothing gets sent to my channel
fix?
Is there a way to add an @njit decorator to a discord.py bot command?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot 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
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
what is a njit decorator?
i think you can, but you won't really gain much speed because most of the code will come from discord.py which won't be compiled JIT
!e print("a" == "a")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e print("1" == "a")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
#bot-commands
Ratio
Is there any way I can host multiple bots but they all need to be able to access the same log txt file
Centralize file writing with something like API
But what for would you need one log for multiple bots
help, I'm trying to make my bot send a message after 5 seconds it detects a msg in the chat, but i get no response.
code :
from collections import UserString
import requests
import os
import discord
from discord.ext import commands
from discord.ext import tasks
from keep_alive import keep_alive
import asyncio
from bs4 import BeautifulSoup
import time
from time import sleep
import random
cid = int(input("Enter channel ID:\n"))
client = commands.Bot(command_prefix='.')
client._skip_check = lambda x, y: False
@client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
keep_alive()
client.run(os.getenv('tok'),bot=False)
client.run(os.getenv('tok'), reconnect=True)
@client.event
async def on_message(mes):
if mes.content.startswith('sdrop'):
channel = mes.channel
sleep(5)
await channel.send(mes.author,'Sdrop Karle!')
@client.event
async def on_message(mes):
if mes.content.startswith('sd'):
channel = mes.channel
sleep(5)
await channel.send(mes.author,'Sdrop Karle!')
cant you just use json lib to store info and just retrieve the required data via the file path
Json database cring
Write API in java btw 😉 you can use synchronized keyword for file writing function that's pretty useful
Except the file writing in java is aids unless you use 3rd party lib
help, please
is there an error message?
and your sure the message is detected right?
i mean personally i would try add a print("msg") so is can see if is actually the detection or the output which is broken
@client.event
async def on_message(mes):
if mes.content.startswith('sd'):
print("input detected")
channel = mes.channel
sleep(5)
await channel.send(mes.author,'Sdrop Karle!')
therefore you can see what is not working
lemme try
If.i host it on a website will it still be able to access the pathway ?
depends where the file is stored
On my pc
i think you would need to store the json file and the rest of the bot code on the website together i think
im not too sure
then no
How would I do it the
it isn't detecting
what could be the reason?
why do my commands get executed twice whenever i add @client.listen event
ok that means its probably not detecting the message try something like this
@client.event
async def on_message(mes):
if "sd" in mes.content:
sleep(5)
await message.channel.send(mes.author,'Sdrop Karle!')
also did you define mes as message?
You're probably calling bot.process_commands in it
yes i am ?
otherwise it woudln't work
What wouldn't work
nvm removed bot process and the same issue still happening
stil didn't detect
isn't it just a variable?
ok try like this then
@client.event
async def on_message(message):
if "sd" in message.content:
await message.channel.send('Sdrop Karle!')
how do i make the bot does a specific event when a certain word is used within a sentence
why does it keep doin that forever
This is a loop
how
It is looping
but why
even though it shouldn't
should i make a condition where it stops
Please explain your problem briefly
i see
first the bot is replying to your hello
all other replies are for its own Hellos
you should add if message.author == client.user: return to avoid it replying to its own messages
True
genius
i could've never figured its replying to itself
cause i didn't know bots do that
Bots identify every user if commanded.
It will of course reply to its own messages as the bot itself is identified as a user.
in reality that should be if message.author.bot: to not respond to any bots
if they want to avoid all the bots, true
They should avoid all bots
is this how you do it
why not put all those into a list?
i tried
both don't work anyway
it replys to any message
not only those
not even sure why does the event gets executed when its not true
message = "Hello world application, this is an example. Hello Tho."
mylist = ["Hello", "my", "friend", "application"]
if any(word in message for word in mylist):
print(message)
```https://stackoverflow.com/questions/3271478/check-list-of-words-in-another-string
uh lmao
just use sets?
Who needs sets when you can use lists!
the formation isn't the issue
i am wondering why does it reply to any message
even when that condition isn't true
sets have intersections lists dont
Send the full code block please @fresh iron
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
!e ```python
message = "Hello world application, this is an example. Hello Tho."
mylist = {"Hello", "my", "friend", "application"}
if mylist.intersection(set(message.split())):
print("yes")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
yes
oh
variable mylist is a set 🗿
How is this any better tho? Both achieve the same thing and stop once it hits one of the entries?
i just copied vars from this code
'twas a joke
what im trying here is to check if a specific word is within the message then do an action
no, using the iteration inside any is much slower that a set intersection, it's going through the items one by one, whereas the set intersection looks directly for similar elements
more like do an action to banned words
but anyway for small sizes of word lists the set approach will probably be slower.
You havent checked if author is bot either. Make sure the author is not a bot or else say goodbye to that channel and discordbot.
Well, until you're willing to share the full codeblock there's not much I can do.
How to learn to create good looking embeds? Have u got any guide guys?
just a online embed builder
help, i'm trying to make a simple on_message bot but it's not detecting the message.
code:
seems an intent problem
1min
@bot.event
async def on_message(message):
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
i enabled intents.message
entire code:```py
from collections import UserString
from multiprocessing.connection import Client
import requests
import os
import discord
from discord.ext import commands
from discord.ext import tasks
from kp_alv import keep_aliv
import asyncio
from bs4 import BeautifulSoup
import time
from time import sleep
import random
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix=',', intents=intents)
bot._skip_check = lambda x, y: False
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
def bot_start():
bot.run('token_here',reconnect=True)
@bot.event
async def on_message(message):
if message.content.startswith('$hello'):
await message.channel.send('Hello World!')
keep_aliv()
bot_start()
This from github?
just search discord embed builder online and you should find it
yeah i saw it but i cant do embed that i want there
you also need message_content intent
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is
recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not
possible, then consider disabling the privileged intents instead.
this error
Read the error
ah
you're requesting an intent that's not specifically enabled in the bot's page
enable it
Before you consider building a good looking embed, also consider what information will be on said embed
it still doesn't seems to be working, current code: ```py
from collections import UserString
from multiprocessing.connection import Client
import requests
import os
import discord
from discord.ext import commands
from discord.ext import tasks
from kp_alv import keep_aliv
import asyncio
from bs4 import BeautifulSoup
import time
from time import sleep
import random
intents = discord.Intents.default()
intents.messages=True
intents.message_content=True
bot = commands.Bot(command_prefix=',', intents=intents)
bot._skip_check = lambda x, y: False
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
token = 'token'
def bot_start():
bot.run(token,reconnect=True)
@bot.listen
async def on_message(message):
mes = message.content
if mes.startswith('hello'):
channel = message.channel
msg = 'Hello World'
await channel.send(msg)
keep_aliv()
bot_start()
Are you trying to do commands through the on_message event?
no, just a msg reply
any errors?
none
your Bot is unverified right?
yes
worked, i replaced the @bot.listen to @bot.event
oh true the parenthesis
thanks!
Consider moving to a cog format btw
cog?
So just have 1 file that loads everything and put all your commands into various different files
that you can easily pull out or add in whenever needed
o
السلام عليكم
how can i get this field with "Try my commands"? Or will it be usable later this year
this happened when i tried to run it in replit, any solutions?
looks like you aren't on discord.py 2.0
yeah, just realized, thanks
you can't, rn only verified bots have it and it's not customizable
thx
thx
class modercmd(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@app_commands.command()
async def test(self, interaction: discord.Interaction):
await interaction.response.send_message("Hello from command 1!", ephemeral=True)
@app_commands.command()
@app_commands.guilds(discord.Object(id=979105932355194900))
async def test1(self, interaction: discord.Interaction):
await interaction.response.send_message("Hello from private command!", ephemeral=True)
async def setup(bot: commands.Bot):
await bot.add_cog(modercmd(bot))
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
How to fix?
it doesn’t work
well it does work
but commands dont show
from menu
oh
now it works
are the rest still the same?
in 2.0
interaction no attribute author how to define author in interaction button
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
wait
2022-09-02T13:07:28.352913+00:00 app[worker.1]:
await load_extensions()2022-09-02T13:07:28.352924+00:00 app[worker.1]:
File "/app/main.py", line 557, in load_extensions2022-09-02T13:07:28.353270+00:00 app[worker.1]:
await bot.load_extension(f"commands.{file[:-3]}")
2022-09-02T13:07:28.353279+00:00 app[worker.1]:
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1012, in load_extension2022-09-02T13:07:28.353521+00:00
app[worker.1]: await self._load_from_module_spec(spec, name)2
022-09-02T13:07:28.353533+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 951, in _load_from_module_spec2022-09-02T13:07:28.353783+00:00 app[worker.1]: raise errors.ExtensionFailed(key, e) from e2022-09-02T13:07:28.353822+00:00 app[worker.1]: discord.ext.commands.errors.ExtensionFailed: Extension 'commands.test' raised an error: TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>2022-09-02T13:07:28.547977+00:00 heroku[worker.1]: Process exited with status 12022-09-02T13:07:28.765484+00:00 heroku[worker.1]: State changed from up to crashed
how do u do embeds now
how do you get a certain category in dpy?
if you don't have message content intents enabled you'll get None for the message.content
which would give that error
not all messages have content anyway, e.g. when someone sends an attachment
also docs says itll just be an empty string rather than None
well, what do you want your embed to look like when the message doesnt have any content?
e.g. using a placeholder message, or not including your content field
well that example doesnt describe what it should look like if the message didnt have any content
should it just be Before/After without any text?
aka a placeholder
oh true, but you can update from no content to some content
i know this is kind of an aside, but don't servers already have logs for all of that?
i dont think there's any event for audit logs so you cant receive them in real time
plus certain stuff isnt logged like messages deleted by their authors
the error you got indicates that the value is required, meaning you cant set the value to an empty string, so what do you want it to look like?
e.g. if you wanted to put in a zero-space placeholder you could write value or '\u200b'
it wont technically be empty since zero width spaces dont count, but to the user they would see nothing
'\u200b' could be any string like No content
if not len(message.after):
message.after = "whatever you want"```
or operator is king
oh weird, on_message() is not being triggered at all with this new message content intent thing
i thought it'd still work but only show the content if you're mentioned
even for unverified apps?
yeah, doing this on my test bot
are you sure? it fires just fine for me with empty content
idk if it's just disnake being weird
Logically incorrect
well now its never going to show the value
wot
but I think on_message() should work everytime, it has nothing to do with the new intent update unless you request for content
i suggested value or '\u200b' because it does work, in that if value is an empty string it defaults to '\u200b' instead
anyone know how to create a text channel inside a specified category?
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
ty
How can I make a simple slash command.
Everywhere I have looked or tried doesn't work
wtf happened with emojis
since the message content update it looks like my bots cant use get_emoji
Alias of emojis_and_stickers.
Changed in version 2.0: Changed to an alias.
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
reaction = await message.add_reaction(":tada:")
how can I get a list of every user (nextcord.Member) who reacted to reaction
tried enabling it and it didn't work
this is annoying af
if i dont change any intents then it gives me the error that im asking for intents that im not in the discord portal
if i disable messages intents then it works but on_message() is broken and fetching emojis is broken
Weird indeed
if i disable messages intents and enable emojis intents then emojis still don't work
am i doing something dumb i don't understand
any idea why i am getting an error Client object has no attribute _transport this happens prior to bot logging in
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
.
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
is there a way to set specific respones to a slash command option? like if i said
async def a(interaction: nextcord.Interaction, hi):
could i make it so it has like option of what to make hi?
ive seen it before but idk how to do it
you want options like this?
yeah
well, it's Literal typehint in discord.py, but not sure about nextcord
I think it should have something like Option
hmm
im on replit and how do i enter the login line
like on discord.js it's client.login(process.env.token)
I don't think it's the same
class nextcord.SlashOption(name=None, description=None, required=None, *, name_localizations=None, description_localizations=None, choices=None, choice_localizations=None, ...)```
Provides Discord with information about an option in a command.
When this class is set as the default argument of a parameter in an Application Command, additional information about the parameter is sent to Discord for the user to see.
someone?
wait no
What?
lol
?
client.run(os.environ["Name of environment"])
but i dont want my token to go in the code as there is this
it's python server btw
i know
edited
so do i also add at the top
at the top of th code import os
import os
yes
is that how to?
eee
hm I think nextcord also has Literal typehint implementation https://docs.nextcord.dev/en/stable/ext/commands/commands.html#typing-literal
@wanton pebble
what?
oh bruh
is that it?
yeah
thank you
yes, Literal is for prefix commands
Choices is an inbuilt disocrd thing so you will be using that here
🗿500ms
ty both for your help
Hey @fierce karma!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
can someone please help me
https://paste.pythondiscord.com/igufakibup
the error is really confusing
@wanton pebble
@silk fulcrum
type kill 1 in shell
and there is no need to ping someone
sorry
lol
still same error.
i got the code from https://discordpy.readthedocs.io/en/stable/intro.html.
import discord
import os
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run(os.environ["token"])
you are ratelimited, type kill 1 in shell
The error isn't confusing, it's just that error is on top, the rest of the thing is html page
i did but still same error
SEE i did
why
for using replit, check pins
Do you have an opportunity not to use replit
but the code is just
import discord
import os
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run(os.environ["token"])
why
how can i check to see if a bot is in the same voice channel as me? i currently have
if ctx.author.voice==self.bot.voice_channel
i will just stick to discord.js 
There are explanations in pins, shortly you should just use normal code editor/IDE
Ok.
Visual studio code is pretty fine
ctx.author.voice.channel == ctx.voice_client.channel
and make sure voice and voice_client properties don't return None here
thank you so much!!
Exception ignored in: <function Client.__del__ at 0x00000201A51243A0>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\httpx\_client.py", line 1139, in __del__
self.close()
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\httpx\_client.py", line 1111, in close
self._transport.close()
AttributeError: 'Client' object has no attribute '_transport'
httpx 🗿
discord uses it in its backend
so i get this error before i even initialise my bot its subclassed btw
any idea?
What are the reasons why slash commands may not appear?
- Not syncing / not syncing properly
- Global commands may take up to 1 hour to appear (not sure if that's still the case)
so like i'm EXTREMELY new to python and coding in general but like i wanna try doing stuff yk. so like idk why but i'm basically testing out stuff and this code is not working 🙄
i basically have this:
from discord.ext import commands
class HelloCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="hello", pass_context=True)
async def hello(self, ctx):
user = ctx.author
msg = await ctx.send(f"Hello, {user}!")
reaction = '👋'
await msg.add_reaction(reaction)```
in a file which is in a folder called `commands`
in my `main.py` file, i have this:
```py
# main.py
import discord
from discord.ext import commands
botIntents = discord.Intents.default()
botIntents.message_content = True
bot = commands.Bot(command_prefix = 'e!', intents = botIntents)
from commands.hello import HelloCog
# add the cog
bot.add_cog(HelloCog(bot))
### CONFIRM THE BOT IS ON IN CONSOLE
@bot.event
async def on_ready():
print('this is {0.user}'.format(bot))
bot.run('actual token')
but it keeps saying discord.ext.commands.errors.CommandNotFound: Command "hello" is not found like i'm so confused
but like please note idk how a lot works and my friend was helping me out w/ this. i just want a brief understand of how cogs work and how i can make separate files and have them all in my main.py file so like it's very clean yk
What is your discord.py version?
how do i check that 😍
In version 2+ you need to await add_cog which means you need to put it in an asynchronous function
probably 2.0 given that they have message_content, though it could be a fork of dpy as well
if it helps i ran this command like 10 mins ago
python3 -m pip install -U discord.py
The easiest way would be to define such a function and set bot.setup_hook to it
yeah most likely dpy 2.0 then
oh i see
Also, you don't need to import the cog this way
Usually you would use load_extension and define a setup function in the cog's file
That adds the cog
It should accept the bot instance as its only parameter
i've watched so many tutorials but like none of them helped me 😭
I think there are no up-to-date tutorials
sad D:
would it be like bot.load_extension('cogs.Hello')
yes
Then yes
lowercase h tho
Then lowercase the h there
oh ok
discord.py extensions are Python files with a setup function
Ideally, of it's an extension for a cog, its setup function should add the cog
How to make an item drop rate? Like for 45% one item, for 1% another, for 30% another?
why discord.Role.id doesnt work?
Youre extremely new to python but youre trying OOP?
yes 😭
If youre extremely new to python you shouldnt be practicing classes and using advanced libraries, you should learn the basics like functions and how they work
A good project would be making an HTTP request and parsing its payload within a function and making a REST API client with input
Show me the code
@client.command()
@commands.has_permissions(administrator = True)
async def notify(ctx, role = discord.Role, *, msg):
if role == role.id:
emb = discord.Embed(title = "Notification 📨", description = msg, color = 0xffffff)
emb.set_footer(text = f"By {ctx.author}")
await ctx.channel.purge(limit = 1)
await ctx.send(f"<@&{role_id}>", embed = emb)
Youre comparing the class discord.Role to discord.Role.id
no?
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
wait nvm, he set the default value of a class and not an annotation💀
Yea
My bad, never seen something as cursed as that
But yeah he should make it an annotation for the converter
really is
No purpose to do that when you have the great docs at your disposal
A rare skill most people havent mastered
It does depend on which docs youre viewing and your purpose
m
Its quite nice knowing how libraries work
I gotta figure out what is going wrong in my code somewhere around here
if ctx.message.attachments != None and ctx.message.attachments[0].content_type != "audio/mpeg" or "audio/ogg" or "video/mp4" or "video/quicktime":
at = ctx.message.attachments[0]
artist, title, album, songUrl, artistUrl, imageLink = call_AudD(at)
embed=discord.Embed(title=title, url=songUrl, description=f"{newline}**Album**{newline}{album}")
embed.set_author(name=f"Artist: {artist}", url=artistUrl)
embed.set_thumbnail(url=imageLink)
embed.set_footer(text="a")
await ctx.send(embed=embed)
i found it now
pro tip: dont use VSC fully zoomed in because you will miss whats on very long lines
You use the zoom feature in VSC!??!?
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
yea
Cursed
I like to have it on half my screen
yes
You can make the code better but why do you have a newline variable?
because f strings dont allow me to have backslashes
They do
how
!e
f = 1
print(f"a\n{f}")
@grim oar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a
002 | 1
you can use them just not in the expression
yea so btw i changed it to
ctx.message.attachments[0].content_type in acceptedFileTypes
because better
tell me why i shouldn't use it
reminds me of
#define newline "\n"
kek
I used to know how it works but I forgot😩
Im not using camelCase
im using mixedCase
menace
That's worse
mixedCaseisLikethis?
yea first letter is lowercase
CamelCase and camelCase both exist
mixedCaseisLike_this
how do you forget how comparing a class to an int.......
PEP8 refers to camel case as camelCase
mixedCase (differs from CapitalizedWords by initial lowercase character!)
pep-8 defines it as that
thats pascal case bozo
CamelCase lowerCamelCase
If pep-8 is god
CapitalizedWords
Descriptive: Naming Styles
There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.
The following naming styles are commonly distinguished:
b (single lowercase letter)
B (single uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CapWords, or CamelCase – so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps.
Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
mixedCase (differs from CapitalizedWords by initial lowercase character!)
where? here it refers to it as CamelCase https://peps.python.org/pep-0008/#naming-conventions:~:text=or CapWords%2C or-,CamelCase,-– so named because
Python Enhancement Proposals (PEPs)
To me, that doesnt say that mixedCase is explicitly wrong
BASICALLY THE SAME THING
idk but I knew how to, nvm I go search help in docs
sus
Nova did you see mudkip got owner
Where
but thats just an expression...
But why.
ToxicKids is why
We cant mute his ass no more this is disastrous
not that
That moment you waste api requests, time while troubleshooting and other peoples time, just to realize that the API you use doesnt support MOV files
im just getting random files from my meme folder
How to make an item drop rate? Like for 45% one item, for 1% another, for 30% another?
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
Im pretty sure other stdlibs use the cumventions
All the fun coding on the bot is done, now its just fixing bugs, adding error handling, etc
This will be "fun"
Hey atleast it has only taken me < 2 days to finish this part
Does anyone know how app commands and cogs work together? Or if there are any examples for them
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#slash-commands-within-a-cog
if you mean categories for slash commands, I don't think there are
Oh cool, thanks
theres so many examples im not even sure the examples in that gist would work
They don't need to, I just need a general idea on how you would structure it and I can go from there
I love coc(not clash of clans)
clash of code?
||🤌 ||
More fun than css thats for sure
god i hate css
tailwind
https://gvanrossum.github.io// what a lovely page
i love how guidos HTML skills are as bad as mine
😭
@silk fulcrum I don't understand, can you show an example?
You know what
Im just gonna ignore css
discord only requires the privacy policy to be somewhere
css is a pain
not that it looks good at all
choose_from_me = ('this is 48% chance', 'this one is 13%', 'and I am 39%')
result = random.choices(choose_from_me, (48, 13, 39))```
who uses single quotes
disgusting single quote man
double quotes > single quotes
always
nordic keyboard best keyboard
for python at least
alt gr + 7 for { isnt that great
1 sec
!d discord.ext.commands.Context.channel
Returns the channel associated with this context’s command. Shorthand for Message.channel.
They are interchangeable in python
i know
Sorry, an unexpected error occurred. Please let us know!
DiscordServerError: 500 Internal Server Error (error code: 0): 500: Internal Server Error
?!??
<@&831776746206265384> i think you guys should know...
Do you want to print it to the user?
Okay.. another issue:
@app_commands.context_menu(name="Run code")
async def eval_ctx_menu(self, interaction: Interaction, message: Message):
fake_ctx: Context = Context.from_interaction(interaction)
python_version = "3.11"
code = await CodeblockConverter.convert(fake_ctx, message.content)
await self.run_job("eval", fake_ctx, python_version, "\n".join(code))
The stuff inside doesn't matter. This is the problem:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/robin/Desktop/Dev/pydis-bot/.venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 995, in load_extension
await self._load_from_module_spec(spec, name)
File "/Users/robin/Desktop/Dev/pydis-bot/.venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 920, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'bot.exts.utils.snekbox' raised an error: TypeError: context menu callback 'Snekbox.eval_ctx_menu' requires 2 parameters, the first one being the interaction and the other one explicitly annotated with either discord.Message, discord.User, discord.Member, or a typing.Union of discord.Member and discord.User
I'm thinking that it doesn't expect self... but I need self? Any ideas?
seems like it was trigged with my command
What command did u run?
just !d
Thanks, but that's a 500 error we got from Discord's API, so not much we can do about it
ahhhh kek
Damm discord api
i thought it was something related to a server the python bot was serving but nvm😭
thats odd how an HTTP 500 came up
Message.channel can return a TextChannel so no need to reference the class
God knows
Well, I hope discord developers know
I was right. Context menus don't support cogs, so I'll have to do it another way
Ah
Is context menu a dpy 2.0 thingy?
Do you want me to write the full command for you or what?
so message.channel.id is the correct way
I can do it, just let me finish this csgo match lol
yes
Nono let them 😂
win at least
What is it
Its 4-4 wingman on lake, ill win for sure
Yea, it's just not having a good time right now.
Ha
Nah nah ill add comments to help him see what stuff does
Lmfao
i know the problem
Nono dont spoonfeed them, rather help them figure it out
Developer are drunk atm
@unkempt canyon has a disease that effects your skill in a task or topic, it is called a "skill issue"
Do we know which requests responds with 500
You can right click on a message or a user, then click on "Apps", then choose the thing you want to run. your bot will recieve that and do something special
Ohhhh
I'm working on letting users right click on a message, then run the code in that message using these context menus
That thing
Hopefully it'll get merged and yall will get to try it out soon