#discord-bots

1 messages · Page 359 of 1

autumn sierra
#

@shrewd apex

#

@discord.app_commands.command(name="kick", description="kicks a member from the server")
@discord.app_commands.default_permissions(kick_members=True)
async def kick(self, interaction, member: discord.Member, *, modreason=None):
await member.kick(reason=modreason)

    conf_embed = discord.Embed(title="Success!", color=discord.Colour.green())
    conf_embed.add_field(name="Kicked", value=f"{member.mention} has been kicked from "
                                              f"the server by {interaction.author.mention}.", inline=False)
    conf_embed.add_field(name="Reason", value=modreason or "No reason provided", inline=False)

    await interaction.response.send_message(embed=conf_embed)
viscid hornet
#

!code 🗣️

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

autumn sierra
#

but somn wrong about mod reason

viscid hornet
#

checks out but you should definitely use this py from discord import app_commands

#

makes your code look much cleaner, like when you do py from discord.ext import commands

autumn sierra
viscid hornet
autumn sierra
#

now i dont cuz am using discord.app_commands alrdy

viscid hornet
#

just remove the asterisk and typehint mod reason to a string

autumn sierra
#

also when i use it it says unused lol

viscid hornet
viscid hornet
#

you're supposed to change the stuff using discord.app_cmds to just app_cmds

fast osprey
#

Using module aliasing is purely personal preference

autumn sierra
#

cuz it worked with discord.app_command

viscid hornet
#

was just abt to say that

autumn sierra
autumn sierra
viscid hornet
autumn sierra
#

then ?

#

how do i typehint mod reason to a string ?

viscid hornet
viscid hornet
# autumn sierra i removd asterisk

good. the asterisk defines i think positional arguments, but in dpy its used to take everything after a certain argument. not sure. maybe solstice can add

#

its not needed for slash commands because the inputs are already separated

#

probably poor explanation im ngl

fast osprey
#

It's worth mentioning that as written, this throws away several protections already made by the built in /kick

viscid hornet
#

also was my explanation faulty

fast osprey
#

Prefix commands use the * because at the start it's just one giant string and dpy has to parse them. The * means "parse the rest as one parameter". This isn't needed for slash commands as discord sends these as individual already parsed arguments

viscid hornet
#

thanks solstice prayge

autumn sierra
#

also now my slash isnt even showing up lol

fast osprey
#

Basically what you said but expanded a bit with what's happening under the hood. This also means all slash command parameters need to be typehinted

autumn sierra
#

just a sec ago it showed up at least

#

now what do i do ?

viscid hornet
#

what do you mean by "a sec it showed up at least but its not there"

autumn sierra
#

literally that

#

now the /kick

#

not showing up

viscid hornet
#

try resyncing your commands or refreshing any cogs

#

screenshots would also be pretty helpful for this sort of stuff

autumn sierra
#

refresh worked

#

but i think now reason is being a necessary arg

#

i want it to be an option and if no reason
it will auto send
no reason specified

#

i have alrdy coded like that but whn it came to slash
it bcm compulsory

#

how do i change@discord.app_commands.command(name="kick", description="kicks a member from the server")
@discord.app_commands.default_permissions(kick_members=True)
async def kick(self, interaction, member: discord.Member, modreason: str):
await member.kick(reason=modreason)

    conf_embed = discord.Embed(title="Success!", color=discord.Colour.green())
    conf_embed.add_field(name="Kicked", value=f"{member.mention} has been kicked from "
                                              f"the server by {interaction.author.mention}.", inline=False)
    conf_embed.add_field(name="Reason", value=modreason or "No reason provided", inline=False)

    await interaction.response.send_message(embed=conf_embed)
viscid hornet
viscid hornet
#

!code also pretty important

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

autumn sierra
#

oh

#

where do i add none ?

autumn sierra
viscid hornet
autumn sierra
#

but now str is thr

viscid hornet
viscid hornet
#
modreason: str = None```
fast osprey
#

Typehints and defaults are two separate parts of a parameter declaration

viscid hornet
#

you can have a typehint and a default

#

yeah what solstice said

autumn sierra
#

what is typehint lol

viscid hornet
#

they're not mutually exclusive

viscid hornet
fast osprey
#

You also can (and probably should) use the Optional typehint in combination with this

viscid hornet
#

when you do something: something_else, that : is a typehint

autumn sierra
viscid hornet
autumn sierra
viscid hornet
#

and how they can't be put on the same bow?

autumn sierra
#

also still now it says mod reason is requiredd

viscid hornet
#

(just the arguments. not the whole thing)

autumn sierra
autumn sierra
#

async def kick(self, interaction, member: discord.Member, modreason: str = None):

viscid hornet
#

try syncing your commands again

autumn sierra
viscid hornet
autumn sierra
viscid hornet
#

thats part of it

autumn sierra
#

also this type command worked
and it became optional
but then the embed didnt show up

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

autumn sierra
#

what is this now ?

viscid hornet
#

commonly called "errors"?

autumn sierra
#

no red flags btw

viscid hornet
#

so whats the problem?

cold sonnet
#

programming hard

autumn sierra
#

i just want the mbed to wurk lol

viscid hornet
#

!code | and please for the love of god use this

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

viscid hornet
#

im gonna go for a walk soon

autumn sierra
autumn sierra
autumn sierra
autumn sierra
wanton current
#

hm

autumn sierra
#

?

swift acorn
#

Hey guys, I am using discord.py and autocomplete for the options since they are more than 25, I am just wondering why if nothing is typed, it doesn't load any options by default
Only when I type at least one letter

swift acorn
#
async def maps_autocomplete(interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
    speedrun_maps = ['Abduction Avenue', 'Abducted Avenue', 'Behold the Gold', 'Burrito Bonanza', 'Cannon Climb', 'Cannonball Chaos', 'Construction Climb', "Crab's Landing", "Don't Be Jelly!", 'Floor Flip', 'Humble Stumble', 'Ice Caramba', 'Icy Heights', 'Jungle Roll', 'Lava Rush', 'Lost Temple', 'Monopoly Rush', "MrBeast's Dangerous Traps", "MrBeast's Warehouse", 'NFL Scramble', 'Over & Under', 'Paint Splash', 'Pivot Push', 'Race For Eternia', 'Space Race', 'Sping Go Round', 'Stumble Cove', 'Stumble Trouble', 'Super Lava Slide', 'Super Paint Slide', 'Super Pivot Slide', 'Super Slide', 'Super Waterpark', 'Tile Fall', 'Tornado Temple', 'Turtle Tumble']
    return [
        app_commands.Choice(name=speedrun_map, value=speedrun_map)
        for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
    ]


@bot.tree.command(name="submit-time-trial", description="Submit an entry into the Time Trial Competition!")
@app_commands.check(check_cc)
@app_commands.autocomplete(speedrun_map=maps_autocomplete)
@app_commands.describe(speedrun_time = "Please enter your speedrun time in MM:SS:MS format", video = "Please enter the link to your speedrun video", speedrun_map="Enter the map you are submitting for.")
async def speedrun(interaction : discord.Interaction, speedrun_time : str, video : str, speedrun_map : str):
    await interaction.response.defer(ephemeral=True)
#

My friend has a JS bot with similar use of autocomplete but theirs show default options when nothing is typed

slate swan
#

try this ```py
if not current:
return [app_commands.Choice(name=speedrun_map, value=speedrun_map) for speedrun_map in speedrun_maps[:25]]
return [
app_commands.Choice(name=speedrun_map, value=speedrun_map)
for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
]

swift acorn
#

gotcha, thank you so much! Let me try

fast osprey
#

You should probably always be capping at 25 just in case even a search yields more

swift acorn
#

It worked! And yes that's true
How would I go about doing this? Would something like this work?

if not current:
        return [app_commands.Choice(name=speedrun_map, value=speedrun_map) for speedrun_map in speedrun_maps[:25]]
    return [
            app_commands.Choice(name=speedrun_map, value=speedrun_map)
            for speedrun_map in speedrun_maps if current.lower() in speedrun_map.lower()
        ][:25]
fast osprey
swift acorn
#

Thank you both a ton prayge

upbeat otter
autumn sierra
#

i used author instead of user

#

i think its user for slash cmds instead of author perhaps ?

#

@upbeat otter

wanton current
#

you should probably check permissions before kicking someone

wanton current
#

like hierarchy

upbeat otter
fast osprey
#

This lets anyone with the kick members permission kick anyone else underneath the bot, with no tracking or auditing, and bypassing the server's 2FA requirements

upbeat otter
#

That seems cool

shrewd apex
#

pulling out all stops

autumn sierra
#

i kept manage perm
to kick_memebers

#

=true

fast osprey
#

which covers the first part of my sentence, but none of the rest

autumn sierra
#

what r u gys saying ?

shrewd apex
#

yes now say there is another guy with a higher or similar perm i can kick them out as long as the bot is highers than either of them

autumn sierra
#

are u saying it to me ?

shrewd apex
#

yes

autumn sierra
#

so my code can let anyone kick ?

upbeat otter
#

kinda

autumn sierra
#

but how come

fast osprey
#

anyone with that perm can kick anyone else that the bot could kick, even if they themselves shouldn't be able to

#

because you're not checking anything

autumn sierra
#

@discord.app_commands.default_permissions(kick_members=True)

wanton current
#

eg. a mod could kick another mod with the same role, using the bot

shrewd apex
#

yeah but now say there is a guy with manage_server perms now i can still kick him out (i am the guy with kick_perms)

#

if the bot is higher than both of us

autumn sierra
#

ohhh

fast osprey
#

When someone kicks someone else in the normal discord flow, discord performs several checks. Not only do they have the perm, but it also checks the server's 2FA policy and the hierarchy. Your code does none of that

autumn sierra
#

then how do i solve that ??

shrewd apex
#

use the built-in kick

autumn sierra
#

then ?

fast osprey
#

That's the unironic correct answer

shrewd apex
#

check for role heirarchy

autumn sierra
#

ummm

shrewd apex
#

role positions basically

autumn sierra
#

how do i do that

shrewd apex
#

!d discord.Role.position

unkempt canyonBOT
#

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

fast osprey
#

You will also never be able to verify 2FA settings without every mod authorizing your bot through oauth. There's no functional reason to do this in a bot at all

autumn sierra
#

how do i code that to the bot ?

shrewd apex
#

so allow kicking only when role lower than commands author

autumn sierra
#

like what shud i type in ?

#

the tutorial guy did this for kick

shrewd apex
fast osprey
#

I'm willing to bet a large sum of money that this tutorial guy had no idea what they're doing

autumn sierra
#

i thot it had brains

autumn sierra
#

wait gys just come back down

shrewd apex
#

and same with the guy being kicked

autumn sierra
#

stop stop lets come back

shrewd apex
#

then compare

autumn sierra
#

i wanna ask what does my bot do now ?
am thought it would allow ppl to kick othrs if they have kick members perm switched on
isnt that what my bot is gonna do ?

fast osprey
#

Discord checks 3 things. Your bot checks 1 thing

autumn sierra
#

okah done
so what are the other 2 things i need ?

#

to add to my bot ofc

wanton current
#

hierarchy, 2fa

fast osprey
#

It's in that sentence

wanton current
#

lol

autumn sierra
#

got it
now next
how do i do it

fast osprey
#

and as I have said, these things already exist in something people already have

#

and implementing it yourself is going to range from annoying to impossible

shrewd apex
#

thats quite a bit of selective reading 💀

autumn sierra
#

lol mb
now how do i do it ?

shrewd apex
#

continue reading lol i told u how

#

unless ur expecting code for that particular bit

autumn sierra
fast osprey
#

Telling you now that you are not going to bother with the 2FA bit

autumn sierra
fast osprey
#

Maybe one question worth asking is why do you want people to use this instead of the built in /kick they already have and works great

shrewd apex
#

whats the point then, u just seems to copy pasting lines of code from few of us or a few tutorials and patching stuff up, what are u learning?

shrewd apex
autumn sierra
fast osprey
#

You can do this with other pieces of the api that aren't sensitive and aren't eroding security protections people rely on, but you do you

autumn sierra
#

also i did not come to master python or stuff
just making a small bot for my server
a part time hobby if u wanna say

shrewd apex
#

i also pointed out which particular attributes you need to check

fast osprey
#

People already have a /kick, but you want to make a /kick to learn something. People already can make channels, send messages, modify settings, and a billion other things that aren't as sensitive or protected so why not just implement those

shrewd apex
#

so why dont you try or atleast attempt to solve the issue by yourself once before looking for a solution

autumn sierra
shrewd apex
#

imo ur just doing stuff with little to no goal

autumn sierra
blazing beacon
#

why not try to figure it out yourself first? its fun too like a puzzle ||with less than 1000 peices||

autumn sierra
# shrewd apex imo ur just doing stuff with little to no goal

umm
in one way or the othr yea
Free time go to yt tutorials
copy paste code is what am literally doing rn
lol
but now i can make embeds cuz i have done in first time by copying
and i did it alone for my ping command altho i sneek peaked a bit
lol

shrewd apex
#

!d discord.Interaction.user

unkempt canyonBOT
shrewd apex
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
tardy trail
#

tell me a program that you are proud of writing as a beginner

autumn sierra
#

nyways thanks for ur tym ig
i will figure it out by trial and error or some referrals lol

blazing beacon
autumn sierra
#

also like solstice said
y the shit am i even making kick and ban and unabn etc stuff what all thr

#

imma think outta the box and do somn different

#

it makes no sense
lol

#

wasted my tym lol

wanton current
#

at the end of the day you should do whatever you feel like, as long as you're learning on the way

fast osprey
#

Re-implementing things is fine as a learning exercise. But when you do so and actively make security worse on a server you probably should be re-implementing something else

autumn sierra
#

lol yea

autumn sierra
#

perhaps i can create a game

#

but i think its too complex for a beginner like me

shrewd apex
#

maybe just start with basic python

glad cradle
autumn sierra
#

lol
4got aftr i went to boarding school where electronic devices were not allowed for 2 whole yrs
lol

#

like a bit i tried

blazing beacon
# autumn sierra oh wow

copy pasting is only good in the short term of things it rlly doesnt help in the long term of things like imagine you have this super unique issue only to your project youre kinda just done there

#

to learn how to use something is to have more ideas on how to make something new

blazing beacon
#

ive had issues where even gpt cant help me and i had to quit the project and learn the basics

autumn sierra
#

i dont think i have the patience
tbh

blazing beacon
#

but thats just me

autumn sierra
blazing beacon
#

nope far from it

autumn sierra
#

learning as we all do ig

#

mayb i might start from the beginning as well

rain hedge
#

where would I start to make a code check if someone received a certain role?

fast osprey
#

Coding isn't easy, it takes time + dedicated learning + personal experimentation and exploration

autumn sierra
#

far

shrewd apex
rain hedge
#

no command associated

shrewd apex
#

on member update iirc using before.roles and after.roles

rain hedge
#

do I just skip the command part and go to async def ...

shrewd apex
#

or event

rain hedge
shrewd apex
#

its same as on_message that is normally done except on_member_update here

rain hedge
#

alr

blazing beacon
rain hedge
autumn sierra
#

one doubt
i can use prefixes in my server right
like i dont want slash cmds

#

discord will lemme do that right ?

#

also i dont plan to make my bot private
i will be only thr in 1 or 2 servers max

fast osprey
#

Yes, you only need message content for prefix commands to work

autumn sierra
#

cool

quick gust
shrewd apex
#

^^

autumn sierra
cloud dawn
meager rock
#

Asher

autumn sierra
#

just to get some hang of the basics

#

rest i will learn by trail and error
lol

viscid hornet
autumn sierra
#

can anyone share me a video link to learn the python basic the fastest way
i do not need like the best of the best
just to get a hang of the basics
rest i shall learn from trial and error or by seeking help frm othr ppl
pls share me a link ?
also if there is any specific vid abt discord.py basics
better

autumn sierra
viscid hornet
viscid hornet
autumn sierra
#

lol

meager rock
#

I was regular here a year ago or so

viscid hornet
#

ohh alr

viscid hornet
#

https://codeabbey.com - this is a good one, but its centered around problems. its the one i used.
https://codewars.com - this one is good as well for learning python basics.

Codewars

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

autumn sierra
viscid hornet
shrewd apex
shrewd apex
meager rock
warped cave
#

does anyone know how to make a code so that if i put a command in a specific channel it sends messages that you cant use the command in that channel ?

viscid hornet
warped cave
#

so like if i have 2 commands (!hello and !bye) i want that !hello cant be used in a specific channel

#

only thing i can find is this ```default_invoke = bot.invoke
async def new_invoke(self, ctx: Context):
if ctx.command:
if 'cypher_ascend_a':
return

await self.default_invoke(ctx)

bot.invoke = new_invoke```

upbeat otter
wanton current
#

==

warped cave
# upbeat otter ```py if ctx.channel.id = 12455493993: return await ctx.send("you can't run ...

i have this code ```@bot.group()
async def cypher_ascend_a(ctx):
file_1 = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher A site ascend.png', filename="cypher ascend-a one-way.png")
embed = discord.Embed()
file_2 = discord.File(r'C:\Users\Luuk\Pictures\Cypher setup\ascend\A site\cypher ascend-a one-way.png', filename="cypher A site ascend.png")
embed = discord.Embed()
embed.set_image(url="attachment://cypher ascend-a one-way.png")
embed.set_image(url="attachment://cypher A site ascend.png")

await ctx.send('Aline yourself under this line in the generator and aim at the spike in the sky to get this heaven one-way')
await ctx.send(files=[file_1])
await ctx.send("Jump and throw")
await ctx.send(files=[file_2])
await ctx.send(embed=embed, file=file)

if ctx.channel.id == 1234540499390431252:
return await ctx.send("you can't run the command in this channel")``` but get the following error return await ctx.send("you can't run the command in this channel") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'return' outside function

upbeat otter
#

maybe you have to fix your indentation

upbeat otter
upbeat otter
#

and wtf is with that code

#

😭why are you sending different messages

warped cave
#

bc its sending a picture with a text

wanton current
warped cave
#

you mean this:

    await ctx.send(files=[file_1])
    await ctx.send("Jump and throw")
    await ctx.send(files=[file_2])
    await ctx.send(embed=embed, file=file)
    if ctx.channel.id == 1234540499390431252:
        return await ctx.send("you can't run the command in this channel")```
upbeat otter
warped cave
#

it bc its 2 images with 2 diffirent text inside one command

viscid hornet
viscid hornet
#

!d discord.ext.commands.Bot.group

unkempt canyonBOT
#

@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
viscid hornet
#

damn

warped cave
upbeat otter
warped cave
#

but will it send the text in the same order as now ? bc now i have a text, image, text, image

wanton current
#

sending 5 seperate is not ideal

#

basically a ratelimit every time you use the command

warped cave
#

this is what i created

#

than you can see what i mean

autumn sierra
#

what does ambigous variable mean ??

wanton current
#

name is easily confused with other letters eg. l

#

if that's what you mean

autumn sierra
#

it says

#

0 is ambigous

wanton current
#

you can noqa it if you want

slate swan
#

i mean the name makes no sense

autumn sierra
#

its for tic tac toe

wanton current
#

also why -1 1 2, and not 0 1 2 ?

upbeat otter
autumn sierra
warped cave
#

yeah but when im in game i want to be able to send a command and than check a few photo's

unkempt canyonBOT
#

examples/views/tic_tac_toe.py lines 66 to 68

X = -1
O = 1
Tie = 2```
warped cave
#

so you dont have to watch a video

wanton current
autumn sierra
#

is thr any other thing for edit_message

#

Cannot find reference 'edit_message' in '() -> InteractionResponse'

#

this warn comes

wanton current
#

are you using pycharm

autumn sierra
#

ye

slate swan
autumn sierra
#

lol

slate swan
#

ignore it

viscid hornet
wanton current
#

interesting

autumn sierra
#

also now interactions is unresolved

#

red flag error
ai aint smart to code my tic tac toe ?lol

#

or idk if its my prb

upbeat otter
autumn sierra
#

what do i do for this ?

warped cave
#

well i want o make that but than for every agent, so if i have to cearch for every agent for every map on every site it takes a long time that why i want to make the commands like that

upbeat otter
autumn sierra
#

nvm got it

warped cave
#

so that command is what i wanna use in a channel for only that agent, but i dont know how to block the other commands in that channel. So you won't have different picutres of different agent in the same channel. If that makes sens

viscid hornet
#

you'll need a database for that then

warped cave
#

i guess so, that only a few commands can be send in a specific channel

#

were can i find the right info to learn about a database for that ?

viscid hornet
pale zenith
#

oh damn I am looking through this channel's pins and the misinformation in there hoes hard 🔥

wanton current
#

like?

pale zenith
#

well it was the like old slash libs (2020ish pins)

wanton current
#

yeah should probably be unpinned

pale zenith
#

tbh other pins hold info that was relevant but isn't anymore lol

#

Or the two gists from Deleted User

viscid hornet
rain hedge
#
@bot.listen()
async def on_member_update(before, after):
    staffrole = discord.Guild.get_role(1155546749117669376)
    if staffrole in on_member_update(before, after):
        print("zaddy")
TypeError: Guild.get_role() missing 1 required positional argument: 'role_id'

could use some help

viscid hornet
#

also your command repeats itself so it doesnt go anywhere

#

dw it happens lmao

wanton current
#

ah yes let's not help them and instead tell them how bad their code is

spice warren
viscid hornet
#

but yeah good point. i see what you mean

#

in an argument with friends so kinda pissy

blazing beacon
#

youre doing this voluntarily remember

viscid hornet
elder flower
#

Anyone got any docs you’d recommend for starting with discord bots?

elder flower
#

Thanking you muchly

rain hedge
#

np

slate swan
#

Hello anybody able to help, I'm looking for a script I could add to my python script for mentioning members username in an embedded message upon them receiving certain roles

unkempt canyonBOT
viscid hornet
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
viscid hornet
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
viscid hornet
#

@slate swan this is all you need, pretty much

slate swan
mossy jacinth
#

why does it say i dont have message content intent enabled even though i have all intents enabled?
I even added the intent.message_content = True just to be sure but it still doesnt work

MissingMessageContentIntentWarning: Message content intent is not enabled. Prefix commands may not work as expected unless you enable this. See https://docs.nextcord.dev/en/stable/intents.html#what-happened-to-my-prefix-commands for more information.

viscid hornet
#

nextcord farm_pepeHAHAUSUCK

viscid hornet
#

i think nextcord renamed that to discord.Bot

#

show where you defined your Bot

#
# for dpy
import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix = '?', intents = intents)```
#

should look smth like this

mossy jacinth
viscid hornet
#

also whats the silly error that you dont want to return to dpy because of

mossy jacinth
viscid hornet
mossy jacinth
viscid hornet
#

theres a very good gist about subclassing help commands in dpy here

mossy jacinth
#

the help command isnt my problem now though

#

it works fine so i wont change it

timber dragon
#

Print dict(bot.intents) somewhere please

obsidian hill
#

If theres an error in main.py how could I send it to bot.py so it can send it in a embed or if possible just send it in a webhook from main.py?

blazing beacon
#

make an error handler

#

!d discord.discord.ext.commands.on_command_error

unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error)).
blazing beacon
#

AHA there we go

fierce ridge
#

how to take input as a txt file

#

example /give dskfjsdkfssssss.txt

#

the txt is uploaded

slate swan
fierce ridge
#

to my laptop

#

can i get the whole command im kinda new

#
bot.tree.command(name="give")
@app_commands.describe(txt = "Give Txt FIle")
async def say(interaction: discord.Interaction, txt: discord.Attachment):
#

like this?

slate swan
#

yep

fierce ridge
#

ok thx

slate swan
#

but this wont accept only txt

#

it will also accept for example images

fierce ridge
#

@slate swan i can add an execption if i can read the txt its txt file if it gives error its not right

#

i can do it like tht no?

#

@slate swan another thing when u get the attachemnt

#

is it downloaded in my laptop

#

like in the folder of python code?

slate swan
fierce ridge
#

ill try it

slate swan
#

and to the second question, they arent afaik

fierce ridge
#

afaik?

#

oh shi mb

#

@slate swan and another how do i check name of the file in the attachment

slate swan
#

hm

#

!d discord.Attachment

unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str) and is hashable.
fierce ridge
#

thx

#

@slate swan the attachment

#

dosent download

#

@slate swan

#

so download file is await save(fp, *, seek_begin=True, use_cached=False)

#

it shows this tho

#
@bot.tree.command(name="add")
@app_commands.describe(file = "Give The txt combo")
async def say(interaction: discord.Interaction, file: discord.Attachment):
    file_name = file.filename
    
    await file.save(fp, *, seek_begin=True, use_cached=False)
#

whole code (basically trying to downlaod the txt file from attachments)

#

it says fp not defined

hushed galleon
#

the signature shown in the documentation has different syntax rules than what you would write when you're calling that function

fierce ridge
#

so how to download the file?

hushed galleon
#

you need to open a file to save it to first

fierce ridge
#

how?

hushed galleon
#

oh it seems you can pass a filename too

#

e.g. attachment.save("foobar.txt")

fierce ridge
#

file.save()

#

dosent work

#

i dint give any response where does it download?
i want it to download to the file where bot.py is loacted

hushed galleon
#

ya, you need to pass either a file object or a filename for dpy to save it to

fierce ridge
#
discord.Attachment.save(file)
#

this?

hushed galleon
#

you er, cant call instance methods on the class directly

#

if you don't need to physically write the file to disk, you can use an in-memory file instead: ```py
import io

@bot.command()
async def command(ctx, attachment: discord.Attachment):
file = io.BytesIO()
await attachment.save(file)
data_bytes = file.read()
data_text = data_bytes.decode("utf-8")
await ctx.send(f"The attachment contains:\n{data_text}")```

fierce ridge
#

its the same with /slash command

#
@bot.tree.command(name="add-stocks-free")
@app_commands.describe(file = "Give The txt combo")
async def say(interaction: discord.Interaction, file: discord.Attachment):
  file = io.BytesIO()
  ===========================================
#

same?

hushed galleon
#

sure

#

well, with a different variable name in your case

fierce ridge
#

i figuired

#

figured

#

yo it dosent work

#

it says invalid Integration(the bot)

copper flume
#
0|bot      | Traceback (most recent call last):
0|bot      |   File "/path/to/venv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
0|bot      |     await coro(*args, **kwargs)
0|bot      |   File "/root/Events/logging.py", line 216, in ModLog
0|bot      |     if not entry.target.is_timed_out() and entry.before.timed_out_until:
0|bot      |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0|bot      | AttributeError: 'AuditLogDiff' object has no attribute 'timed_out_until'```
fierce ridge
#

yo how to add this kinda message into embeds

upbeat otter
upbeat otter
shrewd apex
#

ai coding ducky_beer

upbeat otter
copper flume
#

SO WHY DO YOU REPLY IF YOU DON'T KNOW ABOUT IT?

pale zenith
#

!d discord.AuditLogDiff

unkempt canyonBOT
#

class discord.AuditLogDiff```
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.

Note that accessing an attribute that does not match the specified action will lead to an attribute error.

To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for [`AuditLogAction`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogAction), otherwise check the documentation below for all attributes that are possible.

iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
pale zenith
#

Read this carefully, that error is intended.

#

You need to use hasattr or getattr, probably.

#

!d g hasattr

unkempt canyonBOT
#

hasattr(object, name)```
The arguments are an object and a string. The result is `True` if the string is the name of one of the object’s attributes, `False` if not. (This is implemented by calling `getattr(object, name)` and seeing whether it raises an [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError) or not.)
copper flume
#

ok

viscid hornet
#

!d discord.Member.display_name @swift siren

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
viscid hornet
#

before is an instance of discord.Member

slate swan
#

I am trying to get my discord bot to update an embedded message with their @ under the correct category depending on what they are checking in for, However the code works fine but the bot isn't updating the embedded message with @ username when that role is assigned, could someone tell me what is missing or wrong with the code please.

https://paste.pythondiscord.com/B7VQ

swift siren
copper flume
#

@pale zenithIs it possible to make commands.HelpCommand hybrid?

copper flume
fierce ridge
#

how to download a file given in attachment (slash command) download to folder of bot.py

#

yo nobody les go

#

i tried in the morning nothing worked

turbid condor
#

The file is a parameter right?

fierce ridge
#

ye

#

attachment in /slash command

turbid condor
#

!d discord.File

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
fierce ridge
#

I looked through it the file.save(fp) dosent work some error

#

I'll show later I closed my pc

turbid condor
#

Well i don't know how to do it or is it even possible since i couldn't find anything regarding it

spice seal
turbid condor
#

You can try doing interaction.message.attachments[0].save but i doubt it's gonna work since slash command don't have a message attached to it

spice seal
#

Anyone here? Hello?

turbid condor
#

If it's a free hosting then the are probably not good

spice seal
turbid condor
#

Since free hosting use share ips which causes frequent rate limiting issues

fast osprey
#

As a rule of thumb, anything that markets itself as a "discord bot host" is a scam because "discord bot hosts" don't exist. There are just hosts where you run processes

#

Their privacy policy is also scummy

turbid condor
spice seal
fast osprey
#

You should run your bot and profile it, it's impossible to accurately estimate the resources you'll need from just a one sentence description

spice seal
#

Ohk

turbid condor
#

And how much servers ot will be in? And amount of users

spice seal
#

Anyways anyone can help me with some code?

turbid condor
spice seal
#

I need a code where I have a file named BadWords.txt and the bot scans the message and if the message contains any word from the list(i used line by line for each word) it will delete it and dm a warning and also show a embed.

turbid condor
spice seal
turbid condor
#

Yeah and what have u wrote for the specific feature u mentioned above

#

We are not here to write your code just to help if you have an issue with your existing code

spice seal
spice seal
#

And it's not working AT ALL

turbid condor
#

Show us what u did

#

And any relevant error if you getting one in terminal

spice seal
#

Ok wait

#
        except discord.errors.Forbidden:
            print("I don't have permission to delete messages or send DMs.")

@bot.command()

async def hello(ctx):

    await ctx.send('Hello!')
#

Bruh i couldn't copy it

#

Wait

fast osprey
spice seal
fast osprey
#

Your bot can make automod rules yes

#

Which then discord takes the responsibility of processing

spice seal
spice seal
fast osprey
#

There's a good article from discord one sec

#

Basically anything a human could do to configure automod, a bot can as well

radiant summit
#

Hey folks, i need in help my bot development
DM pls if there is anyone to help with this project

remote reef
#

Does anyone mind helping me?

#

Please DM ME

fast osprey
#

For both folks, it's almost always better to get help in a public place where incorrect or bad answers can be reviewed by multiple people

latent pier
#

Is there way i can get emoji or emoji id from server which isn't into my bot guilds?

Answer - discord.PartialEmoji worked

slate swan
unkempt canyonBOT
slate swan
#

should use this one

fierce ridge
#
@bot.tree.command(name = 'give-file', description="Gimme The txt file")
@app_commands.describe(txt = "Txt")
async def say(interaction: discord.Interaction, txt: discord.Attachment):
    

    split_v1 = str(txt).split("filename='")[1]
    filename = str(split_v1).split("' ")[0]
    if filename.endswith(".txt"): # Checks if it is a .csv file
        await txt[0].save(fp="DISCORD BOT/{}".format(filename)) # saves the file
#

so im trying to download the file sent in /slash command and it gives an error

#
Traceback (most recent call last):
  File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\RedApple\Desktop\DISCORD BOT\bot.py", line 121, in say
IndexError: list index out of range

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\RedApple\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'give-file' raised an exception: IndexError: list index out of range
fierce ridge
#

thts the error

drifting arrow
#

range error \o/

fierce ridge
#

i just wanna download the file in bot.py folder

#

or change the txt file into a list

#

but downloading is better

drifting arrow
#

is 121 the filename?

#
    split_v1 = str(txt).split("filename='")[1]
    filename = str(split_v1).split("' ")[0]
``` this looks weird to me lol
fierce ridge
#

i searched google

#

no the file i gave was lol.txt

#

i replaced the message.attachment to file cuz thts the attachment

drifting arrow
#

Controversial opinion, but fuck stackoverflow

fierce ridge
#

lol

fierce ridge
#

tht error too

#
await save(fp, *, seek_begin=True, use_cached=False)
#

this

#

i prolly wrote it wrong can u show how to write ti

#

is it like py await file.save(fp, *, seek_begin=True, use_cached=False)

drifting arrow
#

hold up

fierce ridge
#

ight

#

btw no need to check if file is txt

drifting arrow
#

I wasnt putting checks in. just saving a simple file if it uploaded

#
    @app_commands.command(name="savefile", description="Saves a file!")
    async def savefile(self, interaction:discord.Interaction, file:discord.Attachment):
      await interaction.response.send_message("File attached!")
      print(file.filename)
      filepath = f"C:\\Users\\Declan\\Desktop\\discordbots\\testbot\\files\\{file.filename}"
      await file.save(fp=filepath)
#

so "file.filename" returns the files name, in my test I used an image called "cabeldrawer.jpg", it returned that.
The file path is where you want the file to be saved to. In this case locally to my code

#

as well as what to save it as

fierce ridge
#

Oh thx

gusty berry
#

how can i send an image? i'm using this format:

@client.tree.command(name="prof", description="Sends an image")
async def prof(interaction: Interaction):
    

    await interaction.response.send_message()
#

can i even send an image this way?

slate swan
#

yes, use the file argument

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
upbeat otter
gusty berry
#

ty

gusty berry
#

the animation is kind of outdated by now

upbeat otter
gusty berry
#

the code is never even run

#

am i missing an import?

viscid hornet
#

!traceback | whats the full traceback?

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

gusty berry
#

because i dont get any errors

#

in the terminal

#

nvm it just suddenly started working

viscid hornet
viscid hornet
gusty berry
#

idk

#

i did the same thing as i did before

wet orchid
#

Need help

gusty berry
#

how can i get a bot to join the vc and play some audio?

viscid hornet
viscid hornet
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

viscid hornet
#

damn hold on

#

!d discord.VoiceChannel

unkempt canyonBOT
#

class discord.VoiceChannel```
Represents a Discord guild voice channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
void mauve
#

So Im trying to make views persistent using data from Django ORM

class TicketBot(commands.AutoShardedBot, View):
    def __init__(
            self,
            initial_extensions: list[str],
            **kwargs,
    ):
        super().__init__(**kwargs)
        self.initial_extensions = initial_extensions
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

    def load_persisted_data(self):
        objects = PersistentView.objects.all()

        for obj in objects:
            print(f'adding {obj.guild_id}, {obj.channel_id}')
            self.add_view(CreateTicketView(obj.guild_id, obj.channel_id))
            print('view added!')
    
    async def on_ready(self):
        await self.change_presence(activity=discord.CustomActivity(name='👀 Watching Tickets'))

        print(f'{self.user.name} is ready')
        tracemalloc.start()

    async def setup_hook(self) -> None:
        for extension in self.initial_extensions:
            await self.load_extension(extension)

        self.executor.submit(self.load_persisted_data)

        print("Cog modules are ready")

    async def cleanup(self) -> None:
        print("Cleaning up...")
        await self.close()
        print("Clean up complete")

but it seems views are not properly added as view outputs nothing. Any ideas?

viscid hornet
#

!d discord.VoiceChannel.connect | @gusty berry

unkempt canyonBOT
#

await connect(*, timeout=30.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) to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states).
viscid hornet
void mauve
#

oh well, i mean i print out something by clicking the button in my view, but after restart it doesnt stay persistent and therefore there is no output
here is my view for clarification


def persist_view(guild_id, channel_id):
    PersistentView.objects.update_or_create(
        guild_id=guild_id,
        channel_id=channel_id,
    )

class CreateTicketButton(discord.ui.Button):
    def __init__(self, guild_id, channel_id):
        self.parser = JSONParser(guild_id, channel_id)

        super().__init__(
            label=self.parser.get_language(),
            style=discord.ButtonStyle.success,
            custom_id=f'persistent:create_ticket_{uuid4()}'
        )

    async def callback(self, interaction: Interaction[ClientT]) -> Any:
        print(f'Creating at {interaction.channel.name}!')


class CreateTicketView(discord.ui.View):
    def __init__(self, guild_id, channel_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.channel_id = channel_id
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        self.setup_view()
        self.add_item(CreateTicketButton(self.guild_id, self.channel_id))

    def setup_view(self):
        print('Setting up view!')
        self.executor.submit(persist_view, self.guild_id, self.channel_id)
ebon rampart
#

Well. I'm geting an issue like that
I literally tired every way it has to be easy to fix but I didn't find any solution I would be very happy if you help.

hushed galleon
viscid hornet
#

deprecated and replaced with regular dpy

hushed galleon
void mauve
ebon rampart
hushed galleon
#
class MyView(discord.ui.View):
    @discord.ui.button(..., custom_id="my-view:my-button")
    async def my_button(self, interaction, button): ...

    @discord.ui.select(..., custom_id="my-view:my-select")
    async def my_select(self, interaction, select): ...

bot = commands.Bot(...)
bot.add_view(MyView(), message_id=1234)
bot.add_view(MyView(), message_id=5678)``` here, both buttons/selects share the same custom ID but can be distinguished by the message they're attached to
void mauve
#

well how would I pass it to the view
the thing is I am creating that view from task

Here I use the view in the class where all the logic lays for creating ticket threads in a forum

And 2nd/3rd image is how my task executes it

hushed galleon
hushed galleon
#

oh, then create_thread() should have returned a tuple

charred sable
hushed galleon
void mauve
swift siren
#

!d user installed

unkempt canyonBOT
void mauve
#

i suppose something like this wont work

hushed galleon
void mauve
#

or i just send view separately?

hushed galleon
#

though your view doesn't really need the message ID

void mauve
#

well how do I add it to the db then? cuz im adding it to a database at the first time view is created

#

at the setup_view

class CreateTicketView(discord.ui.View):
    def __init__(self, guild_id, channel_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.channel_id = channel_id
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        self.setup_view()
        self.add_item(CreateTicketButton(self.guild_id, self.channel_id))

    def setup_view(self):
        print('Setting up view!')
        self.executor.submit(persist_view, self.guild_id, self.channel_id)
#

or I just add it beforehand?

charred sable
void mauve
wanton current
#

ChatGPT doesn't know shite about d.py

hushed galleon
void mauve
charred sable
#

i just began to coding discord bot for a month and im looking every source i foun

#

btw what can i do to make a window like the code i gave but it needs to work ofc ...

hushed galleon
# void mauve oh well, yeah that is kinda weird

i guess simplest option would be to add the message_id parameter to your setup_view() method, then only call it after you've sent your view: py view = CreateTicketView(...) thread, message = await forum.create_thread(..., view=view) view.setup_view(message.id) (might also be worth renaming it to .persist_view(message.id))

void mauve
swift siren
#

im trying to use user apps and when logging into my but it just gets stuck on shard validating

[2024-04-30 21:18:43] [INFO    ] discord.gateway: Shard ID 0 has connected to Gateway (Session ID: 4437c13a60e1848795783ca0d53527e4).
    @app_commands.command()
    @app_commands.allowed_installs(guilds=False, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def useable_only_users(interaction: discord.Interaction):
        await interaction.response.send_message("I am only be installed to users, but can be used anywhere.")
hushed galleon
hushed galleon
charred sable
#

ty maybe i will look back at this at the future

swift siren
#

forgot all about it the cog itself

latent pier
#

Is there anything to get sticker url like discord.Emoji.url

wanton current
#

!d discord.Asset

#

you can just do sticker.url

swift siren
#

me loving that ts still doesn't work m_joestandsad

latent pier
wanton current
#

elaborate

latent pier
#

Vice versa

latent pier
swift siren
#

half ass ss , mb

latent pier
swift siren
latent pier
wanton current
#

those are two different commands

swift siren
#

^^

latent pier
#

Sorry mb

swift siren
#

you're fine

latent pier
#

Anyone else having issue with logging in bot?

wanton current
#

have you set-up logging?

swift siren
#

nope , got done validating after like 5 minutes

#

sob

wanton current
#

aha nvm

#

yeah there's an issue rn

latent pier
#

Taking me 6-7 reconnects to login finally

swift siren
#

ye took a notice ever since logging in said it itself

#

discord ^^

void mauve
# hushed galleon i guess simplest option would be to add the message_id parameter to your setup_v...

if i understood correctly, i need to do something like this:

class CreateTicketView(discord.ui.View):
    def __init__(self, guild_id, channel_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id
        self.channel_id = channel_id
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

    def setup_view(self, message_id):
        print('Setting up view!')
        self.executor.submit(persist_view, self.guild_id, self.channel_id, message_id)
        self.add_item(CreateTicketButton(self.guild_id, self.channel_id, message_id))
    async def _create_products(self, channel: discord.ForumChannel):
        for product in self.data['products']:
            try:
                print(product)
                product_utils = self.ProductModeUtils(product)

                print(product_utils.title, product_utils.description)
                print(channel.type)

                view = CreateTicketView(self.data['guild'], channel.id)

                thread, message = await channel.create_thread(
                    name=product_utils.title,
                    embed=CreateEmbed(
                        title=product_utils.title,
                        description=product_utils.description
                    ),
                    view=view
                )

                view.setup_view(message.id)

but it doesn't add button item

latent pier
wanton current
#

tias

hushed galleon
#

oh wait, the add_item() call should be in init

#

the creation of your components should happen separately from the database persistence so you can skip the excess queries when you're re-adding your views at startup

latent pier
void mauve
# hushed galleon has the randomized custom ID been replaced in CreateTicketButton?

yeah

class CreateTicketButton(discord.ui.Button):
    def __init__(self, guild_id, channel_id, message_id):
        self.parser = JSONParser(guild_id, channel_id)

        super().__init__(
            label=self.parser.get_language(),
            style=discord.ButtonStyle.success,
            custom_id=f'persistent:{message_id}'
        )

    async def callback(self, interaction: Interaction[ClientT]) -> Any:
        print(f'Creating at {interaction.channel.name}!')

but back to the thing, if i keep it in __init__, how do I get message_id ?

hushed galleon
gusty berry
#

how can i make a discord bot run on a linux ubuntu server?

#

it is possible right?

hushed galleon
latent pier
hushed galleon
#

?

latent pier
#

I want to get sticker url like a partial emoji url

wanton current
gusty berry
wanton current
#

You could use something likd systemd, pm2, screen, etc.

gusty berry
#

i'll see if it works

hushed galleon
gusty berry
#

do you automatically get the active dev badge or do you have to apply to something?

latent pier
latent pier
gusty berry
#

yeah i got it

#

i have to wait what

#

24h?

latent pier
#

If you're using it now then you'll be eligible after 24H

gusty berry
#

i've been making bots for days i just didnt have my server as a community so i changed it like 2h ago

latent pier
#

Just visit website and it'll show your eligibility status

viscid hornet
latent pier
#

That means you were already eligible

viscid hornet
#

hasnt been used in 2 years

latent pier
viscid hornet
#

fair enough

swift siren
#
        @app_commands.command(name='avatar',description="view a user's avatar")
        @app_commands.describe(user_id="user id to avatar")
        async def avatar(interaction: Interaction, user_id: str = None):
            if user_id is None:
                user = interaction.user
            else:
                user = await interaction.client.fetch_user(user_id)
                embed = discord.Embed(title=f"{user.name}'s avatar",color=0xffffff)
            if user.avatar is not None:
                avatar_url = user.avatar.url
            else:
                avatar_url = user.default_avatar.url
            embed.set_image(url=avatar_url)
            await interaction.response.send_message(embed=embed)

latent pier
viscid hornet
viscid hornet
latent pier
#

You've associated it in else: only

latent pier
swift siren
#

oh wow

#

I love getting help from above average people

#

thanks you kissss

viscid hornet
gusty berry
#

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)
this is the command for joining a vc. idk how to check if the user is in a vc and how to feed this command which vc to join

viscid hornet
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
latent pier
unkempt canyonBOT
gusty berry
latent pier
latent pier
latent pier
#

You had to check it smh

viscid hornet
viscid hornet
latent pier
#

Better than yours

gusty berry
latent pier
gusty berry
#

oh its that simple

latent pier
#

Works

#

You can still pass other arguments

spice warren
#

Whilst Y'all are racing to "help" you're missing key information

latent pier
#

Enlighten me

spice warren
#

Member.voice is VoiceState | None, meaning it can be None, you'll need to check for that before trying to access .channel (which can also be None)

latent pier
#

I thought we were having heathy competition

spice warren
#

Server has strict rules against music bots like this btw

latent pier
spice warren
#

If I ping a mod they will?

latent pier
#

That could be my personal class too?

spice warren
#

Weird argument

latent pier
#

That's not the full code?

spice warren
#

Fam we all know what wavelink is

gusty berry
spice warren
#

That is one way, sure, yep

latent pier
#

I wouldn't like to take a exit from here

spice warren
#

This means they have a voice state in your cache, which likely means they're in a VC

latent pier
#

It's helpful for me

gusty berry
#

RuntimeError: PyNaCl library needed in order to use voice?

spice warren
#

Did you install your library with the voice addon? That is required and outlined in the "Getting Started" in the documentation

#

E.g.
python -m pip install -U "discord.py[voice]"

gusty berry
#

no... i didnt see any getting started in the docs

#

mb and thank you

latent pier
#

He could install pynacl instead

spice warren
#

The [voice] addon also handles shipping libopus so it should be used instead.

latent pier
#

Elaborate

#

Tf is shipping libopus

spice warren
#

It also installs a bundled version of libopus for you (for Windows users)

gusty berry
#

also every time i add a new command i have to kick the bot and add him back for it to update

latent pier
#

Mac user since birth
Nvm....

gusty berry
#

is there an easier way like to make it update in the code?

spice warren
#

"Kick it"?

#

Like from the server it's in...?

latent pier
spice warren
#

I don't recall asking you?

gusty berry
#

no

latent pier
#

That has no solution

spice warren
#

Please let OP speak.

gusty berry
#

i mean from the server. i use @client.tree.command(name="ping", description="Izpiše, koliko pinga ima bot.") for commands

spice warren
#

Ah you're syncing slash commands on startup

gusty berry
#

client = commands.Bot(command_prefix="$", intents = discord.Intents.all())

spice warren
#

You could make a sync command and do it that way, especially since syncing on startup can incur nasty ratelimits

gusty berry
#

so how should i go about it. idm rewriting the code

spice warren
#

I wrote something about this, one moment

#

There's also an example message command to make syncing easier

hushed galleon
spice warren
#

They're restarting every 20 seconds and syncing globally by the seems of it

#

Global syncing sure be a vicious ratelimit

gusty berry
spice warren
#

Not at all

#

Hence I said you should read the pages

#

They explain how this all works

gusty berry
#

...all of them?

spice warren
#

First being the important one about information and the second being example code

hushed galleon
spice warren
#

Just switching to a new channel and back works (sometimes) in that case

gusty berry
spice warren
#

But what I'm saying is, if they're restarting the bot all the time to update the code, but syncing globally in setup_hook or on_ready then it's gonna get hit by the mean ratelimit

#

Yeah the Rust book is dense

gusty berry
#

making a bot in rust is such a pain

spice warren
#

I tried writing this to be simple but convey the important stuff

gusty berry
#

bless you

#
@client.event
async def on_ready():
    await client.tree.sync()
    await client.change_presence(activity=discord.activity.Game(name="SimulIDE"))
    print(f"{client.user.name} je povezan!")
#

i've had client.tree.sync() there from the beginning but it never really did anything. i'm still not done reading so ig i'll understand later

gusty berry
#

💀 i just read it.

#

so i should just remove that line

spice warren
#

Only if you understand why and have an alternative

#

Like it's likely not gonna be an issue for a smalltime bot or anything, but since I tailored this to the average user I had to mention the issues

gusty berry
#

i'm assuming i'll get thought that in the 2nd document

#

an alternative

spice warren
#

The sync command example is just what I use and share with ppl in the dpy server to use since it covers most cases of use and is pretty user friendly

wanton current
#

when ?tag ass in here

spice warren
#

The brashness we use in dpy wouldn't fly here

wanton current
#

that's a new word

gusty berry
wanton current
#

yeah you can, they are for different situations

viscid hornet
#

@wanton current whats the thing for an app cmd tree?

wanton current
#

|| talking about umbras cmd ||

viscid hornet
wanton current
viscid hornet
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
viscid hornet
spice warren
#

A Snowflake is not an id

viscid hornet
#

lemme read up on snowflakes rq

#

do you have any good suggestions of where to read about them?

wanton current
spice warren
#

It's essentially anything in dpy with an .id attribute
But yeah that's the docs thanks willi

hushed galleon
spice warren
#

Even for global? I sync globally twice and my bot halts the command for like 5 minutes waiting for it

gusty berry
#
@client.command()
async def sync(ctx: commands.Context) -> None:        
    synced = await ctx.bot.tree.sync()
    await ctx.send(f"Synced {len(synced)} commands globally.")
#

well is there anything bad with this? i skipped like 90% of the code

rain hedge
#
@bot.listen()
async def on_member_update(before, after):
    staffrole = server.get_role(1155546749117669376)
    if staffrole in on_member_update(before, after):
        print("All staff have been assigned a team.")

don't know what I did wrong here

AttributeError: 'NoneType' object has no attribute 'get_role'

spice warren
#

This syncs globally, so all servers the bot is in will see it's defined global commands

#

Is it a multiguild bot?

gusty berry
#

no

spice warren
spice warren
rain hedge
#

ive set up a variable for it

hushed galleon
spice warren
rain hedge
#

does it need to be in the code?

#

the variable?

#

or can it be somewhere else

spice warren
#

You can't define it before the bot starts running, which I assume you have

#

Just use before.guild maybe? Since before is a Member object

rain hedge
#

i think i fixed it since im facing a new error

gusty berry
# spice warren Then you may just want non global commands and syncing
@client.command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}")

like this?

rain hedge
spice warren
#

Again there's a bunch of cruft you don't need here
The spec is unnecessary and the guilds parameter too

This is my fault for spoonfeeding you this code I'm sorry

spice warren
rain hedge
#

Im wanting the bot to check whenever someone in the guild receives 'staffrole'

spice warren
#

This is the correct event to do so but can you show the full code relating to this error?

rain hedge
#
@bot.listen()
async def on_member_update(before, after):
    server = bot.get_guild(1000824509869346827)
    staffrole = server.get_role(1155546749117669376)
    if staffrole in on_member_update(before, after):
        print("All staff have been assigned a team.")
stark pike
#

Hello Link can you help me ?

spice warren
#

Why are you calling the function defining this code?
You may just want to check if staffrole in after.roles: or even better, after.get_role(staff_role_id)

#

I can certainly try, just ask your question

stark pike
#

You know selenium ?

spice warren
#

This may be the wrong channel for that

stark pike
#

Yes i know but what is the channel ?

spice warren
#

sorry I don't know ¯_(ツ)_/¯

rain hedge
spice warren
#

Try it :)

rain hedge
#

it works

#

thank you very much

spice warren
#

Okay now

#

You're gonna notice small problems

rain hedge
#

such as?

spice warren
#

This just means someone with the staff role did any kind of update to their member

What you can do is add an and to this if and check that staffrole not in before.roles

hushed galleon
gusty berry
#

i changed 1 command from n4 to join and even tho i used $sync and $sync ~ the /join command still wont appear and the /n4 is still there?

hushed galleon
rain hedge
wanton current
#

in the same if statement

swift siren
#

i’m going to make a antinuke module in for user apps wish me gl

spice warren
rain hedge
spice warren
#

Glad I could help

rain hedge
wanton current
#

ask away

rain hedge
#

I need this same command to assign a role to the member that received the staffrole and for it to rotate between 5 roles each time

gusty berry
#

async def leave(interaction: Interaction):
member = interaction.user
this is how i get member to equal the user's id. how can i make member equal the bot's id?

hushed galleon
rain hedge
#
@bot.listen()
async def on_member_update(before, after):
    server = bot.get_guild(1000824509869346827)
    staffrole = server.get_role(1155546749117669376)
    if staffrole not in before.roles and staffrole in after.roles:
        print("Staff member has been assigned a team.")

how would I check which user it was the staffrole was assigned to?

wanton current
#

before or after

#

they are both member objects

rain hedge
latent pier
#

How can i check for emojis in discord.Message?

pale zenith
#

For discord emojis, you'd look through the content using an emoji regex, like <a?:(?P<name>[a-zA-Z0-9_]{2,32}):(?P<id>\d+)>

latent pier
#

No other way?

#

Like we check mentions?

hardy lily
#

.

pale zenith
latent pier
#

Use bin

hardy lily
#

how

pale zenith
#

for unicode emoji, Good luck. But look into

#

!pypi emoji

unkempt canyonBOT
latent pier
#

Not Unicode i want PartialEmoji

hardy lily
#

binhelp

latent pier
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hardy lily
fast osprey
#

You can only respond once. If you need to defer, you should use interaction.followup.send after that

finite pagoda
#
@bot.tree.command(name='perfil', description='Olhe seu perfil')
async def estatisticas(interact: discord.Interaction):
    name = interact.user.name
    user = interact.user
    fundo = Image.open("per.png")
    tet = Image.open("tet.png")

    imagem1 = await user.avatar.read()
    icone = Image.open(io.BytesIO(imagem1))
    icone = icone.resize((600, 600))

    tet_resized = tet.resize(icone.size)
    tet_mask = tet_resized.convert("L")
    icone.putalpha(tet_mask)

    capa = Image.new("RGBA", (1800, 670), (0, 0, 0, 0))
    capa.paste(fundo, (0,0))
    capa.paste(icone, (100, 140))

    draw = ImageDraw.Draw(capa)
    fonte = ImageFont.truetype("RobotoMono-Bold.ttf", 20)
    draw.text((275, 250), f"{name}", font=fonte)

    buffer = io.BytesIO()
    capa.save(buffer, format="PNG")
    buffer.seek(0)

    await interact.response.send_message(file=discord.File(fp=buffer, filename="perfil.png"))```
#

Why does a png square appear around the circle?

finite pagoda
#

I just wanted the avatar to be in the shape of a circle, I didn't think it would be so complicated...😭

naive briar
unkempt canyonBOT
#

Image.paste(im, box=None, mask=None) → None```
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See [Coordinate System](https://pillow.readthedocs.io/en/stable/handbook/concepts.html#coordinate-system). If a 4-tuple is given, the size of the pasted image must match the size of the region.

If the modes don’t match, the pasted image is converted to the mode of this image (see the [`convert()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert) method for details).

Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module.
hardy lily
#

am I using bot correctly for user apps?

class Main:
    def __init__(self, registrate: CommandRegistrate, bot):
        self.bot = bot
        self.session_manager = SessionManager()

                        interaction = await self.bot.wait_for("interaction", check=lambda i: i.message.id == follow_up_message.id and i.user.id == interaction.user.id, timeout=60)
finite pagoda
latent pier
#

How can i upload emoji/sticker using https://cdn.discordapp.com/stickers/1175496747712249927.png format

tulip ice
#

is there way to have sub choices for slash command? so i select choice and new choices related to that choice will appear?

hushed galleon
#

dpy's sticker objects also have a read method, but its not documented for some reason... you might find that easier to work with but it requires an extra http request: py sticker = await client.fetch_sticker(...) image_bytes = await sticker.read()

hushed galleon
tulip ice
#

so choices

hushed galleon
#

neither support sub options, but in the case of slash commands you could theoretically return different autocompletion options based on what they selected in a previous option

tulip ice
#

that actually possible?

hushed galleon
#

i think it might look something like:
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Command.autocomplete
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction.namespace ```py
@bot.tree.command()
async def pet(interaction, genus: Literal["Feline", "Canine"], breed: str):
await interaction.response.send_message(f"Details for {breed}: ...")

@pet.autocomplete("breed")
async def pet_autocomplete_species(interaction, breed: str):
genus: str = interaction.namespace.genus
if genus == "":
return [Choice(name="Please select a genus!", value="no-choice")]
elif genus == "Feline":
breeds = ["Ragdoll", "Persian", "Bengal"]
else:
breeds = ["Labrador", "Pug", "Dalmatian"]
return [Choice(name=breed, value=breed) for breed in breeds]```

#

cant recall if genus would get set to an empty string or None if the user were to try typing in the breed before the genus...

finite pagoda
tulip ice
# hushed galleon i think it might look something like: <https://discordpy.readthedocs.io/en/stabl...

i tried what you got there but didn't work, so I tried their example:

@app_commands.command(name="fruits", description="Get information about a fruit")
async def fruits(interaction: discord.Interaction, fruit: str):
    await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')

@fruits.autocomplete(name="fruit")
async def fruits_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> typing.List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower()
    ]

but it say this:

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.new_command' raised an error: TypeError: unknown parameter: 'fruit'
hushed galleon
tulip ice
hushed galleon
#

does your command have a fruit parameter?

hushed galleon
#

both methods would be missing self in that context