#discord-bots

1 messages ยท Page 153 of 1

slate swan
#

voice = ctx.author.voice

#

code:

async def onegai(ctx: commands.Context, channel_id):
    vc = discord.VoiceClient(bot, channel_id)
    vc.connect()
    vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
    while vc.is_playing():
        await asyncio.sleep(.1)
    await vc.disconnect()
    await ctx.respond("Please pound me more with you ")```
error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: VoiceClient.connect() missing 2 required keyword-only arguments: 'reconnect' and 'timeout'
#

xd

#

or actually use a discord.VoiceaChannel typehint

slate swan
#

alternatively you can do

channel_id = int(chanel_id)
slate swan
slate swan
#

skill issue

slate swan
#

hm cool

#

kind of knew that ๐Ÿ’€

slate swan
#

vc = await voice.channel.connect()

#

vc.channel.connect according to pycord docs

#

its coro btw

slate swan
#

from here ^

slate swan
slate swan
#

new code:

@bot.slash_command(description='Joins Voice Channel And Play Onegai Sound Effect')
async def onegai(ctx: commands.Context, channel_id):
    channel_id = int(channel_id)
    voice_channel = bot.get_channel(channel_id)
    vc = voice_channel.connect()
    vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
    while vc.is_playing():
        await asyncio.sleep(.1)
    await vc.disconnect()
    await ctx.respond("Please pound me more with you ")```
new error:
    vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
AttributeError: 'coroutine' object has no attribute 'play'
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
#

it's coro ๐Ÿคท

#

altho

slate swan
#

you didn't await the connect thing

#

ohh

#

it's maybe voice_channel.play

#

i think xd

slate swan
slate swan
slate swan
#

imagine creating own wrapper and customize it as u wish looks cool

slate swan
slate swan
slate swan
slate swan
#

there's a todo for things easier than you can imagine

#

and im too lazy for them

#

IS THERE 2 + 2?

#

as easy yeah

#

;-;

#

cul

#

but 2+2 = 5 so hard ;-;

#

what, its 22

#

altho in my higher math exam i kinda fked up in the calculation
9+3-2=10 right but i was kept thinking 11 kinda bruh

#

then after a lot of big brain using real cal culator i realized it's 10 ๐Ÿ’€

#

ike wtf

slate swan
#

carry a python with you at exams so you can do basic maths calc using it

slate swan
#

maybe i should Peepo_Shrug

slate swan
#

can someone tell me who is coro?

#

now tell me how to contribute smirk2

slate swan
slate swan
slate swan
#

async =await

slate swan
slate swan
#

i only know how to serch stuff and how to steal imean learn

slate swan
#

search*

#

i can teach you if you wanna learn

slate swan
#

or vscode makes it easier

slate swan
slate swan
#

but win 7 doesnt support py ;[

#

await voice_channel.connect()

slate swan
slate swan
slate swan
slate swan
#

hmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

slate swan
# slate swan this ^

now it joins vc which is nice but no sound and giving error of this
await vc.play(discord.FFmpegPCMAudio("./sounds/onegai.mp3"))
AttributeError: 'VoiceChannel' object has no attribute 'play'

slate swan
#

@slate swan

#

;]

slate swan
#

I need help in css

proud apex
#

How to make different time for cooldown for each person using database, for example one user has 20 minutes, another 25?

slate swan
#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
regal cove
#

what do you use instead of "ctx" when using slash commands?

brazen raft
#

interaction

regal cove
rare echo
#

interaction.user

brazen raft
#

They don't have the exact same attributes and methods

timid spade
#

where can i make the list of options?

slate swan
#

guys I need help asap

stone quest
#

what

slate swan
#

bot = commands.Bot(help_command=None, command_prefix="2?", intents=discord.Intents.all())

#

I did this but it still doesn't remove the help cmd and I keep getting error

discord.ext.commands.errors.CommandRegistrationError: The alias help is already an existing command or alias.

stone quest
#

you have two help command ssomewhere

#

or two help functions

slate swan
#

how do I disable that?

stone quest
#

youve done it right, with help_command=None

slate swan
stone quest
#

show full code?

slate swan
#
async def help(ctx):
  HelpEmbed = discord.Embed(title="Here are all the commands", color=0x2ecc71)
  HelpEmbed.add_field(name="Basic Predictor Commands", value="2?towers, 2?crash, 2?casemode (casemode is just for fun")
  HelpEmbed.add_field(name="Premium Predictor", value="everything from basic predicator and 2?mines + 2?bloxflip.")```
stone quest
#

remove the aliases=[]

slate swan
#

OH THAT

stone quest
#

function name defined the command as help

slate swan
#

IM SO DUMB

#

ok I changed it to a capital letter, now it works. thanks

stone quest
#

you dont need to do that

#

bot = commands.Bot(help_command=None, command_prefix="2?", intents=discord.Intents.all(), case_insensitive=True)

#

you can use that instead

#

!e discord.ext.commands.Bot

unkempt canyonBOT
#

@stone quest :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'discord' is not defined
stone quest
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
rare echo
stone quest
#

@rare echoyooo

regal cove
#

what does this error mean?

  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'claim' raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
vale wing
#

!paste also use this

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.

regal cove
# vale wing Not full tb

this is the full tb

  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 490, in pay
    await cursor.execute("SELECT user_name FROM claim_data1 WHERE user_id = ?", (USER_ID,))
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
    result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

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

Traceback (most recent call last):
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/modern-economy-bot-3/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'claim' raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
vale wing
#

What's type of user_id col in db and what it is in USER_ID?

regal cove
vale wing
#

I asked about their types

regal cove
cloud dawn
#

Why would you save a username in a database?

vale wing
#

@regal cove send me CREATE TABLE instruction for that table and print(type(USER_ID))

regal cove
cloud dawn
#

I mean it adds a lot of variables, for instance, what if I change my username?

#

If he/she is in 2 servers with a custom username, what will it use?

regal cove
cloud dawn
#

num? is the pk ๐Ÿ‘€ hmmmmmmmmmmmmmmmmmm

regal cove
cloud dawn
#

True, but still you can change the username.

regal cove
#

i will do that but i just wanna solve the error first

cloud dawn
#

Also consider using user_id as pk since that is unique.

vale wing
#

I need the signature

#

K nvm

#

It probably doesn't support aiosqlite docs

cloud dawn
#

Lol

regal cove
#

alright

vale wing
#

@regal cove and what about USER_ID type

regal cove
#

i will double check that hold on

vale wing
#

Print it anyway

slate swan
#

BIGINT ๐Ÿ—ฟ

cloud dawn
slate swan
#

hm lemme check

cloud dawn
#

263 - 1

vale wing
#

In sqlite there's no such thing as explicit BIGINT, it automatically expands the INTEGER field size if needed iirc

cloud dawn
#

2 to the power of 63

regal cove
#

i believe i forgot to convert USER_ID to int

cloud dawn
#

9223372036854775807

vale wing
cloud dawn
vale wing
#

Where does USER_ID even come from

cloud dawn
#

Placing the user.id as pk is always unique

regal cove
#

so i cant use ctx

vale wing
#

So what

cloud dawn
#

interaction.user.id

regal cove
#

ctx just doesnt work with slash commands

cloud dawn
#

Same stuff.

cloud dawn
vale wing
#

As long as it's instance of Interaction everything will be working

regal cove
#

oh i understand

#

bruh i could probably have done what you said but now i've edited so much of my code its easier to just let it stay that way

vale wing
#

Nah better to name it inter/interaction cause good practice

upbeat otter
cloud dawn
#

I guess you could use discord.ext.commands.Bot.get_context and make a custom context to add database support and have really clean commands but eh, clean AND useful, let's not...

cloud dawn
upbeat otter
#

I mean

cloud dawn
#

no

upbeat otter
#

๐Ÿ’€

regal cove
#

thank you guys

upbeat otter
#

frustration or wot ๐Ÿ’€

regal cove
#

i now know what mistake i made. the problem was that i did interaction.user instead of interaction.user.id

vale wing
#

๐Ÿ˜ฑ

cloud dawn
#

repr be like hm yes

#

I guess you could make it cursed like that.

meager chasm
#

do you know what IndexError is

timid spade
#

can someone help me with making persistent views for select menues

#

can you tell me if i did something wrong by looking at my code? i will send you my code in dm

regal cove
#

how do you delete a message when using slash commands

timid spade
#

i dmed you
check your messages requests maybe

#

for the decorator's option argument
i am using a for loop to append select options in the list
but i cant figure out where to run the loop

#

like in discord.ui.Select class i ran the loop after super() to append options

cloud dawn
#

You got custom id's so the view can never be persistent.

vale wing
cloud dawn
#

No the opposite.

#

I mean you can if you use raw requests but it's meant so that you can't have conflicting stuff happening.

ancient glen
#

Hi, any of you guys good with discord bot developing? Like actually good

cloud dawn
ancient glen
#

the question is long

#

i just wanna say im an amateur that is looking to get something done with the help of someone

#

the plan is big

cloud dawn
#

Okay, people are here to help with problems etc. but we aren't providing any kind of "assistance", you do still need to code it yourself. Sometimes we do provide small examples.

ancient glen
#

Any of you guys good with discord bot developing?

cloud dawn
#

Like I said above, you will most likely not get a different answer. Just ask the question.

ancient glen
#

Okay then and I'm gonna specify the question.

#

I need a python bot that runs on discord and has different commands users can use. That bot needs to log in a users instagram's account feed, give the user an option to fill the password area, username 2-fa etc. and when it logs into the instagram, user can choose a refresh second interval from 1-10seconds. The bot then needs to refresh the instagram feed based on the interval the user chooses and everytime there is a less than 60 seconds old post it needs to comment one of the comments we set on the comment list and many other features.

#

A friend of mine send me a 'skeleton' or like asample of that code but I need to work on it with someone. This plan

#

is really big trust me

fading marlin
#

Instagram userbots are surely against TOS

ancient glen
#

But it is not an instagram userbot

fading marlin
#

log in a users instagram's account feed, give the user an option to fill the password area, username 2-fa etc. and when it logs into the instagram
is it not? ๐Ÿค”

timid spade
ancient glen
#

on new posts

#

Like there is no botted comment likes, no botted coments it's just self promoting the account

#

You've seen many memepages do it on comment sections

fading marlin
cloud dawn
fading marlin
#

yeah no, you're not gonna get any help on that here

cloud dawn
timid spade
#

i am confused

cloud dawn
timid spade
cloud dawn
#

yep

timid spade
#
class Role_Select(discord.ui.Select):
    
        
    def __init__(self, ctx, roles_list):
        options = []
        super().__init__(max_values= max_val,min_values=min_val, options=options)# -> options
        options = []
        for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)
                self.append_option( discord.SelectOption(label=role.name))
                options.append(discord.SelectOption(label=role.name))      

    
 
    async def callback(self, interaction: discord.Interaction):
        
        roles = []
        for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)   
                roles.append(role.name)
        
        user = interaction.user
        await interaction.response.send_message("๐Ÿ”ƒ Thinking....", ephemeral = True)
        await interaction.delete_original_response()
        for item in roles:
            role = get(ctx.guild.roles, name= item)
            if item in self.values and role not in user.roles:
                await user.add_roles(role)

                
            elif role in user.roles and item not in self.values:
                await user.remove_roles(role)



Options = []
class DropdownSelectView(discord.ui.View):
    
    
    
    def __init__(self):
        super().__init__(timeout= None)
        self.add_item(Role_Select(ctx, roles_list))
        for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)
                Options.append(discord.SelectOption(label=role.name))   
        
    @discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
    
    async def select_callback(self, interaction: discord.Interaction, select):
        
        roles = []
        for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)   
                roles.append(role.name)
        
        user = interaction.user
        await interaction.response.send_message("๐Ÿ”ƒ Thinking....", ephemeral = True)
        await interaction.delete_original_response()
        for item in roles:
            role = get(ctx.guild.roles, name= item)
            if item in select.values and role not in user.roles:
                await user.add_roles(role)

                
            elif role in user.roles and item not in select.values:
                await user.remove_roles(role)
#

can someone tell why its still not persistent

fading marlin
#

you don't seem to be adding any custom IDs. Your Options list should be inside the class (as a class variable)

timid spade
fading marlin
cloud dawn
unkempt canyonBOT
#

is_persistent()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.11)"): Whether the view is set up as persistent.

A persistent view has all their components with a set `custom_id` and a [`timeout`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.timeout "discord.ui.View.timeout") set to `None`.
cloud dawn
#

set custom_id ahh, who wrote this anyways?

#

๐Ÿ‘€

fading marlin
#

๐Ÿคท

fading marlin
timid spade
#

so i should set custom id or not? Pepe_dua

fading marlin
#

You should set them, yes

timid spade
#
class DropdownSelectView(discord.ui.View):
    
    def __init__(self):
        super().__init__(timeout= None)
        self.add_item(Role_Select(ctx, roles_list))
           
        
    @discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
    
    Options = []
    for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)
                Options.append(discord.SelectOption(label=role.name))
timid spade
fading marlin
#

You'd typically set class variables after you define the class' name

#

So, above __init__

timid spade
#

and loop too
above init?

fading marlin
#

No, your loop should stay where it previously was (inside the constructor), the select decorator should be above the select's callback, and Options should be in between the class definition and __init__. You can also set the options before you instantiate the super class

timid spade
#
class DropdownSelectView(discord.ui.View):
    Options = []
    
    def __init__(self):
        for item in roles_list:
            if isinstance(item, int):
                role = get(ctx.guild.roles, id=item)
                self.Options.append(discord.SelectOption(label=role.name))
        super().__init__(timeout= None)
        self.add_item(Role_Select(ctx, roles_list))
           
        
    @discord.ui.select(max_values= max_val,min_values=min_val, options= Options)
    
    

    async def select_callback(self, interaction: discord.Interaction, select):
#

like this?

fading marlin
#

Well, roles_list isn't defined anywhere lemon_glass but sure

timid spade
fading marlin
#

Anyway, tias ig

timid spade
#

i am getting 2 drop down menus

fading marlin
#

Yup
self.add_item(...) -> Adds a new component to the view
@discord.ui.select(...) -> Also adds a new component to the view

timid spade
#

imma remove self.add_item
will it fix?

fading marlin
#

sure

timid spade
#

well
working fine but not after restart
means still not persistent

fading marlin
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @timid spade until <t:1670771135:f> (10 minutes) (reason: newlines rule: sent 104 newlines in 10s).

The <@&831776746206265384> have been alerted for review.

fading marlin
#

yikes

tall dust
#

!unmute 764775571833749519

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @timid spade.

timid spade
#

thanks

winged coral
#

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

slate swan
naive briar
#

Where specifically

slate swan
#

when i run it

naive briar
#

The way they generate a random string is funny

fading marlin
#

ew

slate swan
#

so it does nothing?

fading marlin
#

it's a sync API wrapper of some sorts?

#

is this for selfbotting?

slate swan
#

idk i got it from google but cant remember where

naive briar
#

Probably for spamming message to a channel ducky_regal

naive briar
slate swan
fading marlin
#

Discord account automation

slate swan
#

it steals? like a tokenlogger?

fading marlin
#

no, it automates stuff on your Discord account, it's also against TOS

slate swan
#

ok thanks

#

but is it alright for bots?

fading marlin
#

sure, but use a good API wrapper like discord.py if you want to code Discord bots

slate swan
#

ok thank you

regal cove
#

why does this only dump one person in the json file?

@tree.command(name = 'initiate_bans', description='This will activate the economic ban system') 
async def ban_all_members(interaction: discord.Interaction):
  if interaction.user.id == (767636284083666971):
    await interaction.response.send_message("Bans have been initiated", ephemeral = True)
    ban_list = {}
    
    for guild in client.guilds:
        for member in guild.members:
            ban_list[member.id] = ban_balance
    print(ban_list)
    print(interaction.user.id)
    with open("ban_data.json", "w") as outfile:
        json.dump(ban_list, outfile)
  else: interaction.response.send_message("Sorry but you dont have permission to perform this command.")
fading marlin
#

what does ban_list print out as?

#

consider using an actual db instead of a json file too

regal cove
winged coral
#

"w" mode puts the cursor at the start of the file

#

When you write to it it's gonna overwrite whatever is already in there

#

You should be

  1. read json file into dictionary
  2. update dictionary
  3. dump dictionary into json file
#

Oh nvm you mean you want that to happen but only 1 guild member is dumped?

cloud dawn
eager hill
#
@bot.tree.context_menu("whothis")
async def whothis(interaction: discord.Interaction, member: discord.Member):
    embed = discord.Embed(title=f"{member.name}#{member.discriminator}", description=f"ID: {member.id}")
    embed.add_field(name="Joined", value=member.joined_at.strftime("%a, %d %b %Y %I:%M %p UTC"), inline=False)
    embed.add_field(name="Roles", value=", ".join([role.mention for role in member.roles]), inline=False)
    embed.add_field(name="Badges", value=", ".join([badge.name for badge in member.public_flags.all()]), inline=False)
    embed.set_thumbnail(url=member.avatar_url)
    await interaction.response.send_message(embed=embed, ephemeral=True)

I get the error ```py
CommandTree.context_menu() takes 1 positional argument but 2 were given

#

why

fading marlin
#

!d discord.app_commands.CommandTree.context_menu

unkempt canyonBOT
#

@context_menu(*, name=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command context menu from a regular function directly under this tree.

This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User"), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message"), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.11)") of `Member` and `User` as its second parameter.

Examples...
fading marlin
#

All arguments are keyword only

eager hill
#

?

#

oh

fading marlin
#

You don't have to add a name if it's gonna be the same as the function's name either

eager hill
#

thanks man

cloud dawn
#

Does look better with it tough.

regal cove
cloud dawn
#

But why is the function called ban_all_members?? @regal cove

regal cove
#

its a feature that will allow the user to ban people from my economy system

cloud dawn
regal cove
eager hill
regal cove
#

and then if ban_balance is == 1 the bot wont allow you to use its economy commands

cloud dawn
cloud dawn
eager hill
regal cove
#

but does that actually change anything? the ban command used to work but when i migrated it to using slash commands it stopped working

cloud dawn
# regal cove because i didnt think of that lol

Then you could have a structure like json { "267624335836053506": [767636284083666971, 169790484594556928], "336642139381301249": [427969521152950284] } string being the guild id and the ones in the list being banned users.

slate swan
#

hello, could someone help me figure this out, im trying to display a users banner

@bot.command(aliases=['bann', 'bn'])
async def banner(ctx, *, member: discord.Member = None):
    user = discord.Member
    member = await bot.fetch_user(user.id)
    if not member:
        member = ctx.message.author
    banner_url = member.banner.url
    em = discord.Embed(color = discord.Color.from_rgb(0, 0, 0), title = "avatar link", url=banner_url)
    em.set_image(url=f"{banner_url}")
    em.set_author(name=f"{member}", icon_url=f"{banner_url}")
    em.set_footer(text=f'Requested by {ctx.message.author}', icon_url=f"{ctx.author.banner_url}")
    await ctx.reply(embed=em)
#

i dont think i can do it as easily as with an avatar

#
@bot.command(aliases=['av', 'pfp'])
async def avatar(ctx, *, member: discord.Member = None):
    if not member:
        member = ctx.message.author
    userAvatar = member.display_avatar.url
    em = discord.Embed(color = discord.Color.from_rgb(0, 0, 0), title = "avatar link", url=userAvatar)
    em.set_image(url=f"{userAvatar}")
    em.set_author(name=f"{member}", icon_url=f"{userAvatar}")
    em.set_footer(text=f'Requested by {ctx.message.author}', icon_url=f"{ctx.author.avatar.url}")
    await ctx.reply(embed=em)

where this worked fine

regal cove
cold sonnet
#
    member = await bot.fetch_user(user.id)```please remove these lines completely
cloud dawn
slate swan
#

still dont know how to get a users banner tho

regal cove
#

why did that get deleted?

cloud dawn
cloud dawn
#

Just don't use underscores that's old code.

honest shoal
#

how ๐Ÿ˜ง

AttributeError: 'Member' object has no attribute 'add__roles'```
slate swan
cloud dawn
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.

honest shoal
#

LOL, I thought fonts were wide on console

slate swan
eager hill
#

hes the goat

slate swan
eager hill
#

is there any way my bot could run a / command upon a keyword in chat?

#

like the only solution i found was to do

@bot.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')
    if message.author == bot.user:
        return
    if message.channel.name == "general":
        if "release" in user_message.lower():
            await message.channel.send_message(f'run /faq')

but i would rather have it run the / command instead of telling the user to run it yk?

cloud dawn
#

The command has to be a hybrid command or message command.

#

!d discord.ext.commands.Bot.get_context then get the context

unkempt canyonBOT
#

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

Returns the invocation context from the message or interaction.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

Note

In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
cloud dawn
#

!d discord.ext.commands.Context.invoke then invoke

unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
eager hill
#

faq is the command im trying to use

slate swan
slate swan
#

if u figure it out please show me

untold bay
#

Can someone show me an example of a properly initialized client = discord.Client() please?

cloud dawn
#

Rough estimation since no clue how hybrid commands react to this.

cloud dawn
dense merlin
#

syntax error, need help
The function
@tree.command(name = "username", description = "Generate a random Username")
async def username(interaction):
#code here

The error

async def username(interaction):
^
SyntaxError: invalid syntax

Info:
Visual Studio Code Insiders, 3.8.2 64 bit python, Code Runner

eager hill
# cloud dawn ```py if "release" in user_message.lower(): ctx = await bot.get_context(mess...
@bot.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')
    if message.author == bot.user:
        return
    if message.channel.name == "general":
        if "release" in user_message.lower():
            ctx = await bot.get_context(message)
            await ctx.invoke(discord.utils.find(lambda m: m.name == "faq", bot.commands))

heres the entire code in case.
but im getting an error saying TypeError: 'NoneType' object is not callable

cloud dawn
# untold bay Can someone show me an example of a properly initialized `client = discord.Clien...
import asyncio
from discord import AutoShardedClient, Intents


class MyClient(AutoShardedClient):
    def __init__(self) -> None:
        super().__init__(intents=Intents.none())

    async def setup_hook(self) -> None:
        print("Setup hook")

    @staticmethod
    async def on_ready() -> None:
        print("Ready!")


async def main() -> None:
    client = MyClient()

    async with client:
        await client.start("token")

if __name__ == "__main__":
    asyncio.run(main())
``` This is a barebone setup
cloud dawn
cold sonnet
#

no intents

#

opp

cloud dawn
#

If you are making a slash command bot you don't need any intents in fact to make it work.

untold bay
dense merlin
cold sonnet
#

holy

#

this reminds me of that calculator

dense merlin
#

@cloud dawn

cloud dawn
#

What is above this function? Issue may be there.

#

Blank if or blank for usually does this

dense merlin
unkempt canyonBOT
#

Hey @untold bay!

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

dense merlin
#

@cloud dawn

slate swan
#

guys i am losing my mind

cloud dawn
# dense merlin

I don't see anything wrong.. could you maybe copy the decorator and the async def line? Not the whole function just that. And paste it here?

slate swan
#

can someone help me with a command thats like an avatar one but with peoples banners

dense merlin
eager hill
#

i give up on hybrid commands

untold bay
cloud dawn
dense merlin
cold sonnet
#

then that won't help

dense merlin
#

but ill try

cloud dawn
cloud dawn
dense merlin
cloud dawn
eager hill
#
if message.channel.name == "general":
        if "release" in user_message.lower():
            # empherial message
            await message.channel.send("run / faq", ephemeral=True)

now im trying to make this message emphemeral and i get TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'

naive briar
#

Only interaction can send ephemeral messages

cloud dawn
eager hill
# naive briar Only interaction can send ephemeral messages

yeah i figure, how can i make this ```py
@bot.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == bot.user:
return
if message.channel.name == "general":
if "release" in user_message.lower():
# empherial message
await message.channel.send("run / faq", ephemeral=True)

an interaction
naive briar
#

Make a slash command probably

cloud dawn
naive briar
#

Or just DM the user

eager hill
#

unfortunate

#

thanks for the help

dense merlin
cloud dawn
dense merlin
#

so not sure

cloud dawn
#

I meant the bot.

dense merlin
#

149

untold bay
untold bay
white citrus
#
            case "show":
                log_finder = {"_id": inter.guild.id}
        
                log_check = await inter.client.settings.find(log_finder)
                print(log_check)
                                        
                if log_check is not None:
                    if "log_id" in log_finder:
                        print("log_id passed")
                        try:
                            print("try passed")
                            log = inter.guild.get_channel(int(log_check['log_id']))
                            embed1 = nextcord.Embed(title=f"{config.DiscordOwnerBadget} Log Channel",
                                                description=f"<#{log.id}>\n `ID: {log.id}`",
                                                colour=config.blurple)
                            
                            await inter.response.send_message(embed=embed1, ephemeral=True)
                        
                        except (nextcord.NotFound, KeyError):
                            await inter.response.send_message(embed=deletet_channel_info, ephemeral=True)
                    
                    else:
                        embedc = nextcord.Embed(title=f"{config.DiscordError} No Log Channel found!", description=f"I could not find any Log Channel for `{inter.guild.name}`",
                                                colour=config.red)
                        await inter.response.send_message(embed=embedc, ephemeral=True)
                    
                if log_check is None:
                    error = nextcord.Embed(title=f"{config.DiscordError} This guild has no log channel.", description="Please add a log channel",
                                        colour=config.red)
                    await inter.response.send_message(embed=error, ephemeral=True)   ```
#

He is always jumping to py if log_check is None: but log_check is not None

log_check = {'_id': 900100165397008465, 'global_id': 1049656196233175060, 'admin_id': 1026839897782366258, 'log_id': 1013596038071853157}

untold bay
cloud dawn
#

You are being ratelimited.

dense merlin
#

what this mean

#
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')]

Im on vs cod

dense merlin
#

@cloud dawn

untold bay
sick birch
#

You've been basically blocked from discord

dense merlin
#

yes i am

sick birch
#

I'll take that as a yes..?

untold bay
#

I see...

sick birch
# dense merlin yes i am

Go into your "Python" folder in your Applications folder, and double click the "Install Certificates" or w/e it's called

shrewd apex
#

u need to manually install the certificates iirc

dense merlin
sick birch
#

Open up Finder

#

Click on "Applications" on the left bar

#

You should see a "Python" folder in there

#

Inside the "Python" folder there should be a file called something like "Install Certificates"
Double click on that to run it

dense merlin
#

ok thank

#

still no work

#

ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/certifi-2022.12.7.dist-info'
Consider using the --user option or check the permissions.

#

@sick birch \

shrewd apex
#

run as administrator if thats a thing

sick birch
#

I'm not much help with MacOS but maybe try with sudo or elevated privledges

dense merlin
#

k

#

ima try it now

#

!load_dotenv

cloud dawn
#

Yes.

#

!d discord.ext.commands.UserConverter

unkempt canyonBOT
#

class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

All lookups are via the global user cache.

The lookup strategy is as follows (in order)...
cloud dawn
#

If this is in a command it can be even simpler by just type hinting it.

#

async def test(ctx: Context, user: discord.User) -> None:

#

user will auto convert using the user converter using the same lookup strategy.

eager hill
#
if user_message.lower() == 'coinflip':
            variables = ['heads', 'tails']
            await message.channel.send(random.choice(variables))

the code runs fine but when i say coinflip it only says heads, so how can i get it to update while its running

umbral pewter
#

using discord.py anyone know why my command isnt working?

# Initalizing bot commands
bot = commands.Bot(command_prefix="?", intents = discord.Intents.all(), activity=discord.Game('Baking a pie!'))

@bot.command()
async def hello(ctx):
    await ctx.send("Hello!")

theres more to it of course, but these are the parts I think are relevent

torn sail
#

Move the defer to above the purge

slate swan
#

Hello!

I am making a tickets bot for a friend and was wondering how to do something

code:

                guild = ctx.guild
                adm = guild.get_role(ADMIN_ROLE_ID)
                ownr = guild.get_role(OWNER_ROLE_ID)
                ticket_owner = inter.user
                if select.values[0] == "P":
                    ticket = await guild.create_text_channel(name=f"ticket-{ticket_owner}-purchase")
                    start_time = datetime.now()
                    await ticket.set_permissions(ticket_owner, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
                    await ticket.set_permissions(adm, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
                    await ticket.set_permissions(ownr, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
                    await ticket.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False, view_channel=False)

I want it so after the user clicks the button it shows as thinking or whatever how would I do something like that?

#

It is an interaction : discord.Interaction

slate swan
#

hey does anyone know how to make like a 24 hour countdown?
ex:

Refreshes in: 23:59:14

#

and it just edits and counts it down everytime

cloud dawn
regal cove
#

what are some good hosting websites?

cloud dawn
eager hill
slate swan
cloud dawn
slate swan
#
Traceback (most recent call last):
  File "c:\project-spot\main.py", line 40, in <module>
    @bot.tree.command(name = "purge", description = "Purge's a channel messages", required = True)
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: CommandTree.command() got an unexpected keyword argument 'required'```?
cloud dawn
#

required?

slate swan
frosty umbra
#

Whats the point in using multiple files for your discord bot rather than doing it all in one?

#

Like what are the advantages and disadvantages

cloud dawn
#

There are only advantages.

#

Well unless you don't know how to make it.

slate swan
#
Traceback (most recent call last):
  File "c:\project-spot\main.py", line 40, in <module>
    @bot.tree.command(name = "purge", description = "Purge's a channel messages")
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 889, in decorator
    command = Command(
              ^^^^^^^^
  File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 393, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\transformers.py", line 832, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\acatto\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\transformers.py", line 791, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
#

am i just stupid

cloud dawn
#

It's more organized and readable. It's also not just that the bot is generally better.. since most people aren't coding it correctly if they do it all in one file. Multi file also allows for better hot reloading.

slate swan
#

can anyone send me their purge command, i can't find a answer

rare echo
frosty umbra
rare echo
#

should be required by default no?

slate swan
rare echo
#

show code

frosty umbra
#

And what should I be splitting it to like one file per command or wha

slate swan
#

how do i make my bot check if the content isnt a id then sent to send a message saying send a id

rare echo
#

why do you have ctx and interaction?

cloud dawn
slate swan
frosty umbra
frosty umbra
slate swan
frosty umbra
#

Also whats wrong with 1k lines

cloud dawn
frosty umbra
frosty umbra
slate swan
frosty umbra
#

Interaction

rare echo
slate swan
# rare echo yes?

ok ty, i just switched over to slash commands so im experiencing new stuff xd

cloud dawn
frosty umbra
#

Slash commands doesnโ€™t use ctx it jses interaction

slate swan
#
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
frosty umbra
slate swan
#

"Synced 3 command(s)"

frosty umbra
#

Also i dont think @lavish micamands.has_permissions works with slAsh commands

slate swan
frosty umbra
#

You should edit the permissions in the integrations menu for slash commands

cloud dawn
slate swan
#

or anything related to it

frosty umbra
#

Configs?

rare echo
cloud dawn
frosty umbra
#

Fat noob here

rare echo
#

is that what you guys are talking about? are all your commands in one big ass file?

cloud dawn
frosty umbra
slate swan
frosty umbra
frosty umbra
rare echo
#

D:

frosty umbra
#

I was just wondering what the advantages and disadvantages were of not doing that

cloud dawn
#

Might as well oneline itpy_guido

rare echo
#

im praying its not that large

frosty umbra
rare echo
frosty umbra
#

I like coding in one file

rare echo
#

speaking in terms of amount to transfer

frosty umbra
#

I structure it so related commands are near each other

#

For example the rep command is above the repleaderboard command

rare echo
frosty umbra
#

Idk I just have never really done that before

#

But Iโ€™m thinking about doing it

cloud dawn
rare echo
#

one file, 6 commands related to x- second file, 9 commands relaying to y- etc.

frosty umbra
rare echo
#

a lot more manageable

slate swan
#

can anyone send their purge slash command please ๐Ÿ™

cloud dawn
#

Experienced dpy coders being busy with the bot base 95% of the time and 5% coding the commands.. ducky_dave

frosty umbra
#

The bot base?

rare echo
slate swan
rare echo
#

whats the error?

cloud dawn
rare echo
#

i might have missed it if you already sent

slate swan
frosty umbra
rare echo
# slate swan

i might be wrong but this is just a sync issue, no?

slate swan
#
  • i'm not experience with slash commands
rare echo
#

404 from a slash command

frosty umbra
#

I tried saying a sync issue before

#

He said it synced

cloud dawn
frosty umbra
rare echo
slate swan
#

am i doing something wrong?

frosty umbra
#

But it would be cool if the bots I made came already with like moderation and stuff

cloud dawn
rare echo
#

idk i dont use tree or wtv that it x)

frosty umbra
rare echo
#

cant help ya there

frosty umbra
#

Dont sync on ready

frosty umbra
#

Or they could disable the module

cloud dawn
#

Sometimes a good bot just has 3 commands that can actually perform them really good.

slate swan
frosty umbra
#

Make a sync command

rare echo
#

make a command to sync

slate swan
#

like /sync?

frosty umbra
#

Preferably a prefix command

cloud dawn
#

setup_hook guys

frosty umbra
#

Like -sync

rare echo
#

i wouldnt use a slash command to sync slash commands

slate swan
frosty umbra
#

Sure

slate swan
#

okay

frosty umbra
#

setup_hook?

rare echo
cloud dawn
frosty umbra
#

The base of the bot is things included for everyone

#

And its one file itself

#

So if I update it I just send the new file to everyone

#

I think I see what you meant now

cloud dawn
#

Well it would update automatically but you're seeing more clearly now.

rare echo
#

saving them money by sending just new lenses for their glasses not the entire frame

slate swan
#

oh it purges but doesnt send message and just spits out that error

cloud dawn
#

Just charge a subscription lmao

frosty umbra
#

Its for each individual persons needs

cloud dawn
rare echo
frosty umbra
#

Yeah

rare echo
#

just toss amount instead of z since itll do that amount anyway

#

ยฏ_(ใƒ„)_/ยฏ

frosty umbra
#

They are tailored to the persons needs

cloud dawn
frosty umbra
#

Ok now im confused

#

What is the base

cloud dawn
#

The base is just useful stuff and initializing the bot.

frosty umbra
#

Bruah

#

Initializing?

#

Pov: bot.run

cloud dawn
#

We'll actually bot.start if we're talking ethics.

frosty umbra
#

Breh

#

I think I know what you mean though, I think, but the bots I make are also usually for a single server

#

So there isnt much initialisation

#

Unless im completely wrong and still dont understand

cloud dawn
#

I mean heck you can code a single bot that has different command and events for each guild.

frosty umbra
#

I mean yeah you could LMAO

#

but I usually give the source to serber owners so it can be their bot application

#

Unless im working with the server in a direct way

#

But i think i have the understanding of base doen

#

Like the bit where you getGuildID fill in variables with the right content etc

#

The configuration for a specific server

cloud dawn
#

I'd use c# for the ultimate bots, I'd prob be a billionaire.

frosty umbra
#

Breh

#

C# was made for sin city

cloud dawn
#

But it has a GUI

frosty umbra
#

(Im too stupid to use it(I havent tried))

cloud dawn
#

And you can add graphs

frosty umbra
#

Bruh

#

Make your own graphs in python

cloud dawn
#

Base releases.

frosty umbra
#

Hehehaw

cloud dawn
#

Updates

frosty umbra
#

Isnt c# used for making games

#

Not discord bots

cloud dawn
#

In unity yes

frosty umbra
#

Smh

cloud dawn
#

c# used for a lot of apps.

frosty umbra
#

I need to learn java, not for discord coding but just because apparently its a good language to know

cloud dawn
#

java is ok

frosty umbra
#

It has alot of usage

cloud dawn
#

Just all of android is based on it lol

frosty umbra
#

Where it spreads to websites and games and loads

cloud dawn
#

websites and games?

frosty umbra
#

Javascript

cloud dawn
#

nahh

frosty umbra
#

Websites

#

Games minecraft?

cloud dawn
#

Games are usually c++

#

names one exception

frosty umbra
#

Me when mojang: brainmon

#

Roblox using lua:hemlock

frosty umbra
#

But isnt c++ really difficult

cloud dawn
#

It's the end boss

frosty umbra
#

Like wtf

cloud dawn
#

Nah rust is worse

frosty umbra
#

Rust?

#

Doesnโ€™t rust have a bunch of mods for it

cloud dawn
#

return 0 class void

frosty umbra
#

Me not understanding at alll

rare echo
frosty umbra
#

C++ is something you would definitely take a course in

cloud dawn
frosty umbra
#

You want a teacher not a youtube video

cloud dawn
#

I just want my docs thanks :3

frosty umbra
#

Bro reads the docs to learn a new language

cloud dawn
#

No one can teach it better than the guy who literally made it and has a written documentation.

frosty umbra
#

I love python and all but the job opportunities it takes you down are really limited

#

Online it all says data analytics

#

Which sounds really boring

cloud dawn
frosty umbra
#

ML?

cloud dawn
#

Lots of automation inside companies.

frosty umbra
#

Also AI is python based?

cloud dawn
frosty umbra
#

Oh fair

cloud dawn
frosty umbra
#

Me about to work for amazon fresh stores using python

granite brook
#

anyone know how to do these "choices" thing? as the tutorial I found didn't work out, it says AttributeError: 'Bot' object has no attribute 'choices'

bot declaration:

intents = discord.Intents().all()
bot = commands.Bot(command_prefix = prefix, intents = intents)

command, I'm trying to make:

@bot.tree.command(name = "pc")
@bot.choices(choices=[
    bot.Choice(name="create", value="create"),
    bot.Choice(name="set", value="set"),
    bot.Choice(name="update", value="update"),
    bot.Choice(name="delete", value="delete"),
])
async def pc_slash(interaction: discord.Interaction, command: bot.Choice[str]):
    pass
frosty umbra
#

Ill be back later see you guys thanks for the help

granite brook
cloud dawn
unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
cloud dawn
#

Click on the link for examples.

granite brook
#

hmmm now I get unknown parameter given: choices :/

#

but I'll test around a few things maybe I find the problem

cloud dawn
#

Did you check the examples?

granite brook
#

yea, and when I copy one in, that works, so now I'm trying to change it to mine one step at a time to see where it decides to not work :D

#

I found it, it was a naming error from my part, didn't realize I need to name two things the same

slate swan
#

yo

slate swan
#

How can I get messge history for a channel?

#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโ€™s message history.

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

Examples

Usage...
slate swan
tacit storm
#

imo the more an language can do, the better it is.

primal token
#

The abstraction level of a programming language used for a project should depend on the user and application.

#

Some users like low level languages, while some use low level languages due to the lack of abstractions making it easier for them, some people use high level languages to make there life easier or to have set of rules they like or libraries/platforms the language may have.

untold bay
primal token
#

Games also use C++ due to unreal engine!

untold bay
#

Yes, but it's actually a variant (Unreal C++).

primal token
#

Mhm thats interesting, what does the general unreal engine use?

untold bay
#

wdym?

shrewd apex
primal token
#

Well, you said only a variant of unreal engine uses C++, so what does the general/main one ig? use?

#

I dont really know much about games๐Ÿ˜…

untold bay
#

No, no, no. UE uses a variant of C++ called "Unreal C++".

unkempt canyonBOT
#

examples/basic_usage.py line 16

return None```
primal token
primal token
#

๐Ÿ˜”

shrewd apex
primal token
primal token
#

Smh, just like andy, you guys both want to see the world burn

shrewd apex
#

i had all declared so first time i did wild import but mypy wanted explicit so i just went ahead and did it

primal token
#

or does mypy not like that eitheir

shrewd apex
#

didn't try

primal token
#

It probably does since you've already done them in multiple modules

shrewd apex
primal token
#

From an overall view, seems like allot of abstractions none the less

sick birch
#

Abstraction is the name of the game here

shrewd apex
#

in the models yeah but lots of endpoints

primal token
shrewd apex
#

๐Ÿ˜

primal token
#

PR incoming!

#

Not from me but from robin!

slate swan
#

๐Ÿ’€ just from pokelance important models

#

and use models.Class

#

@shrewd apex ^

shrewd apex
#

I'll do it before publishing

slate swan
#

it's literally just find and replace

glad cradle
slate swan
#
@discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "SELECT PAYMENT METHOD", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maximum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Name 1",
                description="OPTION #1"
            ),
            discord.SelectOption(
                label="Name 2",
                description="OPTION #2"
      
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")

What do I need to add to give an output when the option is selected?

upbeat gust
slate swan
robust fulcrum
#

Guys what difference between
bot.start() and bot.run()
And which one should I use?

slate swan
#

ill suggest using bot.run because it enables logging and stuff by default

#

you also won't have to use a Seperate asyncio
run with it

robust fulcrum
#

Ok

#

Guys why i getting error
no module named 'cogs'
This is my code

import discord
from discord.ext import commands
import os

class botclass(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(">"),intents=discord.Intents.all())
        
    async def setup_hook(self):
        print("i am ready")
        for cog in os.listdir("rustcomp/cogs"):
            if cog.endswith(".py") and cog.startswith("_"):
                try:
                  load = cog.replace(".py","")
                  load = f"cogs.{load}"
                  await bot.load_extension(load)
                except Exception as e:
                    print(e)

bot = botclass()
upbeat gust
upbeat gust
#

rustcomp/cogs/cogs doesnt exist as a module

robust fulcrum
#

I have file called _rust_compiler in it but that's empty

upbeat gust
#

dont go into cogs twice

robust fulcrum
#

Where am I going twice?

slate swan
upbeat gust
upbeat gust
slate swan
#

i mean I have it as well , like i have a lot of cocks folder

upbeat gust
#

thats so funny

robust fulcrum
#

I am not going into cogs twice
I am formatting the string with cogs. there

robust fulcrum
#

I am not able to understand what you mean

slate swan
#

Means file directory

robust fulcrum
#

Oh cwd = current working directory

slate swan
#

Yep

robust fulcrum
slate swan
#
 @app_commands.command(name = "mylist", description="A list of shop commands!")
    
    async def mylist(self, interaction: discord.Interaction) -> None:
        
        for command in self.bot.commands:
            print(command)

Anyone know how to make a list all current commands thats using CTX + app_commands with cogs? The online exampls arent working for me

slate swan
unkempt canyonBOT
timid spade
grand hazel
#

i was trying to make a bot change its presense every 10 second to show the ram usage

import asyncio, discord, sys, os, psutil
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import CommandNotFound

activity = discord.Activity(type=discord.ActivityType.watching, name=f'Memory Usage : {psutil.virtual_memory().percent}%')
intents = discord.Intents.all()
client = discord.Client(intents=intents, activity = activity)

async def status_task():
    global activity
    while True:
        await client.change_presence(activity)
        await asyncio.sleep(10)

@client.event
async def on_ready():
    await tree.sync()
    print('Logged in as')
    print(client.user.name)
    print('------')
    client.loop.create_task(status_task())

but i got this error :

naive briar
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the clientโ€™s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
naive briar
#

It only takes keyword arguments

#

Also, your presence won't change because you've only defined the activity once but never changed it, so it's pointless to try to change it every 10 seconds

full marten
naive briar
#

What do you mean?

slate swan
timid spade
slate swan
#

if its consuming any input from a command how will it be a persistent view lol
you'll have to run the command everytime you restart the bot

timid spade
slate swan
slate swan
# timid spade ouch then how tf bots like slash bot manage to do it

they don't use discord.py like persistent system but something simpler ig, i can imagine doing this:
user invokes the command wih guild ids:
you make a simple view with role names added in the select.

and the you can use an on_interaction event with checks that adds the role based on the role names...

i might be very wrong when i say that :p

#

actually wait there's some open source bots that use this lemme check

hushed galleon
#

afaik with libraries like discord.js, you only get that interaction_create event so it becomes your responsibility to know what the interaction is meant to do

#

d.py views abstract it into callbacks which makes it feel a lot more object-oriented; the only expectation is that whenever your bot starts up, you use Client.add_view() to tell d.py what views it can respond to

slate swan
#

yeah but if there's like 10-15 select-roles setup ( that they're doing ) it would be hellish to begin with

hushed galleon
#

yeah definitely should use the builtin RoleSelect class for that

slate swan
#

wish discord allowed to limit the roles that show up there

outer flint
#

what's the best way to cycle through all members? thinko

frosty umbra
#

How can I make a bot have a custom profile picture for a specific guild like dyno can with dyno premium

slate swan
slate swan
#

if you look into the tags of normal and premium bot it's different

slate swan
#

that edits the global avatar

outer flint
slate swan
unkempt canyonBOT
slate swan
#

you can use a for loop on it

outer flint
#

ok perfect, then I'll just check which of them have added a reaction to a message thonkhmm

slate swan
#

!d discord.Reaction.users :)

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
outer flint
#

I wonder if it's better in this way
for all users
if have addded reaction to message && other stuff
then do Y

or do the opposite
search all the users that have added reaction to message
if other stuff
do Y

frosty umbra
#

So does dyno create a new application for each server?

frosty umbra
#

And considering how big it is would it not get limited

slate swan
frosty umbra
#

They make you make the application and then put in the token

#

Cant the bot token give access to your discord account or something

#

Thats the warning discord gives me when I try to send my bot token in a message on discord

slate swan
#

mee6 asks for your bot token in order to create a custom bot, maybe dyno does the same

frosty umbra
#

i guess maybe

slate swan
frosty umbra
#

maybe it was mee6 that i saw with a custom avatar

slate swan
#

8 bots i.e.

frosty umbra
#

but it makes sense

#

8 bots all doing the same thing

slate swan
#

yeah mee6 can do that

#

;-;

outer flint
#

something like this?

@bot.command()
@commands.has_role("Botmakers")
async def players(self, ctx):
    channel = self.bot.get_channel(channel_id)
    message = await channel.fetch_message(message_id)
    users = set()
    for reaction in message.reactions:
        async for user in reaction.users():
            users.add(user)
    await ctx.send(users)

Get all the users that, in a specific channel, have reacted to a specific message

slate swan
#

yes indeed this should work

#

yep

outer flint
#

obvs channel_id and message_id are defined thonkhmm

wonder why the bot tells me that the command "players" doesn't exist ree

outer flint
slate swan
#

it will be @commands.command

#

for cog

outer flint
#

I put that into the main "cog" thonkhmm
here

slate swan
#

@commands.command()
@commands.has.....

#

like dat

outer flint
#

all the others commands in the same .py work though thonkhmm

slate swan
slate swan
#

self doesnt make any sense on normal commands

outer flint
#

๐Ÿค”

outer flint
slate swan
#

it's normal command

#

also make sure to restart the bot XD

outer flint
#

Oh yeah, using the restart command

hushed galleon
slate swan
timid spade
slate swan
#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.

New in version 2.0.
slate swan
#

use this

robust fulcrum
#

Anyone pls help me

outer flint
#
@bot.command()
async def players(ctx):
    author_roles = ctx.author.roles
    if any(
        role.name in {"Botmakers", "Admin", "Moderators", "Staff", "Lead Devs"}
        for role in author_roles
    ):
        channel = bot.get_channel(channel_id)
        message = await channel.fetch_message(message_id)
        print("message ok")
        users = set()
        print("users created")
        for reaction in message.reactions:
            print("reaction")
            async for user in reaction.users():
                # if user.role != "Player":
                users.add(user)
        await ctx.send(users)
slate swan
#

makes sense

#

did u check docs?

outer flint
#

I checked the message_id [I set it manually at beginning of file] and it's correct thonkhmm

slate swan
#

wait imma check for u

outer flint
#

from the doc it seemed like that was the way to write that thonkhmm

slate swan
#

the id

#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
outer flint
#

uhm... I wonder if it's too long and wasn't created as an int thonkhmm

#

1000324697663209502

slate swan
#

or
message_id = "12121212112"?

outer flint
#

yes thonkhmm

#

channel_id = 914105154469498880
message_id = 1000324697663209502

slate swan
#

fun fact: fetch_message doesn't care if you provide a string or integer

slate swan
#

ik, but it will work with a string as well
it makes an api request which can be in form of str or int

night crater
outer flint
#

strange the channel fetching is right, but not the message one thonkhmm

slate swan
#

u can get

outer flint
#

yes the bot has all perms needed [admin] thonkhmm

slate swan
#

Then the message is too old maybe

outer flint
#

well the message is very old indeed

slate swan
outer flint
#

5 months

slate swan
#

try checking with new message id for test

outer flint
#

I thought older kek

slate swan
outer flint
#

nah, that ain't the problem handscry

slate swan
#

just try with newer id vro

#

and fetch the messageif doesnt work then idk xd

outer flint
#

tried with newer ids [messages from a few minutes ago]

#

same result :T

slate swan
#

cooooooool

outer flint
#

yep :T

#

nono wait I miread, I'm using disnake

slate swan
#

BRUH

outer flint
#

I thought I said that monkahide

slate swan
#

well for disnake the method is just same

#

get_channel is same too opsi

#

then whats the prob

outer flint
#

I knew god had a punishment for me ree

slate swan
#

can u try printing message?

#

print(message)

outer flint
#

doesn't get printed at all

slate swan
#

add this line and run the command

#

just do it xd

timid spade
outer flint
slate swan
#

!d disnake.PartialMessageable

unkempt canyonBOT
#

class disnake.PartialMessageable```
Represents a partial messageable to aid with working messageable channels when only a channel ID is present.

The only way to construct this class is through [`Client.get_partial_messageable()`](https://docs.disnake.dev/en/latest/api.html#disnake.Client.get_partial_messageable "disnake.Client.get_partial_messageable").

Note that this class is trimmed down and has no rich attributes.

New in version 2.0...
slate swan
#

hmm

slate swan
# timid spade Ah, how can I use this for that?

!d discord.Interaction you get this class as an argument in the event
first you'll check the type of interaction so that its select type
next you will check if the select was one made for your select roles
then you can get the label of interaction using interaction.values and convert it into a role using discord.utils.get(interaction.guild.roles, name= the name)
and finally add the role

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

!d disnake.Client.get_partial_messageable

unkempt canyonBOT
#

get_partial_messageable(id, *, type=None)```
Returns a partial messageable with the given channel ID.

This is useful if you have a channel\_id but donโ€™t want to do an API call to send messages to it.

New in version 2.0.
slate swan
#

@outer flint ig try

#

wait no

#

that doesnt make any sense ๐Ÿ’€

#

!d disnake.Client.get_message

unkempt canyonBOT
slate swan
#

LoL

#

use that

#

for that u dont need to get channel

#

bot.get_message(id)

#

the for reaction in message.reactions XD

outer flint
#

so just message = bot.get_message(message_id) ?

sullen pewter
#

why isn't it returning what I want

slate swan
#

do print(string.upper) ig xd

#

idk lol

outer flint
#

uhm... it is none kek

slate swan
outer flint
#
        message = bot.get_message(message_id)
        print(message)
        print("message ok")
        users = set()
        print("users created")
        for reaction in message.reactions:
            print("reaction")
            async for user in reaction.users():
                # if user.role != "Player":
                users.add(user)
        await ctx.send(users)
slate swan
#

tried with new message id?

#

it said it will get the message from bot cache

outer flint
#

yeah, even with new message id same None

slate swan
#

how do i make my bot also check for another message

robust fulcrum
#

Guys why i getting error
no module named 'cogs'
This is my code

import discord
from discord.ext import commands
import os

class botclass(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(">"),intents=discord.Intents.all())
        
    async def setup_hook(self):
        print("i am ready")
        for cog in os.listdir("rustcomp/cogs"):
            if cog.endswith(".py") and cog.startswith("_"):
                try:
                  load = cog.replace(".py","")
                  load = f"cogs.{load}"
                  await bot.load_extension(load)
                except Exception as e:
                    print(e)

bot = botclass()
naive briar
#

You have to give it a valid path to the cog

robust fulcrum
naive briar
#

What does your project structure look like

robust fulcrum
slate swan
#

try:
.... await client.wait_for(..., timeout=seconds to wait)
except asyncio.TimeoutException:
.... x

where do i add the code above @naive briar

naive briar
#

I really don't know about that

robust fulcrum
#

Hmmm?

outer flint
slate swan
slate swan
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

slate swan
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

Thanks

#

it's ok ;]

slate swan
upbeat otter
#

๐Ÿ’€ what...

naive briar
#

What the

slate swan
slate swan
upbeat otter
#
  • get_message is an object
  • objects are basically class instances of None
  • message = None and None has an attribute content

๐Ÿ› everyday godly advice

slate swan
#

but rust_compiler doesnt even star with _

slate swan
#

My brain dies sometimes

upbeat otter
#

๐Ÿ’€

slate swan
slate swan
slate swan
#

at the same time

upbeat otter
slate swan
#

not at the same time

naive briar
#

Did you put double quotes around it

slate swan
#

xd
first u have to wait for 1 message then for another

cold sonnet
#

I don't understand anything that happens here rn

upbeat otter
#

same

shrewd apex
cold sonnet
#

get_message is a method of the Client class

slate swan
cold sonnet
#

which returns a Message instance

slate swan
slate swan