#discord-bots

1 messages Β· Page 170 of 1

pulsar kettle
#

Tempmute command mutes the person but doesn't unmute them after the timer is over, can anyone help?

@bot.tree.command(name='tempmute', description='Temporarily mutes a member')
@has_permissions(kick_members=True)
async def tempmute(interaction: discord.Interaction, member: discord.Member, time: str, reason: str=None):
    desctime = time
    guild = interaction.guild
    mutedRole = discord.utils.get(guild.roles, name="Muted")
    time_convert = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
    tempmute= int(time[:-1]) * time_convert[time[-1]]
    if not mutedRole:
        mutedRole = await guild.create_role(name="Muted")
        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
    await member.add_roles(mutedRole, reason=reason)
    embed = discord.Embed(title=(f'***{member} has been muted for {desctime}*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)
    await member.send(f"You have been temporarily muted from: ***{guild.name}*** for **{desctime}** | {reason}")
    await asyncio.sleep(tempmute)
    if mutedRole in member.roles:
        await member.send(f"You have been unmuted from: ***{guild.name}***")
        await member.remove_roles(mutedRole)
slate swan
#

Try printing tempmute and check that it is indeed the expected value.
Also, muting members by adding a Muted role is outdated, the built-in time-out feature is much more reliable and easy to use now.

sick birch
#

The entire command could be shortened into 1 line :P

pulsar kettle
#

Forgot Discord had a time out feature, I'll look into it, thanks!

sick birch
unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
pulsar kettle
#

thank you <3

flint bolt
#

im looking to add a description to my discord bot that rolls a dice after it rolls, so it sends the embed first and then changes the text afterwards. can I do that somehow?

#
@tree.command(name='dice', description='Roll a metaphorical dice!')
async def dice(interaction: discord.Interaction, start:str=None, end:str=None):
    dice_embed=discord.Embed(title=f'Rolling the dice...', description=None, color=discord.Colour.og_blurple())
    dice_embed.set_footer(text=str(datetime.datetime.now))
    await interaction.response.send_message(embed=dice_embed)
    await asyncio.sleep(1)
    dice_embed.set_description(text=random.randint({start}, {end}))
#

and also id like to add a gif of a dice roll to the embed. how do i do that?

slate swan
#

!d discord.Embed.set_image /set_thumbmail depending upon where you want to add the gif

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
flint bolt
#

what about changing the description after the embed is sent

shrewd fjord
#

I think after adding the desc u need to send the embed again or edit the msg

flint bolt
#

alright

slate swan
flint bolt
#

and wait how do i copy the image url

#

is it copy address?

shrewd fjord
shrewd fjord
#

Copy image address

flint bolt
#

wait but what do i replace the star with

#

dude the docs are so confusing omg

pulsar kettle
#

Hiya, trying to add timeout slash command but I get this error when I run the bot ```TypeError: SelectOption.init() got an unexpected keyword argument 'require'

```python
@bot.tree.command(name = 'timeout', description = "mutes/timeouts a member")
@has_permissions(moderate_members = True)
async def timeout(ctx, member: SelectOption(discord.Member, required = True), reason: SelectOption(str, required = False), days: SelectOption(int, max_value = 27, default = 0, required = False), hours: SelectOption(int, default = 0, required = False), minutes: SelectOption(int, default = 0, required = False), seconds: SelectOption(int, default = 0, required = False)):
    if member.id == ctx.author.id:
        await ctx.respond("You can't timeout yourself!")
        return
    if member.guild_permissions.moderate_members:
        await ctx.respond("You can't do this, this person is a moderator!")
        return
    duration = timedelta(days = days, hours = hours, minutes = minutes, seconds = seconds)
    if duration >= timedelta(days = 28):
        await ctx.respond("I can't mute someone for more than 28 days!", ephemeral = True)
        return
    if reason == None:
        await member.timeout_for(duration)
        await ctx.respond(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{ctx.author.id}>.")
    else:
        await member.timeout_for(duration, reason = reason)
        await ctx.respond(f"<@{member.id}> has been timed out for {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds by <@{ctx.author.id}> for '{reason}'.")```
flint bolt
#

hmm

#

you can definitely make it in a simpler way

pulsar kettle
#

I figured haha

naive briar
#

I can't read any of those

slate swan
flint bolt
#

you can do something like this

#
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
#

where you define the reason as None

#

before sending it

#

but yeah otherwise i can't read almost anything from that code

sick birch
slate swan
#

why would they call it Argument and not Option

sick birch
#

Probably more inline with how it's called in programming, I suppose

slate swan
#

i mean they call the prefix command arguments as param πŸ’€ lmao

#

!d discord.ext.commands.param

unkempt canyonBOT
#

discord.ext.commands.param(*, converter, default, description, displayed_default)```
param(*, converter=…, default=…, description=…, displayed\_default=…)

An alias for [`parameter()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.parameter "discord.ext.commands.parameter").

New in version 2.0.
slate swan
#

the class name is Parameter or Param I don't remember

sick birch
#

chicken param

#

🀀

slate swan
#

!d discord.app_commands.Argument

unkempt canyonBOT
slate swan
#

!d discord.app_commands.Parameter

unkempt canyonBOT
#

class discord.app_commands.Parameter```
A class that contains the parameter information of a [`Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command") callback.

New in version 2.0.
slate swan
#

πŸ’€ make me cry

#

guess the second one is read only

torn flame
#

import discord

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('MY TOKEN')
Why is this not working?

sick birch
loud junco
#

this means that my database url is not connected to my bot correctly right?

sick birch
#

postgres URL has the password in the URL if memory serves?

loud junco
#

lemme show it here jkjk

#

aight its working

pulsar kettle
#

Trying to code a user profile command, works correctly when inputting a member, but when I leave the member blank it returns the error Command 'uinfo' raised an exception: AttributeError: 'NoneType' object has no attribute 'author' instead of sending the user info of the author. Please help <3

@bot.tree.command(name='uinfo', description ='Provides information on a member')
async def uinfo(interaction: discord.Interaction, member: discord.Member=None):
    if member == None:
        member = interaction.message.author
    roles = [role for role in member.roles]
    embed = discord.Embed(title="User info", description=f"Here's some information on the user {member.mention}", color = discord.Color.green(), timestamp = interaction.created_at)
    embed.set_thumbnail(url=member.avatar)
    embed.add_field(name="User ID", value = member.id, inline=False)
    embed.add_field(name='Name', value = f'{member.name}#{member.discriminator}', inline=False)
    embed.add_field(name='Nickname', value = member.display_name, inline=False)
    embed.add_field(name='Discord Member Since', value = member.created_at.strftime('%a, %B %#d, %Y, %I:%M %p '), inline=False)
    embed.add_field(name='Server Member Since', value = member.joined_at.strftime('%a, %B %#d, %Y, %I:%M %p '), inline=False)
    embed.add_field(name=f'Roles ({len(roles)})', value = "".join([role.mention for role in roles]), inline=False)
    await interaction.response.send_message(embed=embed)
naive briar
#

What does interaction.message supposed to mean

sick birch
naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
pulsar kettle
sick birch
pulsar kettle
loud junco
#

do you guys have any suggestion on how to define bot here

#

this is what i plan to do

naive briar
#

Function argument

#

Or in bot subclass, cog subclass, ...

loud junco
#

what is function argument

#

the thing inside () ?

torn flame
sick birch
loud junco
torn flame
loud junco
#

erm delete it ur token is there

sick birch
naive briar
#

Read the error maybe

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

sick birch
#

You will see a special little link pop up when you paste it here

#

Also the error tells you exactly what the error is and exactly how to solve it

torn flame
#

Traceback (most recent call last):
File "D:\Prgrammieren\Eigene versuche\Discord Bot\bot.py", line 16, in <module>
client.run('bot token')
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Lennox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 672, 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.

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.

loud junco
#

wondering if this thing is looking healthy

sick birch
#

I wonder what happens if I press it?

loud junco
#

πŸ’€

torn flame
#

it opens my applications idk what i have to do here

#

i startet programming a week ago

sick birch
loud junco
#

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.

sick birch
#

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.

#

Quite interesting, isn't it?

torn flame
loud junco
#

πŸ’€

sick birch
#

Explicitly enable the privleged intents within your applicatoin's page

torn flame
#

yeah but hoe am i doning that?

sick birch
#

That is, go to your "Bot" tab and enable the 3 intents

loud junco
#

its called DatabaseFunc.fetchvalue(blah, blah, blah) right?

torn flame
#

Thank You SO much it woked πŸ™‚ ❀️

sick birch
#

Thank the error πŸ˜„

loud junco
#

btw where do i add this link

vale wing
loud junco
vale wing
#

Slash commands

#

If your bot has them must turn on

loud junco
#

bruh what is this

#

can i just put a rickroll link

vale wing
#

Ah yes that's trash

loud junco
#

i dont have a website just for TeRmS AnD CoNdItIoN

vale wing
#

Put it on github

loud junco
#

huh

#

README?

vale wing
#

No just create separate .md files or whatever

sick birch
#

Technically you're not supposed to make a Terms of Service with a lawyer but ...

vale wing
sick birch
#

(Disclaimer: I am not a lawyer, don't take legal advise from random nerds online)

vale wing
#

Random nerds like me

sick birch
#

or me

loud junco
#

LOL

#

hipidi hopedi yours tos are now my properti

vale wing
#

Those docs passed verification tho so I think there shouldn't be problems

loud junco
#

alright dont mind if i do

#

no one is going to read that junk tho

sick birch
#

Technically they're supposed to

vale wing
#

Ouch edgy internet causes emotional damage

#

@loud junco actually you would better edit definitions and stuff about data usage

loud junco
#

and the email KEKW

#

wtf is going on with your ToS

#

its too complicated for a 16 yo kiddo like me

loud junco
#

and why are you mentioning european country

vale wing
#

I didn't write the rest of those tos yk

loud junco
#

lol

vale wing
#

But I read everything with very close attention and cut out everything that would become an issue in certain cases

#

Like there was "if user paid for something and got damage, they receive as much as they paid, if they didn't pay for anything but still got damaged (idk how the heck), they receive 200$"

vale wing
#

There was "Russian Federation" because it's official country name

vale wing
#

Malaysia is just Malaysia I think?

loud junco
#

yaya

torn flame
#

Hey i need your help again:)i have a list with the name red numbers and i want to ask if my varible number is in there and if it is won schould be true how can i do that?

loud junco
loud junco
torn flame
#

thanks and i have one more question: i want to filter if a message was witten by a user or by a bot how can i do that?

loud junco
#

filling up the vertification thing is just πŸ’€

#

i just want to make a bot that let people have fun

#

can someone explain to me what these 3 thing does

slate swan
#

So message intents allows you to edit delete ect messages

#

Server member intent allows you interact and mess with servers

#

It's best turn them all on

loud junco
#

but the reason to apply for them

loud junco
#

im doing the vertification thing

#

and how tf am i suppose to answer this question?

#

i dont give my password to strangers that call me for password

vale wing
#

"I have firewall set up and I do code scanning to detect possible vulnerabilities, all data sensitive commands are limited to developer-only"

vale wing
unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
vale wing
loud junco
#

i mean i could need them in the future

#

so its best if i can apply for all of them now

vale wing
#

You can apply for them in the future

#

You can't apply for what you don't need and can't explain

icy meadow
#

How can I change only 1 permission from a channel without changing the rest?

vale wing
#

Fetch overwrites first then set the permission and update with new overwrites

random obsidian
#

yo guys
how can i make an slash command what make an channel with predefined permissions?

bright wedge
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.

The `overwrites` parameter can be used to create a β€˜secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
bright wedge
#

@random obsidian

loud junco
#

what else do i write πŸ’€

bright wedge
#

this is off topic πŸ˜›

loud junco
#

nah nah its discord bot KEKW

#

this is part of the discord bot dev

bright wedge
loud junco
#

the hardest part πŸ₯Ή

loud junco
bright wedge
loud junco
light violet
#

how do i generate a time stamp ahead of current time by 60 secs

loud junco
#

show your code

#

wish me luck πŸ’€

#

which tutorial are u following lmao

#

!d discord

#

!source

unkempt canyonBOT
loud junco
#

wait no

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

loud junco
#

alright i cant find it

upbeat gust
#

Stop following tutorials, use the official documentation and examples

quick gust
#

Follow a good tutorial

slate swan
#

Look at the error, you haven't defined intents in your client constructor.

upbeat gust
naive briar
unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
naive briar
#

Add 60 seconds to it

upbeat gust
loud junco
upbeat gust
#

what are you on about

quick gust
# upbeat gust No tutorials are good

Why's that so? They can be good if they incentivize people to look for some stuff in their own and explain what the code they're writing does, instead of just writing them and expecting the viewer to copy

quick gust
upbeat gust
vale wing
#

Tutorial is entrypoint, everything further is trial and error, community help and docs

upbeat gust
#

Yeah sure, for like basically everything, except dpy, simply because all the tutorials are so bad

vale wing
#

Regulars from here are just tired of putting ones who picked wrong entrypoint onto the right path

upbeat gust
#

As am I

vale wing
#

If you are tired of something, automate it py_guido

loud junco
#

me who literally started with freecodecamp and still doesnt know what is ctx.send after 1 year of bot dev

#

imagine one day chat gpt can write code

upbeat gust
loud junco
#

like

naive briar
#

It can also be wrong

loud junco
#

it can write any code without mistake

upbeat gust
loud junco
#

LOL

naive briar
#

Like when I asked it about NumPy brainmon

upbeat gust
#

Asked for a website,it stopped after the head tag

vale wing
#

Surprisingly they responded to my latest verification request in just 30 minutes and bot got verified after me providing some more data they requested

#

Oh heck stupid edgy internet

slate swan
#

Using an AI to write code to do a task instead of doing that task yourself is just mega-brain BigBrain

vale wing
#

ChatGPT is bad at coding bots as heck, probably watched all those youtube tutorials for training πŸ˜‚

quick gust
#

I can see the requirement for programmers declining in the next ten years

loud junco
#

LOL

upbeat gust
#

Can't really predict things that far into the future anymore

loud junco
#

any shit could happen anytime

vale wing
#

Ask chatgpt if it will replace programmers

loud junco
#

YES I WILL

upbeat gust
vale wing
#

Yes like bobux bot release

#

Was coding usage stats commands and data collection stuff whole yesterday

quick gust
loud junco
#

🀣

vale wing
#

Now people can have bobux

quick gust
#

The fuck

vale wing
#

In other terms life is pointless

loud junco
#

what is bobux

vale wing
#

Robux but πŸ…±οΈobux

#

You can't even imagine who we got on developers team

quick gust
#

Yeah shouldn't have searched for this

slate swan
vale wing
quick gust
#

πŸ—Ώ

upbeat gust
quick gust
#

I think I'll send it in dms this tutorial is too tarded to send here

loud junco
#

lol

vale wing
#

Without coding they mean like human will be responding to them like a bot?

random obsidian
upbeat gust
buoyant quail
#

I wonder how much useless commands are there, i don't believe in 500 good commands

vale wing
#

If those are slash commands that's beyond discord limit

vale wing
#

!e ```py
ph = """@commands.command(name="{name}", description="Send letter {name} in chat")
async def {name}(ctx: commands.Context) -> None:
await ctx.send("{name}")

"""
print("from discord.ext import commands\n")
for n in "abcd":
print(ph.format(name=n))```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | from discord.ext import commands
002 | 
003 | @commands.command(name=a, description="Send letter a in chat")
004 | async def a(ctx: commands.Context) -> None:
005 |     await ctx.send("a")
006 | 
007 | 
008 | @commands.command(name=b, description="Send letter b in chat")
009 | async def b(ctx: commands.Context) -> None:
010 |     await ctx.send("b")
011 | 
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/ukeyatimiq.txt?noredirect

vale wing
#

Guys I am chat gpt

shrewd fjord
#

Lol

buoyant quail
shrewd fjord
#

πŸ’€

buoyant quail
buoyant quail
#

also profile, it has like 10 fields and for each field it has separate set and delete command

slate swan
rare echo
#

welp

lucid jolt
rare echo
#

a quick google search for discord py alias should tell ya

lucid jolt
#

oh thanks

flint bolt
#

hey, im looking to add a ping slash command to my discord bot but it keep showing an error. can anyone help?

@tree.command(name = "ping", description = "Shows latency of bot")
async def ping(interaction: discord.Interaction, latency:str={client.latency * 1000}):
    ping_embed=discord.Embed(title={latency}, color=discord.Colour.og_blurple())
    await interaction.response.send_message(embed=ping_embed)
upbeat otter
#

you have to calculate the latency inside the command and not ask the user for it

flint bolt
#

ohh

upbeat otter
#

if the user inputs the latency of the bot, how's that real and gonna be true

flint bolt
#

so i calculate it in the title?

#

yep alright i think i got it

upbeat otter
#

yeah cool

flint bolt
#

uhhh

upbeat otter
# flint bolt

you might want to typecast it to an integer or round it off

flint bolt
#

i want to round it

night crater
#

you're wrapping it in a {} fyi

upbeat otter
flint bolt
#

yeah got it

#

i'm a bit dumb, i thought its a string lol

upbeat otter
#

it's alright, we all have those days

flint bolt
#

wait, if i want to have text before it, how can i do that?

upbeat otter
flint bolt
#

alright i forgot

#

dumb today idk what it is

upbeat otter
#

no comments if you forgot that
hope you have a good day

flint bolt
#

yeah, got it to work, thanks

slate swan
#

Aye, my code works, but I want it to only print the keys found in the found list, not all keys with the value "weak"

    async def hadith(self, ctx, *, message):
        if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
            found = ' '.join([str(elem) for elem in narrators.keys()])
            await ctx.send("This is unreliable because of:\n"
                           + found')```
#

here my json
{"aban": "weak", "aban b. abi ayyash": "weak", "abi ayyash": "weak", "aban ibn abi ayyash": "weak", "\u0623\u0628\u0627\u0646 \u0628\u0646 \u0623\u0628\u064a \u0639\u064a\u0627\u0634": "weak", "\u0628\u064a \u0639\u064a\u0627\u0634": "weak"}

#

when i do !hadith aban, it gives me all keys with the value, weak

#

and also, my JSON cant read arabic text

#

it works with english words, but when I input an arabic word, it doesnt

oblique sorrel
#

In my bot config on the dev portal the checkbox to make my bot not private keeps checking itself back on. I don't want my bot to be able to join other servers. Just my own.

rare echo
slate swan
#

or not share the bot?

#

@rare echo You do know that you can easily get authorize links

#

The syntax is easy d.c/oauth2/authorize?client_id=ID&scope=bot&permissions=8

rare echo
slate swan
#

good

#

but like you can't really "not share it"

#

if people see a bot that they think is private they are incentivised to try and invite it

rare echo
#

hence the on_join leave

slate swan
#

true

rare echo
#

you are really blowing up a small suggestion lmao

oblique sorrel
#

Yes u can just click the "add this bot to server" link

#

I want that not to be able

slate swan
#

or the actual link?

rare echo
#

thats why i said on guild join : leave, since idk about the website issue

#

though on guild join is a jank quickfix kinda way of doing it

slate swan
#

you can turn off "Public Bot" from the dashboard to make it invitable only by you. πŸ€·β€β™‚οΈ

rare echo
slate swan
#

ic

rare echo
#

which ive never seen Β―_(ツ)_/Β―

lucid jolt
slate swan
#

Hey! Can somebody help me to do ticket system in python?

#

Or something like @novel apex

#

Aye, when I do !test aban, it sends me the message, but when i do something with spaces, like !test abi ayyash, I get nothing

        found_keys = [weak for weak in message.split() if weak in narrators.keys()]
        nars = ', '.join(found_keys)
        await ctx.send("This is unreliable because of:\n"
                           ++ nars)```
#

{"aban": "weak", "aban b. abi ayyash": "weak", "abi ayyash": "weak"}

vocal snow
#

because "abi" and "ayyash" aren't keys

#

you're splitting the message and checking if each word is in the dict

slate swan
vocal snow
#

then it would check for each character

#

just check if message is in the dict

#

what are you trying to do exactly

slate swan
vocal snow
#

so for "abi ayyash" what output is expected?

slate swan
vocal snow
#

what about the "aban b. abi ayyash" key

#

it also contains abi ayyash

slate swan
#

it shouldnt read it then, thats a problem i faced

#

if i wrote "aban b. abi ayyash" it would send me aban and abi ayyash

#

although its supposed to be its own key

vocal snow
#

ok so you just want to find exact matches right

slate swan
#

yep

vocal snow
#

so just check if message is in the dict

#

why do you need list comp

slate swan
#

so if i did like, !command abi ayyash text text, it would check if the text text is also a key

vocal snow
#

yes

#

why do you have text text there

slate swan
#

i need to check large blocks of text if they contain the specific word

quick gust
#

maybe you could use .find()

slate swan
#

yeah but what would i put as the value? if i put narrators.keys(), it would check if all the keys in the dictionary are in the message

#

i need it to loop over each key, checking if they are in the message

vocal snow
#

yes

#

how many keywords do you have

slate swan
#

right now, around 5, but its going to be in the hundreds

#

i tried something along the lines of this, but it doesnt work

#
        weak = "weak"
        keys = narrators.keys()
        found = narrators.find(keys)
        if found in ctx.message.content:
            await ctx.send("e")```
naive briar
#

ctx.message.content is the whole content of the message that triggers the command

#

Why would you add a message argument if you never gonna use it

slate swan
#

yeah, i deleted that, but heres the thing, im trying to make it so

if a key with a specific value is found in the message, it should send the message

#

im facing two errors:

  1. it doesnt work if the key has spaces,
  2. if i have a key like "aban b. abi ayyash" which contains another key, it will tell me theres two keys in the entire message, aban and abi ayyash
slate swan
#

can someone help me with my bot when i do the command it sends a embeded message but it is suppose to get edited after and it dosent

cedar snow
#

a key should be one word

slate swan
cedar snow
slate swan
#

Yep

cedar snow
#

your keys should just be one word...

slate swan
#

I have a better idea

#

I could make it so I force the message to remove all spaces

#

and have all spaces removed from the keys too

cedar snow
#

that's just bypassing the issue

#

you're currently facing an xy problem

#

what's the main goal of your whole command? try to be as specific as possible

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
cedar snow
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

If it does, send keys present in text with value β€œweak”

cedar snow
slate swan
slate swan
cedar snow
tough echo
#

does anyone know if its possible to make this menu pop-up using a button in an embed ?

cedar snow
cedar snow
upbeat otter
#
for key, value in dict.items():
  ...

😳

upbeat otter
#

my bad

shrewd apex
cedar snow
cedar snow
slate swan
cedar snow
upbeat otter
tough echo
#

I dont think its possible

upbeat otter
cedar snow
#

I mean "more readable", but yeah, it's just A way of doing it

cedar snow
cedar snow
#

because you SHOULD get errors, since ctx.respond doesn't exist

#

also, get_round_data is an async function for no reason
(unless you want to io open your files like you do with all the rest (?)
also time.sleep is blocking, you should asyncio.sleep, .... .... ...

boreal berry
#

does anone know why this doesnt work?

#

it says that if is an unexpected intent

quick gust
tough echo
upbeat otter
tough echo
#

line 13,14

#

remove one set of tab from those lines

boreal berry
cedar snow
tough echo
boreal berry
tough echo
#

ok send ss

upbeat otter
cedar snow
cedar snow
boreal berry
upbeat otter
cedar snow
upbeat otter
#

no

#

py-cord is uwu

cedar snow
tough echo
slate swan
boreal berry
quick gust
cedar snow
boreal berry
#

still says this though

cedar snow
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

cedar snow
#

read this ^

#

if you're following a YT tutorial, please don't, they're outdated regularly

#

or, if you just want to get the bot working, type F and I'll give you the lines to edit to make at least your first command "working"

boreal berry
#

ok thanks

#

i just want to have a bit of fun and make a command work

slate swan
#

so im confused

cedar snow
#

lastly, you should go to the discord dev portal, and enable the "message content" intent (the link the bot already shared)

cedar snow
boreal berry
#

thank you πŸ™‚

tough echo
#

its sub-concious ig

cedar snow
#

the sad truth

tough echo
#

seems scary to beginners lol

cedar snow
#

right? I guess most beginners get frustrated and want to get at least SOMETHING working before putting in decent effort (like reading 5 sentences)

slate swan
cedar snow
#

or better yet, what Exception was raised πŸ™‚

cedar snow
#

your error traceback is like 20 lines of "code", shouldn't be that hard to guess what the actual error msg is

slate swan
#

idk ive been looking and i cant find what th eproblem is

shrewd apex
#

just send the error here

#

copy paste it

shrewd apex
#

and the file dosent exists

cedar snow
#

spoiler

prisma girder
#

i literally cant find the problem

#

i have it enabled and everything

shrewd apex
#

am i out of touch with discord bot community now πŸ˜”

shrewd apex
slate swan
#

someone help me pls

slate swan
#

also enabled in dev portal

#

if so then make sure you have the correct bot token

slate swan
# slate swan

file does not exist. tells u right there, you have the directory wrong

prisma girder
slate swan
#

you have the path wrong

#

wdym??

prisma girder
cedar snow
slate swan
#

^

cedar snow
#

Intents

slate swan
prisma girder
#

fixed

#

thanks

bright wedge
unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
prisma girder
#

it works thank you guys

slate swan
#

wait what do i do \im confused

quick gust
#

it literally tells u what to do in plain english

slate swan
#

ik

quick gust
#

consider using ok.edit_original_response

slate swan
#

but when i try to do it it dosent work

slate swan
quick gust
#

explain doesnt work

quick gust
slate swan
#

ohh

quick gust
#

try reading the error?

slate swan
#

ima go try it

rare echo
#

great question

#

if only there was something i could help with

cedar snow
#

bad luck

rare echo
slate swan
#

omg now it says this again

quick gust
#

show your file tree

rare echo
cedar snow
quick gust
#

πŸ—Ώ

slate swan
quick gust
#

used to it at this point

slate swan
rare echo
quick gust
rare echo
cedar snow
#

have you read the error?

cedar snow
shrewd apex
#

from where u copied the code @slate swan ?

rare echo
#

it doesnt have perms

quick gust
#

need a !read-error tag at this point

slate swan
rare echo
#

or the role isnt high enough

cedar snow
rare echo
#

show code

slate swan
quick gust
#
  1. make sure the bot role is at the top
  2. make sure it has admin
    and then come back with your new error if any
rare echo
#

if you are sure its not a perm / hierarchy error then show code

cedar snow
slate swan
rare echo
#

what in the world

slate swan
#

If I had a key with value strong, and this key was in the message, but also a kry with value weak, it should ignore the strong

craggy sleet
#

hello, is there anyway to show people which button they have selected? (this is for role selects)

cedar snow
quick gust
#

dont be shy tell us where u copied that from

rare echo
#

weirdest code structure ive ever seen in my life lmao

cedar snow
craggy sleet
#

not a big deal

rare echo
quick gust
#

uh

#

nvm havent touched dpy in a while

rare echo
#

we need a #I-used-chatGPT-and-dont-know-what-todo

quick gust
#

bro πŸ’€

shrewd apex
#

πŸ—Ώ

cedar snow
craggy sleet
#

rn theyre all gray, so making it blue

cedar snow
shrewd apex
cedar snow
#

unless the role selection is an ephemeral message on itself

slate swan
shrewd apex
#

its a select add a callback

#

bro no perms give ur bot admin

cedar snow
shrewd apex
#

and makw sure u are not trying to kick the owner

#

or people with same perms and higher role level

rare echo
#

@shrewd apex ooc did you see the hastebin?

craggy sleet
shrewd apex
slate swan
cedar snow
craggy sleet
#

ah okay

shrewd apex
#

role select is different

craggy sleet
shrewd apex
#

bro be clear

craggy sleet
#

didnt know role select itself was a thing

quick gust
#

is asher and ash the same person

rare echo
#

and ducks?

slate swan
quick gust
#

@slate swan send ur code again

shrewd apex
# craggy sleet didnt know role select itself was a thing

there is a much easier way to do this u set role id in custom id of button then in callback
put all buttons in an array for loop add callback and add to view

async def callback(inter):
     role_id = int(inter.data["custom_id"])
     # add roles

add callback to button

#

no need to subclass button lol

slate swan
quick gust
#

and also send ur file tree

slate swan
#

lol ok

shrewd apex
unkempt canyonBOT
#

class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.

Please note that if you use this in a private message with a user, no roles will be displayed to the user.

New in version 2.1.
shrewd apex
unkempt canyonBOT
#

Hey @slate swan!

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

potent light
#

Is there a way to initialize a value in a slash command argument? like:
/test role_id: 41534654648968

slate swan
#

@quick gust

potent light
quick gust
quick gust
potent light
quick gust
#

i really suggest u write stuff u know how worls

quick gust
shell wing
#

I want to make a msg leader board...i need DB for that ? and what all

potent light
shell wing
potent light
shell wing
#

hmm so basically a func to put msg data in a DB and a func to fetch that data and put it in an embed and an auto reset every 30d....

rare echo
#

potentially something to modify values

shell wing
#

gonna be hell of a ride

#

first time working with db

potent light
rare echo
shell wing
rare echo
#

still should use a counter over the actual messages

potent light
rare echo
#

makes more sense

shell wing
#

small server

shell wing
potent light
rare echo
shell wing
cold sonnet
#

450 people message daily?

shell wing
#

thats the best fking case scenario

cold sonnet
#

dat a lot

shell wing
#

acc to stats 22k msgs weekly

rustic edge
#

Hello!

How can I check if a button is pressed in a Discord UI View using / commands?

rustic edge
#

I have this UI view shop menu

#

ANd I have buttons at the bottom of it.

#

I want to run something specific on the press of one of the buttons.

#

For example, I have two buttons, A and B. When A is pressed I want to execute the function foo() and when B is pressed I want to execute the function bar()

#

And all I want to know is how to detect the button press.

cold sonnet
#

button callbacks

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The callback associated with this UI item.

This can be overridden by subclasses.
slate swan
#

^ perfect

rustic edge
#

ty

#

❀️

cold sonnet
#

you override this and it's called when it's pressed

slate swan
#

For example if button is called btn you would do

#
    await inter.response.send_message("hi")

btn.callback = callback_btn```
idle radish
#

what is the right way to let only a specific role do a command

fading marlin
#

depends on the type of command

#

I mean, you'd still use a check, but the namespace differs

idle radish
#

client.command

fading marlin
#

!d discord.ext.commands.has_any_role or has_role depending on what you need

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
frail notch
#

how can i make a basic dropdown on a message

oblique fern
#

Could I get someone to test some multiplayer game commands on my discord bot? ping or message me thanks.

sick birch
cloud dawn
sick birch
#

!d unittest

unkempt canyonBOT
#

Source code: Lib/unittest/__init__.py

(If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.)

The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

To achieve this, unittest supports some important concepts in an object-oriented way:

oblique fern
# sick birch This is the job of unittesting / integration testing :)

hmm, I was responding to this agreeing that while tests for code are great and serve a wonderful purpose there as some aspects that are just impractical for some situations. but I got to thinking a bit and I can see how it would be possible to write a test for this. not saying it sounds fun though...

#

I could try to simulate some fake inputs and have it get straight to the function I need but this is such a small project and I add so many "complicated-to-test" things every day it just seems a bit impractical to write a test for everything yet.

#

idk, i'll bite the bullet eventually.

frail notch
#

Why does this code not work? ```py
async def callback(self, interaction: discord.Interaction):
# await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
await interaction.response.send_message(f'Creating a ticket for {self.label}', ephemeral=True)

#

{self.label}

fading marlin
#

looks good to me

frail notch
#

self.label should show the label that the user clicked right?

fading marlin
#

no

frail notch
#

Oh.. how would I do that?

fading marlin
#

you can get that from interaction.data or self.values[0]

frail notch
#

oh alright

slate swan
#

interaction.data['values'][0]

frail notch
#

and how can i create a channel in a specific category depending on the choice made?

fading marlin
#

!d discord.CategoryChannel.create_text_channel

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.
fading marlin
#

or pass in a category kwarg to Guild.create_channel

frail notch
#
        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label='General Support', description='Support ticket regarding ingame information or general information about the server.', emoji=':closed_lock_with_key:'),
            discord.SelectOption(label='Report Staff / Department', description='Seen a member of staff or from a department abusing perms or breaking rules? Report it here!', emoji=':lock:'),
            # discord.SelectOption(label='Store Issues', description='Your favourite colour is blue', emoji=':blue_square:'),
        ]

        # The placeholder is what will be shown when no option is chosen
        # The min and max values indicate we can only pick one of the three options
        # The options parameter defines the dropdown options. We defined this above
        super().__init__(placeholder='Click here to see all...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        # await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
        await interaction.response.send_message(f'Creating a ticket for {self.values[0]}', ephemeral=True)
#

Because there is a different category for each option

vale wing
#

Screw callbacks we use GenericView

#

That's such a good custom class

#

Don't mind me

frail notch
#

lol

cerulean lichen
#

Hi I need some help to figure out how to move my bot from AWS EC2 to lambda, has anyone tried it before ?
I just can't figure out how the bot will be active 24/7 if the lambda is only active when there requests

sick birch
#

I don't think AWS Lambda is built for discord bots

cerulean lichen
#

I want to terminate the EC2, to lower the costs

#

Also have telegram one I will move

sick birch
#

I run my bots and sites on EC2
Lambda is not built for this sort of thing

#

You can try out Lightsail if you want cheaper prices

cerulean lichen
#

I only run like couple bots on "free" instance and I end up with 5-10$ every month

#

It's not much but when added up its something I'd like to lower as much as possible

cloud dawn
sick birch
#

The lowest option is only $3/month

cloud dawn
#

Just get a good host

#

run minecraft server and a website on the side

cerulean lichen
cerulean lichen
cerulean ibex
#

What's the best YT tut for the latest discord.py ?
what do you guys recommend ?

cerulean ibex
sick birch
#

I like to stare at documentation with a bucket of popcorn 🍿

cloud dawn
#

It's very long page so you can use middle mouse button to scroll very slowly to relax in chair.

shrewd apex
#

read in dark mode

sick birch
#

Truly a pinnacle of the 21st century entertainment industry

cerulean ibex
cloud dawn
#

It pains me to say this, but if you want a good tutorial on slash command, use discord.js -> https://discordjs.guide much friendlier (except the syntax).

vale wing
#

noOooOOo

cloud dawn
#

Not my fault their guide is more clearer and better, just don't ask questions in their Discord server, they'll skin you alive.

fading marlin
#

you could probably join the dpy server too, you'll find a lot of useful resources there too

exotic maple
#

how do i add options for arguments in a slash command?

I want there to be the options for all the ids im storing that is linked to the guild the command is executed

#

i would very appreciate some help

fading marlin
#

an autocomplete is probably your best choice here

exotic maple
fading marlin
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
fading marlin
#

!d discord.app_commands.Command.autocomplete

unkempt canyonBOT
#

@autocomplete(name)```
A decorator that registers a coroutine as an autocomplete prompt for a parameter.

The coroutine callback must have 2 parameters, the [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"), and the current value by the user (the string currently being typed by the user).

To get the values from other parameters that may be filled in, accessing [`Interaction.namespace`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.namespace "discord.Interaction.namespace") will give a [`Namespace`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Namespace "discord.app_commands.Namespace") object with those values.

Parent [`checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are ignored within an autocomplete. However, checks can be added to the autocomplete callback and the ones added will be called. If the checks fail for any reason then an empty list is sent as the interaction response.

The coroutine decorator **must** return a list of [`Choice`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Choice "discord.app_commands.Choice") objects. Only up to 25 objects are supported.
unkempt canyonBOT
#

Hey @burnt gull!

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

burnt gull
#

why

lyric sphinx
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

burnt gull
#

ok

#

@lyric sphinx ok

lyric sphinx
#

i guess the problem is here

#

try doing it without the aliases

#

also you should learn the language before copypasting some random code lmao

burnt gull
#

bro

#

😦 i watch tutoral bro

#

no copypastad

lyric sphinx
#

seems like the tutorial didn't explain you anything and you just blindly copypasted the code

burnt gull
#

yes i think 😦

lyric sphinx
#

you should try making something a bit simpler at first

cloud dawn
#

We don't help with music bots here.

lyric sphinx
#

yeah its against the rules if you want to play music from yt link

zenith ginkgo
burnt gull
#

i shold remove all aliaes?

cloud dawn
burnt gull
#

@lyric sphinx

lyric sphinx
#

nope but try removing that one

zenith ginkgo
burnt gull
#

@lyric sphinx is it still not work 😦

lyric sphinx
#

do the other commands work?

cloud dawn
#

@lyric sphinx So stop helping, or go to DM's.

burnt gull
cloud dawn
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
burnt gull
#

???

cloud dawn
burnt gull
#

😦

hushed galleon
jaunty hare
#

thank u so much bro

slate swan
#

how do I fix this?

#
@discord.ui.button(label = "Transcript", style = discord.ButtonStyle.blurple, custom_id = "transcript")
    async def transcript(self, interaction, button):
        await interaction.response.defer()
        if os.path.exists(f"{interaction.channel.id}.md"):
            return await interaction.followup.send(f"A transcript is already being generated!", ephemeral = True)
        with open(f"{interaction.channel.id}.md", 'a') as f:
            f.write(f"# Transcript of {interaction.channel.name}:\n\n")
            async for message in interaction.channel.history(limit = None, oldest_first = True):
                created = datetime.strftime(message.created_at, "%m/%d/%Y at %H:%M:%S")
                if message.edited_at:
                    edited = datetime.strftime(message.edited_at, "%m/%d/%Y at %H:%M:%S")
                    f.write(f"{message.author} on {created}: {message.clean_content} (Edited at {edited})\n")
                else:
                    f.write(f"{message.author} on {created}: {message.clean_content}\n")
            generated = datetime.now().strftime("%m/%d/%Y at %H:%M:%S")
            f.write(f"\n*Generated at {generated} by {client.user}*\n*Date Formatting: MM/DD/YY*\n*Time Zone: UTC*")
        with open(f"{interaction.channel.id}.md", 'rb') as f:
            await interaction.followup.send(file = discord.File(f, f"{interaction.channel.name}.md"))
        os.remove(f"{interaction.channel.id}.md")```
polar cargo
#

Can you tell me what's not "working"? Are you getting a error?

#

try adding a print inside the callback function and see if your command even gets executed

mental hollow
#

hey

#

so I want to log when a user gets a role using on_member_update

#

I’m aware I can use an if condition to detect if the update was a role change using if before.roles != after.roles

#

however, I’m unsure on how to get the exact role & say if it was added/removed

#

if anyone replies, please ping me!

rare echo
#

unless you are trying to check if only a certain role was changed / added you can just check the role id difference

torn sail
rare echo
spring summit
#

how would i make a command that displays the total amount of messages in a specific channel

potent spear
torn sail
potent spear
#

only thing which looks "redundant" to me is that if you'd somehow have 2 differences (which isn't really possible), you'd have more than one role returned

cerulean lichen
#

anyone tried to send the same file twice using webhooks, but the second server gets blank file ?

golden portal
upbeat gust
#

if not, did you use bytesobject.seek(0)

shut elk
#

Hi, I have a bot and it has a few slash commands, using tree commands and interactions per usual and everything worked out for one day, although it had interaction acknowledged and unknown interaction errors, it still worked. But after that one day, exactly one day after, all but one slash command have all disappeared and that one slash command is the only one that shows in the integrations. Also, all buttons that already existed are working and that one slash command also works. I'm wondering why all commands disappeared and how to fix it without restarting the program, like if it is due to the interaction errors? If you want to see my code, I can show it but it's very long. Also, I don't want to restart the program since it is running already with data and if I reset it will reset the variables too. I could just fix the interaction issues for future reference if it is because of that if that is the problem

drifting arrow
#

how can I limit a slash command to specific users or roles?

I'm currently doing @app_commands.checks.has_permissions(administrator=True) is there one for "has role"? or "role id? or something?

potent spear
drifting arrow
#

hoping to get a faster response here πŸ˜›

shut elk
potent spear
potent spear
drifting arrow
shut elk
#

well if it's inside the slash cmd

drifting arrow
#

Inside a slash command is easy enough to do.

shut elk
#

yeah

drifting arrow
#

I wanted the decorator.

shut elk
#

alr

#

just read the docs then

drifting arrow
#

To the documentation!

shut elk
#

lmao

shut elk
drifting arrow
#

lol

drifting arrow
#

Did your bot or discord server go offline for whatever reason?

potent spear
#

I'd just suggest a !paste and in a quick glance, you can probably spot the issue

drifting arrow
#

probably

#

but he said it was big, long and tedious. and Im not in the mood for anything big and long

potent spear
#

I read that wrong

drifting arrow
#

I know πŸ˜‰ it was on purpose

potent spear
#

anyways, if that's his case, he should work with cogs

drifting arrow
#

I assumed he was working with cogs

potent spear
#

because if it's "complex" according to him, he should at least be able to refactor

lucid jolt
#

can someone help me in #1059981623854108712 I used a list to try to check if they already have a ticket open but its not working and i dont know why

shut elk
drifting arrow
shut elk
potent spear
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

shut elk
potent spear
#

your issue is shadowing function names

half tangle
#

uninstalled py and tried updating discord.js but gives me this err

potent spear
torn sail
half tangle
naive briar
#

Is that related to Discord bots

#

Doesn't seem like it

#

Also you should ask in Js server

half tangle
#

ok catgal

sick birch
#

Pretty sure Node requires python to run

#

But this is a Node problem not a Python problem

half tangle
potent spear
meager chasm
#

is correct tho. Error being raised by npm not python. Irrelevant to this channel

slate swan
#
async def clans(ctx):
    raw_clan_data = await bot.db.clans.find(raw_clan_data)
    guild = await bot.get_or_fetch_guild(bot.guild_id)
    total_clans = []
    for field in raw_clan_data:
        clan_tag = await bot.db.clans.find(clan_tag.lower())
    total_clans.append(channels)
    clans_formatted = "\n".join([entry['clan_tag'] for entry in total_clans])
    embed = discord.Embed(title=f'{bot.server_name} Total Clans',
                            description=f'{clans_formatted}',
                            color=discord.Color.random()
                        )
    embed.set_footer(text=bot.server_name)
    await ctx.send(embed=embed)```
```Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/bot_base/bot.py", line 118, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/bot.py", line 165, in clan
    raw_clan_data = await bot.db.clans.find(raw_clan_data)
UnboundLocalError: local variable 'raw_clan_data' referenced before assignment```
#

having this error with this command

hollow agate
#

You're defining it with the definition...? raw_clan_data = await bot.db.clans.find(raw_clan_data)

#

Consider changing your variables to something else

slate swan
#

it is tho

hollow agate
#

Where do you define raw_clan_data before raw_clan_data = await bot.db.clans.find(raw_clan_data)?

slate swan
#

i got it i think

#
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/bot_base/bot.py", line 118, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/bot.py", line 165, in clans
    raw_clans = await bot.db.clans.find(raw_clan_data)
NameError: name 'raw_clan_data' is not defined```
hollow agate
#

raw_clan_data isn't defined anywhere, it cannot find(it)

naive briar
#

Imagine

indigo pilot
#

is there any way to get the author of the orgioanl message?

indigo pilot
naive briar
unkempt canyonBOT
hollow agate
#

oh my lord, I keep thinking they're doing something else

indigo pilot
#

not 1060028200069115924

naive briar
#

Author of the message

#

What do you think it is

indigo pilot
#

???

indigo pilot
indigo pilot
#

its a reply

naive briar
#

What???

indigo pilot
#

???

#

what is there to not understand 😭

hollow agate
#

Everything... ?

indigo pilot
#

even gave a example

naive briar
#

I give up

indigo pilot
#

it used to be original_message

#

back in the old days

hollow agate
#

For slash commands?

indigo pilot
#

but its been edited and i got no clue what it is no

indigo pilot
hollow agate
#

You want to find the author of me, right?

indigo pilot
#

yes

indigo pilot
indigo pilot
hollow agate
#

eek, I don't remember how to do it, one sec

torn sail
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

hollow agate
#

ah yeah

indigo pilot
torn sail
#

Then from their you can use cached_message.author

indigo pilot
#

sounds like more work

#

ill just ping the user in the msg ig then get message.mentions lmfaoo

torn sail
#

Lmao ok

naive briar
#

That's not any less thing to do

indigo pilot
#

yeah all you do is message.mentions[0] if i remember

slate swan
# hollow agate `raw_clan_data` isn't defined anywhere, it cannot `find(it)`
async def clans(ctx):
    raw_clan_data = await bot.db.clans.get_all()
    raw_clans = await bot.db.clans.find(raw_clan_data)
    guild = await bot.get_or_fetch_guild(bot.guild_id)
    total_clans = []
    for field in raw_clans:
        clan_tag = await bot.db.clans.find(clan_tag.lower())
    total_clans.append(clan_tag)
    clans_formatted = "\n".join([entry['clan_tag'] for entry in total_clans])
    embed = discord.Embed(title=f'{bot.server_name} Total Clans',
                            description=f'{clans_formatted}',
                            color=discord.Color.random()
                        )
    embed.set_footer(text=bot.server_name)
    await ctx.send(embed=embed)```
#

now its defined

naive briar
naive briar
#

The .MENTIONS will get all member mentions in the message

indigo pilot
#

the msg is sent from the bot

zealous jay
#

How do I check for permissions? Im using discord.py 2.0

#

commands.has_permissions doesn't work, right?

sick birch
#

Are you looking for slash command permissions?

zealous jay
#

yeah its with app_commands.checks.has_permissions

sick birch
#

That's the slash command alternative yeah

zealous jay
#

for slash commands

zealous jay
#

How do I delete a global command?

#

It doesn't even exists anymore

shut elk
#

I just copied and pasted the functions 😭 i forgot, thought it was the self's in classes forgot they were functions 😒 that's why only the first one works too

#

thank you !

light violet
#

i am getting this error

#

File "<fstring>", line 1
(default 5 msg)

upbeat otter
light violet
upbeat otter
light violet
#

only this line

#

no traceback

upbeat otter
#

huh

#

screenshot

vale wing
#

If so do that please

light violet
#

no need now i fixed it

#

thanks

flint bolt
#

hey, i want to make it so a user gets warned by their name and that gets stored in the row of the database

#

its not working at all

#
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
import asyncio
import datetime
intents = discord.Intents.all()
from discord import app_commands
import random
import sqlite3
help_command = commands.DefaultHelpCommand(
    no_category = 'Commands'
)
connection = sqlite3.connect('warns.db')
cursor=connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS warnings(user TEXT, reason TEXT, date INTEGER, mod TEXT)""")
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@client.event
async def on_ready():
    guild = discord.Object(id=1056934892392419329)
    await tree.sync()
    await client.change_presence(activity=discord.Game('/help ┃ We support slash commands!'))
    print(f'Atom has connected to Discord!')

@tree.command(name = "ping", description = "Shows latency of bot")
async def ping(interaction: discord.Interaction):
    ping_embed=discord.Embed(title=f"Atom bot's ping is: {round(client.latency * 1000)} ms", color=discord.Colour.og_blurple())
    await interaction.response.send_message(embed=ping_embed)

@tree.command(name='warn', description='Warn a user')
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
    warn_embed.set_footer(text=str(datetime.datetime.now()))
    date=str(datetime.datetime.now())
    cursor.execute(f""" INSERT INTO warns VALUES('{member.mention}', '{reason}', '{date}', '{interaction.user.mention})""")
    await interaction.response.send_message(embed=warn_embed)   
    warn_embed = discord.Embed(title='Warning', description=f'{member.mention}, you have been warned on {interaction.guild.name} for {reason}. \n Warning issued by: {interaction.user.mention}.', color=discord.Colour.og_blurple())
    await member.send(embed=warn_embed)

@tree.command(name='warns', description="List a user's warnings")
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member):
    cursor.execute(f"""SELECT * FROM warnings WHERE user = '{member.mention}'""")
    rows = cursor.fetchall()
    interaction.response.send_message(rows)
upbeat otter
#

what part

somber imp
upbeat otter
#

and you might want to change the function names πŸ’€

somber imp
#

Also, use member id instead of member mention

somber imp
upbeat otter
#

and sqlite3 πŸ˜”

somber imp
#

πŸ₯²

#

Use aiosqlite if you want to use sqlite

flint bolt
flint bolt
somber imp
somber imp
flint bolt
#

i tried doing it and it just didnt work

#

i wish someone explained it in a concise and understandable manner not in a youtube tutorial from a 10 year old kid that doesnt show half the code from FOUR YEARS AGO

somber imp
#

πŸ’€

#

Tbh aiosqlite hasn't changed any significantly. So 4-5 year old videos aren't inaccurate

bright wedge
#

and use async sqlite framework

#

!pip aiosqlite (for sqlite3)

unkempt canyonBOT
pulsar bridge
#

Getting this error message:

Traceback (most recent call last):
  File "C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\main\Downloads\Personal Stuff\Bots\bot\boto\botname.py", line 70, in create
    file.write(text)
AttributeError: 'coroutine' object has no attribute 'write'
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'write'
C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
With the code:
```python
@bot.command(name='add_note')
async def create(ctx, title: str, *, text: str = None):
    title = title.lower()
    print(title)
    print(text)
    file_name = str(directory + title + ".txt")
    print(file_name)
    proceed = 1
    file = open(file_name, 'xt')
    file.close()
    file = open(file_name, 'wt')
    file.write(text)   # <- Is Line 70
    file.close()
    file = open('list.txt', 'at')
    file.write(title)
    file.close()
    await ctx.send(f'File successfully created with the name {title}!')

Probably something stupid that I've missed

pulsar bridge
#

Nope, just the inbuilt file handling

#

Should I?

viral stump
#

print("Eğer " + str(random_int) "sayısı, " + str(percentage * 100) " sayısından düşükse hedef belirlenir.")

#

SyntaxError: invalid syntax. Perhaps you forgot a comma?

viral stump
#

oh fuck

pulsar bridge
#

No wait

#

It's an f string, why do you have pluses?

naive briar
#

Why would you use f-string if you're using + operator

viral stump
#

nah, i pasted f one sorry

#

there is no f on code, i pasted wrong one sorry

pulsar bridge
#
print(f'Eger {str(random_int)} say151 {str(percentage * 100)} sayısından düşükse hedef belirlenir.')

Would work

#

or

print("Eğer " + str(random_int) + "sayısı, " + str(percentage * 100) + " sayısından düşükse hedef belirlenir.")
pulsar bridge
upbeat otter
pulsar bridge
#

Good to know

upbeat otter
#

it's as easy as

import aiofiles

async with aiofiles.open("filename.extension", "r") as f:
  content = await f.read()
#

you can install aiofiles using python -m pip install aiofiles

pulsar bridge
# upbeat otter it's as easy as ```py import aiofiles async with aiofiles.open("filename.exten...

Two steps ahead of you already! PI_2cool
But thanks for the reply!
Two questions though
Would this work?

if proceed == 1:
        try:
            async with aif.open(file_name, 'xt') as f:
                file = f
            proceed = 2
        except:
            await ctx.send(f'Something went wrong with creating the file! What probably happened is that a file named {title} already exists!')
    if proceed == 2:
        try:
            file.write(text)
            file.close()
            proceed = 3
        except:
            await ctx.send(f'Something went wrong when attempting to write to the file named {title}!')

2nd Question, what does the python -m part do when installing libraries?

upbeat otter
#

and

pulsar bridge
upbeat otter
#

you need to await every action on the file

#

await file.write
await file.close
etc

pulsar bridge
#

ah Hah! That's what I was missing!
Thanks!

upbeat otter
shrewd apex
pulsar bridge
viral stump
#
                idlist = await bot.fetch_user(victim_user_id)
                chance = (percentage * 100)
                await message.channel.send(f"{idlist.display_name} ve %{chance}")````
Everything is working fine but chance's output is being like:
``%50.0`` but i want it ``%50``

How can i do it?
golden portal
#

better to round it actually

naive briar
#

!d round

unkempt canyonBOT
#

round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
viral stump
#

Thank you, string format worked well

#

Can i do output in like this code line?