#discord-bots

1 messages · Page 364 of 1

viscid hornet
#

you’re trying to edit an interaction after a response has been sent but no response has been sent

rancid leaf
#

the other instances of that line of code simply edit the original message though, im not sure why this one specifically is giving me issues

#

and the original message is still present when that line runs

viscid hornet
#

like if we were playing a card game: i have to wait for you to play before i can play my card. but what you’re doing is the same as me playing my cards before you play your turn

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

rancid leaf
#

uuuh the whole thing is like over 250 lines

viscid hornet
#

you dont have to put the whole thing in lmao

rancid leaf
#

So i first send the message up here:

 await ctx.send(embed=embed, components=components)

then have 3 occurrences that all function correctly of:

await interaction.followup.edit_message(
            interaction.message.id,
            components=components,
            embed=embed
        )

then the block of code causing issues is:

if interaction_params[0] == "Dungeon":
            profile = await get_profile(interaction.user.id, db)
            index = int(interaction_params[1])
            dungeon = self._dungeons[index]
            difficulty_embed = LocationsUserInterface.dungeon_difficulty_selection_embed(dungeon)
            if index in profile["dungeons"]:
                has_diff = True
            else: has_diff = False
            components = LocationsUserInterface.dungeon_difficulty_selection_components(index, interaction.user.id, has_diff)
            await interaction.followup.edit_message(interaction.message.id, embed=difficulty_embed, components=components)
#

if i defer it fixes it but then it gives me an interaction has already been responded to prompt anytime anything goes off

viscid hornet
main holly
#

can someone help me make a ticket system

rancid leaf
#

oop sry, english is not first language, i think i see

viscid hornet
viscid hornet
#

just wanna make sure you get the best help available

rancid leaf
#

pasted

main holly
#

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

rancid leaf
main holly
viscid hornet
main holly
#

it just shows "this didnt work" or something like that

viscid hornet
#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.

For interaction based contexts this does one of the following...
main holly
#

when i click the button

rancid leaf
#

it sends the components and embed correctly yes

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

main holly
viscid hornet
slim bloom
#

gambling

viscid hornet
#

yeah?

slim bloom
#

plis help me with slash commands

naive briar
#

lmao

naive briar
slim bloom
#

@viscid hornet

viscid hornet
#

i told you your issue

#

bot.tree.sync, not bot.sync

slim bloom
#

I promise you that I will get you a nitro boost and give it to you as a gift.

viscid hornet
viscid hornet
vapid parcel
#

How would I set this up..?

#

I am a lil confused on this one ngl GoofySkull

viscid hornet
#

the same way you would with a command prefix or with a db pool

vapid parcel
#

alr

#

was a lil confused GoofySkull

viscid hornet
vapid parcel
#

ily

viscid hornet
#

i’ll read for you when you get too lazy 👌

vapid parcel
#

real

#

I was lazy

rancid leaf
#

i think i figured it out thank you<3

viscid hornet
viscid hornet
sweet minnow
#

topggpy
and some other libraries

viscid hornet
#

did all the libraries install fine?

sweet minnow
#

yes

viscid hornet
#

should only need to import topgg

#

idk im gonna go to bed

sweet minnow
#

topggpy-1.4.0.dist-info
and
topgg

#

supposedly it is installed?

#

in python packages

round jetty
# viscid hornet whats your dpy version?

Bro im going to fkkkkkin ballistic, every video garbage, Embeds was so easy to do but now when it comes to slash commands, idek how to start, where to start, I need help brotha

vapid parcel
#

Does dpy have a translator?

#

For supporting multiple languages

golden portal
#

!d discord.app_commands.Translator

unkempt canyonBOT
#

class discord.app_commands.Translator```
A class that handles translations for commands, parameters, and choices.

Translations are done lazily in order to allow for async enabled translations as well as supporting a wide array of translation systems such as [`gettext`](https://docs.python.org/3/library/gettext.html#module-gettext) and [Project Fluent](https://projectfluent.org).

In order for a translator to be used, it must be set using the [`CommandTree.set_translator()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.set_translator) method. The translation flow for a string is as follows:
vapid parcel
#

Yeah I found it

#

Mb lol

golden portal
#

oke

shrewd apex
# vapid parcel Yeah I found it

it doesn't translate perse it just passes the command name params etc to the translator for which u need to get the translated text from files like pot files

vapid parcel
#

Yeah I found that out lol

slim bloom
#

how im create a avatar slash command: ```py
import discord
from discord.ext import commands
from discord import app_commands

class Avatar(commands.Cog):
def init(self, bot):
self.bot = bot

@app_commands.command(name="prof", description = "Get avatar")
async def prof(self, interaction):
    await interaction.response.send_message("This", ephemeral=True)

async def setup(bot):
await bot.add_cog(Avatar(bot))```

viscid hornet
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

viscid hornet
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
viscid hornet
#

this

turbid condor
#

!d discord.Asset.url

unkempt canyonBOT
turbid condor
viscid hornet
shrewd apex
#

!d discord.Member.display_avatar is what u usually want if the user dosent have an avatar it returns url for the default one

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
viscid hornet
shrewd apex
#

so i did

upbeat otter
turbid condor
viscid hornet
upbeat otter
wanton current
viscid hornet
spice seal
#

Guys I heard that there is some issues with dank memer cuz discord had an update,does it put any effect on python bots?

turbid condor
#

dk

swift acorn
#
@app_commands.context_menu(name="Test", default_permissions=discord.Permissions.manage_messages)
@app_commands.guild_only()
async def context_menu_test(interaction: discord.Interaction, user: discord.Member):
    await interaction.response.send_message(f'Test {user.mention}', ephemeral=True)

I have a question regarding default_permissions in a contxt menu, how can I set these? because here if I try to do this it doesn't work

naive briar
#

!d discord.app_commands.context_menu

unkempt canyonBOT
#

@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.

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

Examples...
naive briar
swift acorn
#

I figured it out sorry 😅 I just had to add a seperate decorator for it

@app_commands.default_permissions()

naive briar
#

Ah, right

viscid hornet
viscid hornet
shrewd apex
#

seems like a dank issue and not a discord issue

viscid hornet
old creek
#

how can we make discord bots

viscid hornet
#

!pypi discord.py is a good library to use - almost everyone uses it

unkempt canyonBOT
misty harbor
#

Hello, I would like to host a discord bot in python you know of good hosts I saw the o2switch offer what do you recommend to get started (I also use selenium with the server)

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

misty harbor
#

thanks

river hollow
#

hey anyone knows why the suggestion only shows up when i type in a letter in the search bar ?

i allready tried removing if current.lower() in profit_symbol.lower(): but then the whole auto suggestion stops working

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
#

!traceback and this if possible

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.

slim bloom
#

@viscid hornet ```py
import discord
from discord.ext import commands
from discord import app_commands

color_saura = discord.Color.from_rgb(173, 216, 230)

class Say(commands.Cog):
def init(self, bot):
self.bot = bot

@app_commands.command(name="say", description="Di algo")
@commands.has_permissions(manage_messages=True)
async def say(self, interaction: discord.Interaction, *, content: str):
    await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
    await interaction.channel.send(f"{content}")

@say.error
async def say_error(self, interaction: discord.Interaction, error):
    if isinstance(error, commands.MissingPermissions):
        await interaction.response.send_message(f"Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)
        return

async def setup(bot):
await bot.add_cog(Say(bot))```

slim bloom
#

I have an error and that is that if you do not have permissions it does not execute the @say_error

viscid hornet
#

also you should always end your error handler with “else: raise error”

#

otherwise you’ll end up eating error messages and wondering why stuff wont work

viscid hornet
viscid hornet
slim bloom
viscid hornet
slim bloom
#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        embed = discord.Embed(title="Comando no encontrado", description=f" El comando `{ctx.invoked_with}` no se encuentra en mi codigo.", color=color_saura)
        await ctx.send(embed=embed)
    elif isinstance(error, commands.CommandError):
        embed = discord.Embed(title="Error inesperado", description=f"Ha ocurrido un error ejecutando el comando. ```{error}```", color=color_saura)
        await ctx.send(embed=embed)

    else:
        raise error```
river hollow
# viscid hornet !code show the whole thing
    @app_commands.autocomplete(item=profit_autocompletion)
    async def profit(interaction: discord.Interaction, 
                    item: str
            ):
        
        with open(json_file_path, 'r') as f:
            user_wallets = json.load(f)     

        user_id = str(interaction.user.id)
        user_wallet = user_wallets[user_id] 

        tx = calculate_p(item,user_wallet)

        embed=discord.Embed(title=tx["token_symbol"],color=6645140)
        embed.add_field(name="profit/loss",value=f"${tx['profit_or_loss']} USD")

        del user_cache[user_id]
       
        await interaction.response.send_message(embed=embed)```
viscid hornet
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.

slim bloom
viscid hornet
#

your local handler takes more priority

slim bloom
viscid hornet
#

the same way you’d visit friends who live closer to you more than those who live a city away or a country away

viscid hornet
#

a cog? a main file?

slim bloom
# viscid hornet the same way you’d visit friends who live closer to you more than those who live...
import discord
from discord.ext import commands
from discord import app_commands

color_saura = discord.Color.from_rgb(173, 216, 230)

class Say(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="say", description="Di algo")
    @commands.has_permissions(manage_messages=True)
    async def say(self, interaction: discord.Interaction, *, content: str):
        await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
        await interaction.channel.send(f"{content}")

    @say.error
    async def say_error(self, interaction: discord.Interaction, error):
        if isinstance(error, commands.MissingPermissions):
            await interaction.response.send_message(f"Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)
        else:
            raise error

async def setup(bot):
    await bot.add_cog(Say(bot))```
viscid hornet
#

im seeing app commands and bot.tree.cmd in the same place

slim bloom
#

?

slim bloom
viscid hornet
slim bloom
#

spanish pls

viscid hornet
river hollow
slim bloom
viscid hornet
slim bloom
#
Cog valido: syncup
Cog valido: help
Cog valido: ping
Cog valido: avatar
Cog valido: say
Conectado a Discord
   _____                       
  / ___/____ ___  ___________ _
  \__ \/ __ `/ / / / ___/ __ `/
 ___/ / /_/ / /_/ / /  / /_/ / 
/____/\__,_/\__,_/_/   \__,_/  
                               

Prefix: [?] Bot: [Pruebas#3847]```
viscid hornet
#

damn it

viscid hornet
#

i feel like this could be solved with an app commands check

slim bloom
viscid hornet
viscid hornet
#

!d discord.ext.commands.MissingPermissions

unkempt canyonBOT
#

exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
viscid hornet
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
slim bloom
viscid hornet
#

yeah im tryna think

viscid hornet
slim bloom
viscid hornet
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
viscid hornet
slim bloom
#

?

viscid hornet
#

???

#

wait lemme do some digging rq

slim bloom
#

?

slim bloom
#

ok im test

viscid hornet
viscid hornet
#

read the examples

slim bloom
viscid hornet
#

!discord.Guild.permissions

#

god i need sleep

slim bloom
#

!discord.Guild.permissions

viscid hornet
#

internal screaming

#

!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`).
azure elk
#

x == y

viscid hornet
slim bloom
azure elk
#

im new to discord bot. how is it monetizable? seems too many communities and too many people working on it. is it mostly just making cmds?

viscid hornet
azure elk
#

ok cool. yeah just wondering cause it seems like a lot of interest. im just sniffing for the opportunities. ok, carry on then

viscid hornet
unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for).

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
viscid hornet
#

!d discord.Permissions.manage_messages

unkempt canyonBOT
#

Returns True if a user can delete or pin messages in a text channel.

Note

Note that there are currently no ways to edit other people’s messages.

viscid hornet
viscid hornet
slim bloom
#

@viscid hornet now work ```py
import discord
from discord.ext import commands
from discord import app_commands

color_saura = discord.Color.from_rgb(173, 216, 230)

class Say(commands.Cog):
def init(self, bot):
self.bot = bot

@app_commands.command(name="say", description="Di algo")
async def say(self, interaction: discord.Interaction, *, content: str):

    if interaction.user.guild_permissions.manage_messages:
        await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
        await interaction.channel.send(content)
    else:
        await interaction.response.send_message("Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)

async def setup(bot):
await bot.add_cog(Say(bot))```

slim bloom
#

thx so much

viscid hornet
#

dms are a thing and that will fuck up the command

viscid hornet
#

you can check if its in a guild using this:

#

!d discord.Interaction.guild

unkempt canyonBOT
viscid hornet
#

it can either be a Guild or None

#

so if its None then tell the user they cant use the command there

vapid parcel
#

Are all channel ids the max length of 19?

unkempt canyonBOT
viscid hornet
#

it doesn’t say anything about it

vapid parcel
#

L

viscid hornet
vapid parcel
#

To lazy

#

ill just set the max length to 24

#

just incase 😁

slim bloom
# viscid hornet it can either be a Guild or None
@app_commands.command(name="say", description="Di algo")
 async def say(self, interaction: discord.Interaction, *, content: str):
     if interaction.guild is None:
         await interaction.response.send_message("Este comando solo puede ser usado en un servidor.", ephemeral=True)
         return

     if interaction.user.guild_permissions.manage_messages:
         await interaction.response.send_message("Mensaje enviado.", ephemeral=True)
         await interaction.channel.send(content)
     else:
         await interaction.response.send_message("Necesitas el permiso `Gestionar mensajes` para ejecutar este comando.", ephemeral=True)```
#

good?

viscid hornet
vapid parcel
slim bloom
vapid parcel
#

called being lazy shrug

viscid hornet
vapid parcel
#

This one is

slim bloom
vapid parcel
#

but this is the server i like more

#

the other server i hate more 😁

#

they are more of a TOXIC community lmao

viscid hornet
vapid parcel
#
        try:
            channel_id_int = int(channel_id)
        except ValueError:
            embed = ErrorEmbed(
                title="Error",
                description="The provided channel ID is not a valid integer.",
            )
            await interaction.followup.send(embed=embed, ephemeral=True)
            return

        channel = interaction.guild.get_channel(channel_id_int)
        if channel is None:
            embed = ErrorEmbed(
                title="Error",
                description="The provided channel ID does not correspond to a channel in this server.",
            )
            await interaction.followup.send(embed=embed, ephemeral=True)
            return```
#

this will do 😁

sacred obsidian
#

]9~yh24r*-++++++++++++++++++++

#

whops

#

sorry

viscid hornet
#

?

azure elk
#

are you guys working from one repository? im still green. are your projects pretty tight net or do you have some open source ones where people can slowly jump in and contribute until their added value gets considerable?

viscid hornet
#

this doesnt sound very discord bot like pithink

harsh ingot
#

aways, sell cheap thi

viscid hornet
slim bloom
#

@viscid hornet i need help

#

from only owner can use slash command: ```py
import discord
from discord.ext import commands
from discord import app_commands
import os

color_saura = discord.Color.from_rgb(173, 216, 230)

class Reload(commands.Cog):
def init(self, bot):
self.bot = bot

@app_commands.command(name="reload", description="Recarga todos los cogs del bot")
@app_commands.is_owner()
async def reload(self, interaction: discord.Interaction):
    for filename in os.listdir("src/cogs"):
        if filename.endswith(".py"):
            await self.bot.unload_extension(f"src.cogs.{filename[:-3]}")

    for filename in os.listdir("src/cogs"):
        if filename.endswith(".py"):
            await self.bot.load_extension(f"src.cogs.{filename[:-3]}")

    embed = discord.Embed(title="Cogs recargados", description="Todos los cogs han sido recargados.", color=color_saura)
    await interaction.response.send_message(embed=embed)

@reload.error
async def reload_error(self, interaction: discord.Interaction, error):
    if isinstance(error, commands.NotOwner):
        await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)

async def setup(bot):
await bot.add_cog(Reload(bot))```

steel steppe
#

yo

#

@slim bloom

slim bloom
steel steppe
#

whatchu tryna do

slim bloom
steel steppe
#

ait

fast osprey
#

Slash commands are public and published

viscid hornet
fast osprey
#

You shouldn't be using them for something you specifically want to keep to yourself. That entirely defeats the purpose of the system

steel steppe
#

wdym

fast osprey
#

Don't use slash commands for private bot functionality, it's pretty simple

steel steppe
#

do @commands.command

#

why are ya using slash commands

steel steppe
#

like if ur tryna make owner only command

fast osprey
#

Or whatever else you wanna do, just not something that's broadcast to all of your users

slim bloom
#

but I wanted my bot to be 100% just slash

fast osprey
#

I mean you can make a guild slash command for a private guild only you are in but that's a ton of hassle for no gain and only risk that you accidentally mess up

#

I mean that's like saying you want a bot with only vowels

steel steppe
#

lmfaooo

fast osprey
#

Why limit yourself on the tools that do the job you want better

viscid hornet
steel steppe
#

thatsa pretty unnecessary handicap

fast osprey
#

That doesn't prevent what I was saying about private functionality being broadcast to all of your users for no point

viscid hornet
#

ohh thats what you meant. i see 👍🏽

crisp glacier
azure elk
#

is the discord bot subscription model tricky to get sign ups with a beginner project? do you need a community /social media to funnel from? i'm trying to figure out my next project

round jetty
slim bloom
#

@viscid hornet

#

How do I make my slash command only able to be executed by the owner of the bot?

crisp glacier
#

check

if ctx.author.id != 128391729837129471294 # Owner id
    return await ctx.response.send_message("You are not allowed to do this command!", ephemeral=True)
#

@slim bloom

#

something like this

slim bloom
#
import discord
from discord.ext import commands
from discord import app_commands

color_saura = discord.Color.from_rgb(173, 216, 230)

class Syncup(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def is_owner(self, interaction: discord.Interaction):
        return interaction.user.id == self.bot.owner_id

    @app_commands.command(name="syncup", description="Sincroniza los comandos slash")
    async def syncup(self, interaction: discord.Interaction):
        if not await self.is_owner(interaction):
            await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)
            return

        await self.bot.tree.sync()

        embed = discord.Embed(title="Slash sincronizados", description="Todos los comandos slash han sido sincronizados.", color=color_saura)
        await interaction.response.send_message(embed=embed, ephemeral=True)

async def setup(bot):
    await bot.add_cog(Syncup(bot))```
crisp glacier
#

i guess idk

#

lol

#

if it works it works

crisp glacier
#

yo solstice

#

how would i implement a splitting logic?
Im having problems at letting the user hit and hold on each hand

#

as of right now i have three lists.

  1. First hand
  2. Second hand (if split)
  3. Hands (contains all hands)

I thought of iterating through the hands list and doing something in the logic of the hit and hold button

#

but idk what

slim bloom
#
import discord
from discord.ext import commands
from discord import app_commands
import os

color_saura = discord.Color.from_rgb(173, 216, 230)

class Syncup(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def is_owner(self, interaction: discord.Interaction):
        return interaction.user.id == self.bot.owner_id

    @app_commands.command(name="syncup", description="Sincroniza los comandos slash")
    async def syncup(self, interaction: discord.Interaction):
        if interaction.user.id != int(os.getenv("CREATOR_ID")):
            await interaction.response.send_message("No tienes permiso para utilizar este comando.", ephemeral=True)
            return

        await self.bot.tree.sync()

        embed = discord.Embed(title="Slash sincronizados", description="Todos los comandos slash han sido sincronizados.", color=color_saura)
        await interaction.response.send_message(embed=embed, ephemeral=True)

async def setup(bot):
    await bot.add_cog(Syncup(bot))```
fast osprey
#

Users are really going to love seeing a command that they're not allowed to run put into their faces for some reason

crisp glacier
#

if you do not have permissions to run it

fast osprey
#

Because discord doesn't know about local checks

#

And slash commands can always be run by server managers. Because you publish them. The entire point is to make people see them and use them

crisp glacier
#

alright

vapid parcel
#

anyone have a google image bot working currently without any rate limits..? Or like barely any rate limits..?

viscid hornet
vapid parcel
#

But from google

#

I have something like this.

But with my current way, I can only do 100 requests per day. So I was wondering if anyone had another way that can go past that limit? or that has no limits.

tropic burrow
#

my commands arent working at all.


import json
import random
import discord
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
from web_server import keep_alive


intents = discord.Intents.default()
intents.messages = True
intents.members = True


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

@client.event
async def on_ready():
    print("Bot is ready")

@client.command()
async def hello(ctx):
    print("command executed")
    await ctx.channel.send("Hello!")

keep_alive()
client.run("[INSERT TOKEN HERE]")
#

either im using some outdated method because i have not used dpy in a while

golden portal
turbid condor
#

is it just me or assigning client to a commands.Bot instance has become norm

charred sable
#

can someone look up to my code it deletes the messages but fail to send a message saying it deleted

async def clear(interaction: discord.Interaction, amount: int):
    try:
        if interaction.user.guild_permissions.manage_messages :

            deleted = await interaction.channel.purge(limit=amount)


            await interaction.response.send_message(f"{len(deleted)} mesaj silindi.")
    except Exception as r :
        await interaction.response.send_message(f"hata:{r}")```
turbid condor
glad cradle
turbid condor
#

and then send an ephemeral followup

#

cuz i think if epehemeral is false the bot will delete the followup too

vapid parcel
timber dragon
#

"better"

#

You can call the variable anything you want

#

It is technically a client that interacts with the api

latent pier
glad cradle
#

also using Client you can implement your own prefix command logic

viscid hornet
latent pier
#

Axo woke

viscid hornet
#

i’ve seen prefix logic for Bot instances before

viscid hornet
latent pier
glad cradle
#

it's better to define it on a Client object because you are sure that you'll not miss anything out

glad cradle
viscid hornet
slate swan
#

Hi, is there any way i can clone a discord bot using some python code, I made a new bot on my server using discord.py, I want to make many instances of the same bot that execute the same code ( about 250 bots so i can't do it manually )
Any help would be appreciated

viscid hornet
golden portal
#

are you trying to do sharding

viscid hornet
slate swan
#

then you dont need it

slate swan
latent pier
#

Tokens (fake members)

viscid hornet
#

!rule tos

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

latent pier
#

He want online count i guess

viscid hornet
#

whats your use case for this?

viscid hornet
slate swan
#

New bot and 250 instances don't make much sense together squint

latent pier
#

I'm lawyer

slate swan
viscid hornet
golden portal
#

yes

latent pier
slate swan
viscid hornet
latent pier
slate swan
viscid hornet
slate swan
#

so basically i want to make 250 bots that with same code talk to each other

golden portal
#

that sounds like schizo activity

slate swan
#

reason for 250 bots is bc limit of roles is 250

latent pier
#

😭😭 what is she upto

viscid hornet
viscid hornet
latent pier
#

Now I doubt if she meant bot or ||User IDs||

slate swan
viscid hornet
#

|| someone struck a nerve ||

golden portal
#

i said 2 replies im not even being rude

slate swan
#

I see no reason to have multiple bot instances when it doesnt comes to sharding, sounds like a weird idea

#

what's even sharding?

viscid hornet
golden portal
#

eh she's not trying to shard she's just trying to make different bot join the same server with the same code, its possible but it's just against tos

latent pier
latent pier
viscid hornet
#

when it replicates

slate swan
latent pier
#

No one ever taught me this

formal basin
#

Hello guys, how can i check if a user is a webhook?

viscid hornet
latent pier
#

She want bots in same server shading works completely opposite

viscid hornet
latent pier
slate swan
formal basin
#

some nukes uses webhooks

#

so i need to check if the user nuking is a webhook

#

and delete the webhook

viscid hornet
latent pier
#

Webhook only spams

formal basin
golden portal
viscid hornet
latent pier
#

Axo seems experienced

viscid hornet
slate swan
latent pier
#

!d discord.AuditLogAction.webhook_create

unkempt canyonBOT
slate swan
latent pier
formal basin
#

i want when the user is a webhook

#

using if statment

viscid hornet
latent pier
#

User cannot be a webhook unless he creates it

viscid hornet
#

can webhooks even join servers?

formal basin
latent pier
formal basin
viscid hornet
golden portal
latent pier
#

Webhook can only send a message

viscid hornet
slate swan
#

might I ask what's a webhook, it sound similar to discord application but idk what's difference

viscid hornet
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
viscid hornet
formal basin
#

a bot gets invited to the server

#

then gets kicked

latent pier
#

Bot creates a webhook -> starts spamming

formal basin
#

then a webhook just nukes the server

latent pier
#

Don't ask where i got the experience 💀

formal basin
viscid hornet
#

webhooks can only be used for sending, editing and deleting messages

slate swan
latent pier
#

How else would you spam

formal basin
#

is what i mean

viscid hornet
# slate swan thx

dont go off and create 250 webhooks to fulfil a schizo fantasy. just run them on your own PC

viscid hornet
latent pier
slate swan
latent pier
#

Webhook cannot create channel

viscid hornet
latent pier
#

Bot does that

fast osprey
#

🤨

formal basin
#

but then created a webhook

#

then it just nuked the whole thing

viscid hornet
latent pier
#

Without bot it won't work

#

I want audit logs

viscid hornet
#

webhooks quite literally cannot do anything outside of a normal user

formal basin
viscid hornet
latent pier
slate swan
#

what's ratelimits?

viscid hornet
latent pier
viscid hornet
#

think of it like lag

slate swan
#

why everyone laughing, i'm here to learn

viscid hornet
#

discord will purposefully lag your requests if they’re in too quick succession

latent pier
#

Ray is much better explainer than us

crisp glacier
fast osprey
#

That's not what rate limits do lol

slate swan
#

oh

crisp glacier
#

Im jus trynna helpwait

fast osprey
latent pier
viscid hornet
# slate swan oh

solstice feels like a mum trying to calm down her 6 toddlers who all had sugary drinks before bed

crisp glacier
fast osprey
#

Discord sends headers on replies saying how many times it wants to allow you to do things, and if you do it more than that they start failing the requests

latent pier
#

I wonder if we're really 6 here?

crisp glacier
#

Solstices just too op

latent pier
#

Wise old man

#

We're just toddlers

formal basin
#

the bot was in the server

latent pier
viscid hornet
latent pier
#

That's what i was trynna explain

formal basin
meager rock
crisp glacier
latent pier
#

What does your antinuke contains

formal basin
latent pier
#

Seems dumb to me

formal basin
#

so it looked like the anti nuke didnt work

latent pier
viscid hornet
fast osprey
#

"Antinuke" as how most kids write them are just a band aid for people not understanding how permissions work. Just secure your damn servers

meager rock
#

^ don't give sensitive permissions to random bots

viscid hornet
latent pier
#

Recently one of my friend's bot crossed 100k servers it has only antinuke

fast osprey
#

People like stupid shit that doesn't work

#

Doesn't make it good to make it

viscid hornet
latent pier
formal basin
viscid hornet
#

could you clone a discord server?

meager rock
#

5 channels/20seconds is crazy

latent pier
viscid hornet
#

besides messages other people have sent, theoretically you could just copy it

formal basin
viscid hornet
formal basin
#

not 20

blazing beacon
latent pier
latent pier
blazing beacon
meager rock
#

anti nuke bots are quite useless just get trustable people as moderators and admins

fast osprey
#

If you're too dumb to not give random bots admin, why would you be smart enough to not give the random bot a higher role than your antinuke so it can just kick it

formal basin
meager rock
#

I've seen servers where bots have higher roles than admins

#

cause they're moderation bots 😮

latent pier
#

That's normal nowadays

viscid hornet
viscid hornet
latent pier
viscid hornet
meager rock
#

anyways, what's recent with discord bots? Anything net in the API?

latent pier
meager rock
viscid hornet
slate swan
#

@viscid hornet ig this? not sure

#

!d discord.Template.create_guild

unkempt canyonBOT
#

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

Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) using the template.

Bot accounts in more than 10 guilds are not allowed to create guilds.

Changed in version 2.0: The `region` parameter has been removed.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
meager rock
#

the creator of that bot didn't even add a check to make sure the person they're kicking is a moderator or SAME PERSON

latent pier
viscid hornet
meager rock
latent pier
#

After that i had to add if member == ctx.author

viscid hornet
latent pier
meager rock
#

ah that rolled out with slash cmds iirc

latent pier
slate swan
#

I remember my first attempt to help someone with discord.py

meager rock
slate swan
#

lucky that marvin didn't obliterate me notlikeduck

meager rock
#

🙈 time to start working on my API wrapper again

latent pier
#

notlikeduck i remember this channel as asking for help as dumb begginner, now I'm able to help others

viscid hornet
slate swan
#

real 😔

viscid hornet
viscid hornet
slate swan
viscid hornet
#

dpy help grind dont stop

fast osprey
#

🤨

viscid hornet
#

damn you suck at helping

#

real helpers know theres no days off 👍🏽

#

@slate swan can you confirm

slate swan
latent pier
#

And quicker

viscid hornet
slate swan
viscid hornet
latent pier
#

There's no one who need help rn

viscid hornet
#

fair enough

latent pier
slate swan
latent pier
slate swan
#

it was relatable double_noice

latent pier
shrewd apex
#

mine just got over

glad cradle
#

pls make the cache fully, and i mean fully, customizable / manageable

shrewd apex
#

i have already given up on sarth bro gonna work for 2 days then go for a 2 year hiatus 💀 his updates are slower than some unknown manga series author

young dagger
#

Is there any way to detect this kind of activity?

slim bloom
#

@viscid hornet ```py
import discord
from discord.ext import commands
from discord import app_commands
import os, mysql.connector, time

color_saura = discord.Color.from_rgb(173, 216, 230)

class Ping(commands.Cog):
def init(self, bot):
self.bot = bot

    self.database = database = mysql.connector.connect(
      host=os.getenv("MYSQL_HOST"),
      port=os.getenv("MYSQL_PORT"),
      user=os.getenv("MYSQL_USER"),
      password=os.getenv("MYSQL_PASSWORD"),
      database=os.getenv("MYSQL_DATABASE")
    )

@app_commands.command(name="ping", description="Muestra mi latencia")
async def ping(self, interaction: discord.Interaction) -> None:
    bot_latency = round(self.bot.latency * 1000)
    cursor = self.database.cursor()
    start_time = time.time()
    cursor.execute("SELECT 1")
    result = cursor.fetchone()
    cursor.close()
    database_latency = round((time.time() - start_time) * 1000, 2)
    embed = discord.Embed(title="Pong", color=color_saura)
    embed.add_field(name="Bot", value=f"{bot_latency}ms", inline=True)
    embed.add_field(name="Database", value=f"{bot_latency}ms", inline=True)
    await interaction.response.send_message(embed=embed)

async def setup(bot):
await bot.add_cog(Ping(bot))```

meager rock
unkempt canyonBOT
#

The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member.

It is a dictionary with the following optional keys:

type: An integer denoting the type of message activity being requested.

party_id: The party ID associated with the party.

slim bloom
#

What could I change or improve?

meager rock
shrewd apex
meager rock
shrewd apex
#

29th this month?

meager rock
#

but I need more people

young dagger
meager rock
shrewd apex
#

i see noice noice

shrewd apex
meager rock
young dagger
viscid hornet
unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
young dagger
meager rock
#

!d discord.ActivityType

unkempt canyonBOT
#

class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity). This is used to check how to interpret the activity itself.
young dagger
#

I want to detect when members are sending game invites in channels

#

^^ This kind of stuff

meager rock
#

message.activity["type"] will return the activity type integer of ActivityType.listening in this case

#

Bruh what the bot doesn't embed code anymore?

#
class ActivityType(enum.IntEnum):
    """Type of activity."""

    GAME = 0
    """The user is playing a game."""
    STREAMING = 1
    """Activity where user is streaming."""
    LISTENING = 2
    """Listening activity."""
    WATCHING = 3
    """Watching activity."""
    CUSTOM = 4
    """This activity is a custom status."""
    COMPETING = 5
    """Compoeting activity."""
shrewd apex
#

it should

#

maybe too big

meager rock
#

it was literally the same as what I sent rn

young dagger
meager rock
#

no

young dagger
#

No this wont' work thinkopera

meager rock
#

type instead of message.content in the square brackets

shrewd apex
meager rock
#

this will also raise an error if there's no activity

shrewd apex
#

its optional so u would want to check if its present

meager rock
#

use .get() man

shrewd apex
#

once thats done throw it in some match case or if else stuff to perform whatever u want

meager rock
#

Asher do you wanna leetcode with me

shrewd apex
#

sure from tmrw tho ig

meager rock
#

sure I'm following strivers's A-Z sheet

shrewd apex
meager rock
#

I need someone who can keep pushing me for it

shrewd apex
meager rock
shrewd apex
shrewd apex
meager rock
young dagger
shrewd apex
#

cool

meager rock
#

( it's free, not a promo)

shrewd apex
#

add another check

meager rock
#

you just need to check for message.activity, if that exists type will exist as well

#

probably a ternary statement

meager rock
shrewd apex
#

damn

#

oh its like notion kind of like a todo list

young dagger
shrewd apex
#

sure

meager rock
#
activity = "yes" if message.activity else "No"
``` here's something cleaner
meager rock
#

( for your case )

shrewd apex
#

aight cya have plans for dinner tonight

young dagger
shrewd apex
#

outside with friends lol college exams got over

meager rock
# young dagger What is 4 and 5?

This includes activities that appear on your profile
.CUSTOM is the custom status you sent on discord
. COMPETING is some other activity that discord added for games

meager rock
young dagger
meager rock
#
  • check if message.activity exists
  • If it does check the type of the activity
  • If it's 0, delete the message
#

wait you want everything other than games

young dagger
#

Yes

meager rock
#

only gaming and Spotify activities can be embedded from I've seen

young dagger
#

It says type 1

#

At least for League of Legends game invites

#

Spotify is type 3

young dagger
meager rock
#

Apparently enums for message activities are different

#

use this instead

#

1 2 and 5 are for games

young dagger
#

Hmh I'm doing something wrong

meager rock
#

message.activity(1,2,5) is wrong

slate swan
#

how to add icon to a role using discord.py library?

meager rock
#
x = {"type": 2}
print(x["type"] in (1,2,5))
``` you can use the `in` statement
meager rock
unkempt canyonBOT
#

await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the role.

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

All fields are optional.

Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.

Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
slate swan
#

i already have img installed on my directory

golden portal
#

read the image with open to get the bytes of that file, as in ```py
with open('file/path.png', 'rb') as r:
byte = r.read()

golden portal
#

'rb' is a mode to read in binary

slate swan
bright wedge
#

how can I set through the bot the permissions on a slash command?

#

so that they also apply to the example above (they can also be seen in Server Settings/Integrations)

golden portal
#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
golden portal
#

should be this

bright wedge
slate swan
#

stickers.emoji display this \ud83d\ude31

#

will this worrk if i later decide to create sticker with that argument as parameter to emoji?

golden portal
#

yes it should be, from the look of the docs it accepts emoji

#

that's just a unicode version of that emoji so it shouldn't be a problem

slate swan
#

thx

bright wedge
empty egret
#

Anyone a Ohio skibidi fanum tax Ohio rizzler

viscid hornet
unkempt canyonBOT
slate swan
#

name confuses me a bit

viscid hornet
#

whats that with?

slate swan
#

role icon not emoji

viscid hornet
#

!d discord.Role.icon

unkempt canyonBOT
#

property icon```
Returns the role’s icon asset, if available.

Note

If this is `None`, the role might instead have unicode emoji as its icon if [`unicode_emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role.unicode_emoji) is not `None`.

If you want the icon that a role has displayed, consider using [`display_icon`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role.display_icon).

New in version 2.0.
viscid hornet
#

!d discord.Role.display_icon

unkempt canyonBOT
golden portal
viscid hornet
# slate swan role icon not emoji

im guessing icon is more general and includes unicode emojis (ie. this is valid: ❤️, and so is this: 😄) but display_icon will give you the custom role icon (if available)

#

so icon can be:

  • a custom emoji
  • a default emoji
  • None

but display_icon can only be:

  • a custom emoji
  • None
young dagger
bright wedge
#

any idea how i can do that?

golden portal
#

im not sure what is that since its not in english

bright wedge
viscid hornet
#

so for example, say a command has a cooldown of 30s: mods and admins and whatnot could be able to use it instantly

golden portal
#

that can't be set through the bot, only perms

bright wedge
#

so its only for the server admins

golden portal
#

yea

slate swan
#

!d discord.Guild.icon

unkempt canyonBOT
slate swan
viscid hornet
gritty thorn
#

Can’t connect modules

fast osprey
#

This should raise an error if you're running dpy 2.x

gritty thorn
#

So I should update

fast osprey
#

If you're running on lower than 2 it won't work at all lol

gritty thorn
viscid hornet
#

yes

gritty thorn
bright wedge
# golden portal yea

any way to make the slash command/commands visible only for some members (like mods? )

fast osprey
#

The integrations UI on the server

fast osprey
bright wedge
gritty thorn
#

Lemme check

fast osprey
#

Your code doesn't know all of the roles in all of the servers a bot could be in

fast osprey
#

Well the api doesn't change to accommodate that

bright wedge
#

So it's not possible and it has to be done manually?

fast osprey
#

Plus they don't want you to have to redeploy code every time server managers decide they want to permission things differently. It's very easy on the UI

#

All you can do is limit on default permissions, which are global. Not roles

gritty thorn
#

I forgot

gritty thorn
fast osprey
#

If that's the library you're using then yeah

gritty thorn
#

3.7

fast osprey
#

That is not a version of dpy lol

#

Man is 3 years in the future

gritty thorn
#

Oh

#

Is 2.3

fast osprey
#

Then yeah the code you have should throw an error if you try to run it

gritty thorn
fast osprey
#

that's the most recent stable version

#

The code you have, if run against dpy 2.x, will error. Which means if you're running it and not getting an error, you aren't running it against dpy 2.x

wicked gull
#

are there any free python courses anyone would recommend for someone starting from no experience

fast osprey
#

This typically means either a) you are running against a different python installation than what you're looking at with pip or b) you have other libraries installed that are interfering

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.

wicked gull
#

thank you

gritty thorn
#

is not work

#

i was finding the error

pale zenith
#

#bot-commands

viscid hornet
#

but yeah i'll go there

fast osprey
pale zenith
#

weird thing however, that's the 2.x logging format

#

and that error would show up higher up in the log trace, we can only see text after a print that occurs within on_ready

slate swan
#

please and thank you

viscid hornet
#

as for your mute issue, define "spaces" for me

#

also dont use py except Exception as e: print(e) # or some equivalent
it doesn't output traceback

slate swan
viscid hornet
#

if you want to send a message with an error, use the traceback module (its a stdlib module): py import traceback
and then use: py traceback.format_exc()

#

or .format_exception(e) but idk the difference 🤷

viscid hornet
unkempt canyonBOT
#

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

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

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
slate swan
slate swan
viscid hornet
#

!d discord.ext.commands.Context.command

unkempt canyonBOT
slate swan
#

so you think timeout is better than roles?

viscid hornet
#

thats like asking if leaving your bread out in the sun for the day is better than a toaster

#

theres no comparison

#

well if you wanted to have a place where they can talk, like a "jail" of some sorts, or some other edge case then yes, roles would be used

#

but im assuming you just want to make a mute command and call it a day

viscid hornet
#

i was thinking about getting bread while writing that

fast osprey
#

and if you're just making a thin wrapper over timeout, there already exists a timeout command natively that builds in proper auditing and access controls. Making one yourself that doesn't add anything is a degradation of functionality

viscid hornet
young dagger
viscid hornet
#

holy fuck there is

viscid hornet
#

ie. if you wanted to have specifics or additional operations on timeouts, you would have to use roles and role permissions

viscid hornet
blazing beacon
blazing beacon
#

but you do you man

wispy falcon
#

how do i run my discord.py via a .bat file? like i see people that can contol their bot from a .bat
for example:

vapid parcel
slate swan
slate swan
#

yeah

wispy falcon
#

alright

#

thx

wispy falcon
#

i closed the bat and its still online..

fast osprey
#

Is there any particular reason you want this extra level of indirection?

slim bloom
#

@viscid hornet code is good? ```py
@bot.event
async def on_shard_ready(shard_id):
print(Fore.LIGHTGREEN_EX + f"Shard {shard_id} is now ready.")

@bot.event
async def on_shard_connected(shard_id):
print(Fore.LIGHTGREEN_EX + f"Shard {shard_id} has been connected.")

@bot.event
async def on_shard_resumed(shard_id):
print(Fore.LIGHTYELLOW_EX + f"Shard {shard_id} has been resumed.")

@bot.event
async def on_shard_disconnect(shard_id):
print(Fore.LIGHTRED_EX + f"Shard {shard_id} has been disconnected.")
await bot.reconnect()```

fast osprey
wispy falcon
fast osprey
#

Right

wispy falcon
#

how can i make the question pop up after the bot has been logged into?

viscid hornet
#

also why are you censoring the time 😭

wispy falcon
wispy falcon
#

i dont want random people to know my time

viscid hornet
wispy falcon
viscid hornet
#

so why do it then 💀

wanton current
#

expose exact location via time zone

blazing beacon
#

my opps hunting my timezone

#

gyatta lay low 🤫

wispy falcon
wispy falcon
viscid hornet
wanton current
#

yeah that's the joke

viscid hornet
viscid hornet
#

sorry bro im bad w jokes 😭

viscid hornet
wispy falcon
wispy falcon
fast osprey
#

If your school wants you to add random layers of indirection for no reason, that's a shitty school

wispy falcon
#

i lied🤷

viscid hornet
viscid hornet
slim bloom
slate swan
#

is there a way to secure you account from rate limited?

viscid hornet
#

they're a limit on the rate of your action

wispy falcon
viscid hornet
wispy falcon
slim bloom
#

XD

slate swan
#

so i don't rich the limit on the rate of my actions

viscid hornet
#

discord doesnt specifically outline ratelimits

#

so the only way to tell is to do the processes yourself and see what gets hit by ratelimits and what doesnt

viscid hornet
#

i have a feeling you dont know python basics

slate swan
#

i might try to time.sleep(1) but idk if my bot can run on every s

wispy falcon
slim bloom
viscid hornet
slate swan
viscid hornet
#

i have a feeling you dont know python basics and dpy explicitly advises you learn that before learning how to use their library.

#

!resources ⬇️

unkempt canyonBOT
#
Resources

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

slate swan
#

is asyncio built-in or i have to instsall it?

wispy falcon
viscid hornet
viscid hornet
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.

slate swan
#

good

slim bloom
#

!paste | roblox

#

ignore that

viscid hornet
#

since its not counted in the command

slim bloom
#

!paste se

viscid hornet
#

!paste | hehehaha

#

welp, bot went offline 💀

slim bloom
#

!paste py from asyncio import asyncio

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.

slim bloom
#

5

viscid hornet
#

probably just a reboot 🤷

#

@wispy falcon did you get the paste link?

wispy falcon
#

yh

viscid hornet
#

send it here

wispy falcon
#

no

viscid hornet
#

what was the point of pasting it anyway if you weren't gonna send it?

wispy falcon
#

ill try to fix it myself

viscid hornet
wispy falcon
#

i did try, but aii

wispy falcon
blazing beacon
#

goodluck

viscid hornet
unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

viscid hornet
#

there's a reason this is a rule

wispy falcon
#

im js askin it how to fix my problem

blazing beacon
#

chat gpt doesnt have any updated info about dpy

viscid hornet
#

and its because gpt is terrible at fixing code

wispy falcon
#

no one here can help

viscid hornet
viscid hornet
#

im right here yk, and so is smile guy and so is aluminium

blazing beacon
blazing beacon
#

its like trying to diagnose cancer but you cant see the person and u cant touch them

viscid hornet
# wispy falcon yeah at the end

!res | yeah bro you got no idea how python works if you're wondering why having a print before the run statement means that it gets printed before the dpy logging

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.

slate swan
#

when making function in discord.py

correct me if i'm wrong

async def my_func(guild):
  pass

@client.event
async def on_ready():
  guild = discord.utils.get(client.guilds, name="my server")
  await my_func(guild)
slate swan
#

thx

viscid hornet
#

same for any function in any scenario

slate swan
#

ok

#

so basically rule of thumb, if my_func have any async func, the parent has to be async too

glad cradle
wanton current
blazing beacon
viscid hornet
viscid hornet
blazing beacon
glad cradle
blazing beacon
viscid hornet
viscid hornet
wispy falcon
finite salmon
wispy falcon
wispy falcon
slate swan
viscid hornet
# wispy falcon why

because you wondered why this: ```py
print(1)
print(2)

produces this ```py
1
2```
and not this: ```py
2
1```
viscid hornet
#

that should solve your issue 👍

wispy falcon
finite salmon
wispy falcon
#

bro wth

viscid hornet
slate swan
viscid hornet
#

it only wouldnt know about it if you tried to reference guild when guild didnt exist

slate swan
#

i see

viscid hornet
#

so if you did: py async def my_func(something): print(guild.id)
this would not work because you're referencing guild which doesnt exist in the function

finite salmon
viscid hornet
#

!e ```py
def func(a):
print(b + 1)

func(13)```

unkempt canyonBOT
#

@viscid hornet :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     func(13)
004 |   File "/home/main.py", line 2, in func
005 |     print(b + 1)
006 |           ^
007 | NameError: name 'b' is not defined
viscid hornet
#

however if i change the parameter to b