#discord-bots

1 messages · Page 72 of 1

dull terrace
#

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?

#

it would on it's face be faster to just render images every time but processing is more expensive than disk space

hushed galleon
#

maybe temporarily caching it in memory as bytes?

dull terrace
#

you know that didn't even occur to me

gentle crescent
#

None of my commands work

#

No errors appear though

sick birch
#

Do you have message content intents?

gentle crescent
#

Ive done discord.intents.all()

#

Worked for 1.7.3, but someone said it was different for 2.0

dull terrace
#

how would you store an object in a dataclass attribute

#

what's the uh annotation?

worn onyx
#

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?

dull terrace
worn onyx
dull terrace
#

show code

gentle crescent
slate swan
dull terrace
#

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)
silk fulcrum
dull terrace
worn onyx
# dull terrace embed is not defined before you try to send it

@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)

dull terrace
slate swan
worn onyx
slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
silk fulcrum
#

docs don't even contain it

#

it just exists

#

discord.utils.maybe_coroutine

slate swan
#

!d inspect.iscoroutine

unkempt canyonBOT
#

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.
worn onyx
#

@silk fulcrum

dull terrace
silk fulcrum
dull terrace
#

still have no idea what i'd put here in a dataclass

silk fulcrum
#

disnake.File?

slate swan
#

thats the full path of the class

dull terrace
slate swan
silk fulcrum
worn onyx
# silk fulcrum what

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

slate swan
dull knot
#

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 lemon_grimace

slate swan
dull knot
slate swan
#

show code

dull knot
#
    """         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()
dull terrace
#

okay so storing the disnake.file object did not work

slate swan
#

hi

dull terrace
#
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

swift pumice
#

!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

dull terrace
light jungle
#

Hello, is it possible in the discord modal (modal window) to make it possible for a person to attach a picture

dull terrace
slate swan
dull terrace
swift pumice
#

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?

swift pumice
swift pumice
#

Cause ur bot responds so fast mine legit takes like 3 secs to respond

swift pumice
dull terrace
swift pumice
#

yep

dull terrace
#

show your import line

swift pumice
#

why did you ping me for that

dull knot
# dull knot ```py """ Topic """ @commands.command(name="topic") ...

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

glad cradle
#

!pypi aiohttp

unkempt canyonBOT
shrewd apex
#

dpy needs better examples docs etc they need to get more descriptive

slate swan
#

🚶‍♂️asked you to do that 2 months ago

shrewd apex
#

yessir

slate swan
#

disnake >>> dpy

shrewd apex
#

well maybe next rewrite

dull knot
#

lol

glad cradle
dull knot
slate swan
#

the warning says exactly what you need to do

dull knot
#

So postpone the interaction and edit the msg?

slate swan
#

indeed

glad cradle
slate swan
#

it extends the time to respond to the interaction from 3 seconds to 15 minutes

glad cradle
#

deferring an interaction you'll see NameBot is thinking...

glad cradle
dull knot
#

Noted. WIll try figuring out the rest. Thanks guys! I'll ask for more if I get stuck or smth lol

glad cradle
#

kk

high tapir
#

how to create good looking embeds in discord?

glad cradle
glad cradle
slate swan
#
  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 ?
glad cradle
#

?

#

send you're code

slate swan
#

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

worn onyx
slate swan
cold sonnet
#

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

slate swan
#

@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'```
cold sonnet
#

self.bot.tdict
is not how you define a variable

#

set it to something like self.bot.tdict = {} in your __init__ function

hollow ice
cold sonnet
#

don't need to install from git anymore

#

pip install discord.py is enough now

hollow ice
#

Take chill bot

hollow ice
#

Oh, can help me? "How to join vc but didn't work?"

slate swan
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

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").
cold sonnet
#

that doesn't seem like v2....

hollow ice
#

Oh

quaint epoch
#

!d discord.VoiceClient

unkempt canyonBOT
#

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.
quaint epoch
#

make a command that makes a bot join a VC and play the blue lobster jump scare at 200 DB

ionic garden
#

should i only use slash commands now? or should i include implementations for both a normal prefixed command + slash command?

light jungle
#

is it possible to make a bot that will be similar in functionality to getting hypescuad in discord?

finite falcon
#

how to fix

silk fulcrum
finite falcon
#

oh mb i thought it didnt send

silk fulcrum
#

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."

finite falcon
#

the code stopped working on py 2.0

silk fulcrum
#

do pip show discord.py

silk fulcrum
finite falcon
#

i upg my py and the code stopped working so my new py is the probelm

ionic edge
#
ttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'```
silk fulcrum
#

btw how do you upgrade py to 2.0

#

maybe dpy?

#

because python's latest is 3.10

silk fulcrum
#

I know webdriver from selenium

#

but i don't think that is it

ionic edge
#

it is that

silk fulcrum
#

@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?

finite falcon
#

tell me how to please ik what im doing

#

i can always upg after lol

silk fulcrum
finite falcon
#

ty code works now

finite falcon
silk fulcrum
#

venvs

drifting arrow
#

Whats the max character limit for a discord modal paragraph (long)?

drifting arrow
torn sail
#

it can be reduced

drifting arrow
#

I got mine to set to 1k

torn sail
#

👍

#

i keep mine at 4k cause im too lazy to test what would be best for users

swift pumice
#

dont its annoying lol i did it once

high tapir
#
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?

full lily
high tapir
#

wow

#

thanks brother

full lily
#

does it work

high tapir
#

lemme check

#

No it doesnt

high tapir
#

but also doesnt work

#

This one worked thanks for help anyway @full lily

full lily
#

cool

slate swan
#

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)
outer parcel
#

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

hushed galleon
unkempt canyonBOT
#

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...
hushed galleon
strange carbon
#

ik this is the wrong channel but uh can someone help me w this wouldn’t it jus be print(“Hello”) print(“World”)

outer parcel
#

all my libraries

#

but i do this

strange carbon
hushed galleon
# outer parcel but i do this

you just need to not provide guild= in sync() and command() so it becomes a global command and syncs global commands

cold sonnet
#

😳

slate swan
hushed galleon
#

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

outer parcel
#

so how would i be able to get this badge in a bot

glad cradle
cold sonnet
#

it tells you to use input() twice to save two words

hushed galleon
glad cradle
cold sonnet
#

first_word = input()

outer parcel
cold sonnet
#

this is how you do it once

strange carbon
#

a

strange carbon
cold sonnet
#

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

unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

strange carbon
cold sonnet
#

do you know how to make a variable

strange carbon
#

no

cold sonnet
#

what were you doing in class 😭

#

you make a variable like
a = something

#

but something has to be something

#

so something is now input()

glad cradle
#

he was playing clash of clans

cold sonnet
#

but you have to make two variables so you have to make
a = input() and b = input()

strange carbon
cold sonnet
#

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

strange carbon
#

fr

cold sonnet
#

so at
a = input()
if you type Hello,
a will be Hello

strange carbon
cold sonnet
#

like print(a) prints what you first typed in

strange carbon
#

a = input(Hello) b = input(world)

cold sonnet
#

no

strange carbon
#

then

cold sonnet
#

nothing in the brackets

#

and also you have to start a new line after () in this case

strange carbon
#

print(a,b)

#

so how would i do it

cold sonnet
#

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

strange carbon
#

would i put Hello World in the “”

cold sonnet
#

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

strange carbon
#
a = input() 
b = input() 
print(a + " " + b) 
cold sonnet
#

yes

#

no wait I see the sample

glad cradle
cold sonnet
#

does it have to type Enter a word:

cold sonnet
glad cradle
cold sonnet
#

😭

glad cradle
cold sonnet
#

probably yes

#

seff probably submitted already

#

@strange carbon I'm worried

glad cradle
#

he will get a bad grade for your fault

#

😈

cold sonnet
#

what a bozo

#

there's even a run code option tf

#

infinite tests

strange carbon
slate swan
cold sonnet
#

k but does the output have to be the exact same

hushed galleon
#

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

slate swan
#

this? o alrr

dull terrace
#

rip 90% of bots

cold sonnet
#

90% of bots are verified?

dull terrace
#

rip 90% of verified bots

cold sonnet
#

rip

#

I hope it works out for seff

cold sonnet
#

technically the exercise was done

strange carbon
cold sonnet
#

that's great

glad cradle
dull terrace
#

how many bots are incredibly old and just left up on servers tho

glad cradle
#

btw discord will kill moderation bots

slate swan
#

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?**
gentle crescent
#

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

steep cape
#

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

gentle crescent
#

Well yes you do

#

Go and enable them

steep cape
#

but i dont need them.. none of my commands require any intents

primal token
#

why are you requesting them if you dont need them?

steep cape
primal token
#

kek

primal token
glad cradle
# slate swan uhm why?

discord's ID are too big to be simple integer, you should take IDs as str and convert them in your function

primal token
#

?

dull terrace
#

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

glad cradle
gentle crescent
#

Speaking of prefix commands...

#

None of my prefix commands work at all

glad cradle
#

any errors?

dull terrace
dull terrace
#

this whole channel is gonna be about prefix commands for a while i bet doge_kek

primal token
gentle crescent
#

I would have never figured it out otherwise

#

Man i hate that the backspace and enter keys are so close together on this laptop

dull terrace
primal token
#

?

gentle crescent
#

I think he means most of the verified bots

#

More than 50% of them per definition

dull terrace
#

more than 50% of all verified bots are getting message content intents

#

i'd like to see any evidence of that

dull terrace
#

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

primal token
#

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

glad cradle
#

with slash commands and modals most verified Bots doesn't really need message content intent

primal token
#

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

primal token
dull terrace
glad cradle
sick birch
#

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

steep cape
slate swan
#

how to wait for a message and then get the content of the message?

scarlet sorrel
#

How do i set permissions again

scarlet sorrel
#

Then just message.content

cold sonnet
#

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

#

I think it's not just asyncpg

#

yeah it's not, please read that message

scarlet sorrel
#

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.

onyx cipher
#

can someone tell me whats this problem

cold sonnet
#

users is None

#

how did you define it

onyx cipher
#

oh damn

scarlet sorrel
cold sonnet
#

nah I don't know about client.close

scarlet sorrel
#

Kk

cold sonnet
#

just use users.append(line.strip())

onyx cipher
#

ok

onyx cipher
cold sonnet
#

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

onyx cipher
#

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

cold sonnet
scarlet sorrel
#

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

cold sonnet
# onyx cipher

the way you do this is

with open...:
    users = [] 
    for line in f:
        users.append(...)
#

not to overcomplicate

#

then you can continue

cold sonnet
#

what

primal token
#

You should use something asynchronous like aiofiles and you can always use readlines()(a coroutine in aiofiles)?

cold sonnet
#

yeah readlines would've made sense

onyx cipher
#

@cold sonnet its not working the command still exectues even though the data is in the text file

cold sonnet
#

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

primal token
#

what?

cold sonnet
#

iterating through a File

#

do you get the lines?

primal token
#

like what the __iter__ dunder returns?

cold sonnet
#

think you get it

#

yes

primal token
cold sonnet
#

quite accidentally there's no issue with that part then

primal token
cold sonnet
#

atleast from my side, Pxin probably had it all planned

cold sonnet
primal token
#

Still causes issues

cold sonnet
#

ok

#

excuse me what

#

what do you mean by that?

pallid meadow
#

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

winged coral
#

Spacebar

slate swan
#
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

pliant gulch
#

CogTicketsRecrutement.my_modal

primal token
#

why are you nesting classes either way?

pliant gulch
#

By the way you spelt recruitment wrong

#

Missing an I

sick birch
#

hey look it's the friendly neighborhood grammar police 👀

pliant gulch
#

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)

hushed galleon
#

its probably the french spelling of recruitment

pliant gulch
#

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

cold sonnet
#

vars shall be English

sick birch
#

python is inclusive 😄

patent lark
fresh iron
#

is nexcord same as as dpy

rugged shadow
#

\what

sick birch
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
sick birch
#

there you have it

patent lark
sick birch
#

You probably have multiple instances of your bot running

daring olive
#

hey @fresh iron please censor or don't include inappropriate words in screenshots here

fresh iron
#

wtf are you on about mina

fresh iron
daring olive
#

it was the bot or webhook name

fresh iron
#

oh the liberals thing

#

ok no worries

slate swan
#

async def on_member_join(): not working, when a user joins nothing gets sent to my channel

#

fix?

dapper shell
#

Is there a way to add an @njit decorator to a discord.py bot command?

unkempt canyonBOT
#

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.

slate swan
dapper shell
#

Numba

#

It is a jit compilator To speed up python

slate swan
#

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

slate swan
#

!e print("a" == "a")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
slate swan
#

!e print("1" == "a")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

False
hazy oxide
#

#bot-commands

dapper shell
#

Ratio

onyx cipher
#

Is there any way I can host multiple bots but they all need to be able to access the same log txt file

vale wing
#

But what for would you need one log for multiple bots

slate swan
#

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!')
ashen perch
vale wing
#

Json database cring

vale wing
#

Except the file writing in java is aids unless you use 3rd party lib

ashen perch
slate swan
#

no

#

there's no error but, it doesn't work the way i intended it to

ashen perch
#

and your sure the message is detected right?

slate swan
#

i gave the bot permissions to read the channel and send too

#

am i missing something?

ashen perch
#

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

slate swan
#

lemme try

onyx cipher
ashen perch
#

depends where the file is stored

onyx cipher
#

On my pc

ashen perch
#

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

glad cradle
onyx cipher
#

How would I do it the

slate swan
#

what could be the reason?

fresh iron
#

why do my commands get executed twice whenever i add @client.listen event

ashen perch
#

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?

vocal snow
fresh iron
#

otherwise it woudln't work

vocal snow
#

What wouldn't work

fresh iron
#

nvm removed bot process and the same issue still happening

slate swan
slate swan
ashen perch
#

ok try like this then

@client.event
async def on_message(message):
if "sd" in message.content:
    await message.channel.send('Sdrop Karle!')
fresh iron
#

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

tardy karma
fresh iron
tardy karma
#

It is looping

fresh iron
#

but why

tardy karma
#

even though it shouldn't

fresh iron
#

should i make a condition where it stops

tardy karma
#

Please explain your problem briefly

fresh iron
#

idk

#

thats the code

#

and that's the problem

tardy karma
#

i see

slate swan
#

you should add if message.author == client.user: return to avoid it replying to its own messages

tardy karma
#

True

fresh iron
#

genius

#

i could've never figured its replying to itself

#

cause i didn't know bots do that

tardy karma
#

Bots identify every user if commanded.

#

It will of course reply to its own messages as the bot itself is identified as a user.

night crater
slate swan
night crater
#

They should avoid all bots

outer parcel
#

How can i add a dropdown menu in my slash command

#

im using discord app commands

drifting arrow
fresh iron
#

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

drifting arrow
# fresh iron i tried
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
slate swan
#

uh lmao

drifting arrow
#

it works doesnt it?

slate swan
#

just use sets?

drifting arrow
#

Who needs sets when you can use lists!

fresh iron
#

the formation isn't the issue

#

i am wondering why does it reply to any message

#

even when that condition isn't true

slate swan
drifting arrow
#

Send the full code block please @fresh iron

hollow osprey
unkempt canyonBOT
#

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.")
slate swan
#

!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")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

yes
fresh iron
#

oh

hollow osprey
#

variable mylist is a set 🗿

drifting arrow
slate swan
hollow osprey
#

'twas a joke

fresh iron
slate swan
fresh iron
#

more like do an action to banned words

hollow osprey
#

but anyway for small sizes of word lists the set approach will probably be slower.

drifting arrow
drifting arrow
#

why not just do if message.author.bot: return?

fresh iron
#

does it matter

#

that's literally not my issue here

drifting arrow
high tapir
#

How to learn to create good looking embeds? Have u got any guide guys?

slate swan
#

help, i'm trying to make a simple on_message bot but it's not detecting the message.

#

code:

glad cradle
#

seems an intent problem

slate swan
#

1min

#
@bot.event
async def on_message(message):
        if message.content.startswith('$hello'):
            await message.channel.send('Hello World!')
slate swan
#

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()

high tapir
slate swan
high tapir
glad cradle
#

!d discord.Intents.message_content

unkempt canyonBOT
#

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...

slate swan
# glad cradle you also need message_content intent
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

glad cradle
#

Read the error

slate swan
#

ah

glad cradle
#

you're requesting an intent that's not specifically enabled in the bot's page

#

enable it

drifting arrow
#

Before you consider building a good looking embed, also consider what information will be on said embed

slate swan
#

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()

drifting arrow
slate swan
#

no, just a msg reply

slate swan
glad cradle
#

your Bot is unverified right?

slate swan
#

yes

glad cradle
#

try to use a debugger

#

wait what message are you writing

slate swan
#

worked, i replaced the @bot.listen to @bot.event

glad cradle
#

oh true the parenthesis

slate swan
#

thanks!

drifting arrow
slate swan
drifting arrow
#

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

slate swan
#

o

gleaming fulcrum
#

السلام عليكم

mossy jacinth
#

how can i get this field with "Try my commands"? Or will it be usable later this year

slate swan
vocal snow
slate swan
#

yeah, just realized, thanks

glad cradle
sly fog
#

how do u do slash commands

#

i heard u can now

vocal snow
sly fog
#

thx

sly fog
#

thx

proud apex
#
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?

sly fog
#

well it does work

#

but commands dont show

#

from menu

#

oh

#

now it works

#

are the rest still the same?

#

in 2.0

slate swan
#

interaction no attribute author how to define author in interaction button

unkempt canyonBOT
#

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.

proud apex
#

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
junior verge
#

same way?

#

embeds did not change

slate swan
#

how do you get a certain category in dpy?

dull terrace
#

if you don't have message content intents enabled you'll get None for the message.content

#

which would give that error

hushed galleon
#

not all messages have content anyway, e.g. when someone sends an attachment

dull terrace
#

that's a good point

#

also if the message is an embed

hushed galleon
#

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

dull terrace
#

i know this is kind of an aside, but don't servers already have logs for all of that?

hushed galleon
#

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

silk fulcrum
#

hey! im back

#

i mean my internet is back 🗿

dull terrace
#
if not len(message.after):
   message.after = "whatever you want"```
hushed galleon
#

or operator is king

dull terrace
#

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

dull terrace
hushed galleon
dull terrace
#

idk if it's just disnake being weird

hushed galleon
#

well now its never going to show the value

dull terrace
honest shoal
hushed galleon
winged coral
#

^ This is the best solution I think

#

Message if not empty else ZWSP

wanton pebble
#

anyone know how to create a text channel inside a specified category?

sick birch
unkempt canyonBOT
#

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.
wanton pebble
#

ty

hushed coral
#

How can I make a simple slash command.
Everywhere I have looked or tried doesn't work

dull terrace
#

wtf happened with emojis

#

since the message content update it looks like my bots cant use get_emoji

vale wing
#

Iirc there's a separate intent for emojis

#

!d discord.Intents.emojis

unkempt canyonBOT
primal token
lethal moat
#

reaction = await message.add_reaction(":tada:")
how can I get a list of every user (nextcord.Member) who reacted to reaction

dull terrace
#

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

vale wing
#

Weird indeed

dull terrace
#

if i disable messages intents and enable emojis intents then emojis still don't work

#

am i doing something dumb i don't understand

shrewd apex
#

any idea why i am getting an error Client object has no attribute _transport this happens prior to bot logging in

unkempt canyonBOT
#

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.

unkempt canyonBOT
primal token
#

!d discord.Reaction.users

unkempt canyonBOT
#

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...
wanton pebble
#

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

wanton pebble
#

yeah

silk fulcrum
#

well, it's Literal typehint in discord.py, but not sure about nextcord

#

I think it should have something like Option

wanton pebble
#

hmm

silk fulcrum
#

nope

#

!d nextcord.SlashOption @wanton pebble

fierce karma
#

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

unkempt canyonBOT
#
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.
silk fulcrum
#

wait no

fierce karma
#

What?

wanton pebble
#

lol

fierce karma
#

?

wanton pebble
fierce karma
fierce karma
#

i know

fierce karma
#

so do i also add at the top

wanton pebble
#

at the top of th code import os

fierce karma
#

import os

wanton pebble
#

yes

fierce karma
#

ok.

#

thanks

wanton pebble
silk fulcrum
#

i can't find it

wanton pebble
#

eee

silk fulcrum
#

@wanton pebble

wanton pebble
#

ill look at it; thank you

#

@silk fulcrum i just found smth else too

silk fulcrum
#

what?

silk fulcrum
#

oh bruh

wanton pebble
#

is that it?

silk fulcrum
#

yeah

wanton pebble
#

thank you

slate swan
#

yes, Literal is for prefix commands
Choices is an inbuilt disocrd thing so you will be using that here

#

🗿500ms

wanton pebble
#

ty both for your help

unkempt canyonBOT
#

Hey @fierce karma!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

fierce karma
#

the error is really confusing

#

@wanton pebble

#

@silk fulcrum

silk fulcrum
#

and there is no need to ping someone

fierce karma
#

sorry

wanton pebble
#

lol

fierce karma
slate swan
vale wing
fierce karma
#

SEE i did

slate swan
#

then you are blocked by the API, there's nothing you can do now

#

except for waiting

fierce karma
#

why

slate swan
#

for using replit, check pins

vale wing
fierce karma
#

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"])
fierce karma
austere vale
#

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

fierce karma
#

i will just stick to discord.js Pepe_ThumbsUp_Weirdo

vale wing
# fierce karma why

There are explanations in pins, shortly you should just use normal code editor/IDE

vale wing
#

Visual studio code is pretty fine

slate swan
austere vale
#

thank you so much!!

shrewd apex
#
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'
silk fulcrum
#

httpx 🗿

shrewd apex
#

discord uses it in its backend

#

so i get this error before i even initialise my bot its subclassed btw

#

any idea?

whole sparrow
#

What are the reasons why slash commands may not appear?

sick birch
brazen raft
#

before.channel.mention

#

👍

slate swan
#

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

brazen raft
#

What is your discord.py version?

slate swan
#

how do i check that 😍

brazen raft
#

In version 2+ you need to await add_cog which means you need to put it in an asynchronous function

hushed galleon
#

probably 2.0 given that they have message_content, though it could be a fork of dpy as well

slate swan
#

if it helps i ran this command like 10 mins ago

python3 -m pip install -U discord.py

brazen raft
#

The easiest way would be to define such a function and set bot.setup_hook to it

hushed galleon
#

yeah most likely dpy 2.0 then

slate swan
#

oh i see

brazen raft
#

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

slate swan
#

i've watched so many tutorials but like none of them helped me 😭

brazen raft
#

I think there are no up-to-date tutorials

slate swan
#

sad D:

slate swan
brazen raft
#

It needs to be awaited

#

Is the file name Hello.py

slate swan
#

yes

brazen raft
#

Then yes

slate swan
#

lowercase h tho

brazen raft
#

Then lowercase the h there

slate swan
#

oh ok

brazen raft
#

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

toxic thicket
#

How to make an item drop rate? Like for 45% one item, for 1% another, for 30% another?

summer flume
#

why discord.Role.id doesnt work?

primal token
primal token
#

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

gentle crescent
#

Alright

#

Here we go again

#

actually nvm thank god i did error handling

gentle crescent
summer flume
# gentle crescent 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)
gentle crescent
primal token
#

no?

gentle crescent
#

Yes?

#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
primal token
#

wait nvm, he set the default value of a class and not an annotation💀

gentle crescent
#

Yea

primal token
#

My bad, never seen something as cursed as that

#

But yeah he should make it an annotation for the converter

gentle crescent
#

man when you actually understand the docs

#

its so much easier

primal token
#

Its lovely isnt it?

#

Its even better when you can read src

gentle crescent
gentle crescent
primal token
primal token
gentle crescent
#

m

primal token
#

Its quite nice knowing how libraries work

gentle crescent
#

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

primal token
#

You use the zoom feature in VSC!??!?

grim oar
#

!or-gotcha

unkempt canyonBOT
#

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.")
gentle crescent
#

yea

primal token
#

Cursed

gentle crescent
#

I like to have it on half my screen

gentle crescent
primal token
#

You can make the code better but why do you have a newline variable?

gentle crescent
#

because f strings dont allow me to have backslashes

grim oar
#

They do

gentle crescent
#

how

grim oar
#

!e

f = 1
print(f"a\n{f}")
unkempt canyonBOT
#

@grim oar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a
002 | 1
primal token
#

you can use them just not in the expression

gentle crescent
#

hmmm

#

ill add it to the massive list of things to fix

gentle crescent
#

because better

primal token
#

you shouldnt use camelCase either btw

#

bro

gentle crescent
#

tell me why i shouldn't use it

primal token
#

Python doesnt use it in any name convention

#

!pep 8

unkempt canyonBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

grim oar
#

cause pep 8

#

Well it does, in logging module lul

primal token
summer flume
gentle crescent
#

im using mixedCase

primal token
#

menace

grim oar
#

That's worse

silk fulcrum
#

mixedCaseisLikethis?

gentle crescent
#

yea first letter is lowercase

pliant gulch
#

CamelCase and camelCase both exist

grim oar
#

mixedCaseisLike_this

primal token
pliant gulch
#

PEP8 refers to camel case as camelCase

gentle crescent
#

pep-8 defines it as that

grim oar
silk fulcrum
gentle crescent
#

If pep-8 is god

silk fulcrum
#

who knows it's like wtf

#

UpperCamelCase what is this then?

gentle crescent
#

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!)

gentle crescent
#

To me, that doesnt say that mixedCase is explicitly wrong

pliant gulch
summer flume
grim oar
#

sus

pliant gulch
#

Nova did you see mudkip got owner

grim oar
#

Where

primal token
pliant gulch
#

💀

grim oar
#

But why.

pliant gulch
#

ToxicKids is why

grim oar
#

We cant mute his ass no more this is disastrous

summer flume
gentle crescent
#

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

primal token
#

coc?

#

i love coc(clash of clans)

gentle crescent
#

im just getting random files from my meme folder

toxic thicket
#

How to make an item drop rate? Like for 45% one item, for 1% another, for 30% another?

unkempt canyonBOT
#

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.
silk fulcrum
#

weights arg

#

cumulative

primal token
#

Im pretty sure other stdlibs use the cumventions

gentle crescent
#

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

sick birch
#

Does anyone know how app commands and cogs work together? Or if there are any examples for them

sick birch
#

Oh cool, thanks

primal token
#

theres so many examples im not even sure the examples in that gist would work

sick birch
#

They don't need to, I just need a general idea on how you would structure it and I can go from there

torn sail
primal token
#

clash of code?

torn sail
#

I love coc

#

With a k

primal token
gentle crescent
#

god i hate css

silk fulcrum
#

tailwind

gentle crescent
#

hmmm

#

Ill pass

#

I've done webdesign before, ill do it again

primal token
#

i love how guidos HTML skills are as bad as mine

silk fulcrum
#

Who I Am

#

How To Reach Me

primal token
#

😭

toxic thicket
gentle crescent
#

Im just gonna ignore css

#

discord only requires the privacy policy to be somewhere

primal token
#

css is a pain

gentle crescent
#

not that it looks good at all

silk fulcrum
primal token
#

who uses single quotes

gentle crescent
#

disgusting single quote man

primal token
#

double quotes > single quotes

gentle crescent
#

always

#

nordic keyboard best keyboard

#

for python at least

#

alt gr + 7 for { isnt that great

#

1 sec

primal token
#

!d discord.ext.commands.Context.channel

unkempt canyonBOT
lone lichen
primal token
#

i know

unkempt canyonBOT
#

Sorry, an unexpected error occurred. Please let us know!

DiscordServerError: 500 Internal Server Error (error code: 0): 500: Internal Server Error

primal token
#

?!??

lone lichen
#

Lmao

#

Is this out of nowhere?

primal token
gentle crescent
#

Do you want to print it to the user?

sick birch
#

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?

primal token
lone lichen
primal token
vocal magnet
primal token
#

ahhhh kek

lone lichen
#

Damm discord api

primal token
#

thats odd how an HTTP 500 came up

gentle crescent
primal token
lone lichen
primal token
#

😭

lone lichen
#

Well, I hope discord developers know

sick birch
lone lichen
#

Is context menu a dpy 2.0 thingy?

gentle crescent
#

Do you want me to write the full command for you or what?

primal token
gentle crescent
#

I can do it, just let me finish this csgo match lol

sick birch
lone lichen
primal token
lone lichen
gentle crescent
vocal magnet
lone lichen
#

Ha

gentle crescent
primal token
lone lichen
lone lichen
primal token
lone lichen
#

Do we know which requests responds with 500

sick birch
# lone lichen What is it

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

sick birch
#

I'm working on letting users right click on a message, then run the code in that message using these context menus

lone lichen
#

That thing

sick birch
#

Hopefully it'll get merged and yall will get to try it out soon