#discord-bots

1 messages · Page 307 of 1

naive briar
#

What?

mighty pilot
naive briar
#

You're comparing a user object to a boolean

#

!d discord.User.bot

unkempt canyonBOT
fiery girder
#

it does give me the role but it dont work with old messages like after restarting bot old messages dont give role

mighty pilot
#

Ah so it'd be if user.bot == True or false

vocal laurel
#

meaning he did it correct right?

#

have u made a help post in the dpy server?

mighty pilot
#

Yea I'm just dumb today I guess lol

fiery girder
vocal laurel
#

lol

fiery girder
#

but it dont work on messages after starting the bot

#

like i setup reaction role on a message after restartnig the bot the message will no longer work with bot

mighty pilot
#

I think the messages have to be cached or you have to fetch the message. Not 100% sure on that tbh

vocal laurel
mighty pilot
final iron
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add), this is called regardless of the state of the internal message cache.

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
fiery girder
#

So I just have to use raw instead of normal

#

I'll do it after the power is back on cause it's off right now

glad cradle
#

hi oauth2 question, what are all the endpoints that accept an access_token (bearer token)? i thought they were all the enpoints with a @me but that's not true

wintry crown
#

this is a chill server

slate swan
tall wharf
#

so, for some reason some commands work and some don't. I've marked with red the commands that don't work. What did I do wrong?

naive briar
#

Please send code as texts

#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

tall wharf
#

one sec

#
from nextcord.ext import commands


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

    @commands.command()
    async def test(self, ctx):
        await ctx.send("This is a test!")
    
class basic(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def help(self, ctx):
        await ctx.send("If you need help with the bot, please contact cpt_w0lf on Discord, thank you! ")
    
class basic(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def wiki(self, ctx):
        await ctx.send("Here is the main page of the Stellaris Paradox Wiki site: https://stellaris.paradoxwikis.com/Stellaris_Wiki ")

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

    @commands.command()
    async def patch(self, ctx):
        await ctx.send("Stellaris is currently running on patch 3.9.2 on PC!") ```
#

this is the entire code I've written for the commands

naive briar
#

It is most likely because you're overriding the previous classes

tall wharf
#

so I have to write them in a different class?

slate swan
#

no just add them to one class

naive briar
#

You can have multiple commands in the same cog

tall wharf
#

so, how do I solve this?

#

cause the first and last command work, but those in the middle don't

naive briar
tall wharf
#

aight

twin widget
#

i have a quetion

#

question*

#

how do i add slash commands to my bot

final iron
# twin widget how do i add slash commands to my bot

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

Gist

discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.

twin widget
#

can i get a TL;DR?

thin raft
twin widget
#

fair enough

thin raft
#

it is already pretty small imo

twin widget
#

but i cant find a single reference to slash commands in that forum

#

are cogs necessary for slash commands?

slate swan
thin raft
#

slash commands are called app commands in dpy

slate swan
final iron
#

Nothing to do with slash commands huh

twin widget
#

can i question something

#

what is init

slate swan
#

class constructor

thin raft
slate swan
final iron
thin raft
#

make sense

slate swan
final iron
twin widget
#

idk why it does an error

final iron
#

Oh boy

#

Don't sync in on_ready

twin widget
#

i suck at this bro 😭

final iron
#

Sync in setup_hook, or better yet create a command for it

#

Auto Syncing Sucks

twin widget
#

is this better?

#

i removed .sync

final iron
#

You completely ignored what I said

slate swan
final iron
#

Nice

twin widget
#

you said dont sync in on_ready

#

so i removed .sync 😭

slate swan
#

you def need to learn python before doing a discord bot

twin widget
#

I DID 😭

final iron
#

Yes, and I told you to do it in setup_hook or create a command for it 💀

#

tree() isn't a thing

twin widget
final iron
#

It's an event

thin raft
#

!d discord.ext.commands.Bot.tree

final iron
unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
final iron
#

Not a function/method

slate swan
thin raft
twin widget
#

i copied everything from stack overflow yall 😭

final iron
#

Do you have to subclass your Bot instance to overwrite setup_hook or would a normal event decorator suffice

twin widget
#

what are these gigantic words bro

thin raft
#

can you do something like

@bot.event
async def setup_hook():
  pass
``` ?
final iron
#

That's what I'm asking

thin raft
twin widget
#

please tell me what that does 😭

final iron
thin raft
#

it literally does nothing

final iron
#

Actually read the guide, then ask questions

#

You're asking quesions before reading the guide, and it shows

twin widget
#

It's hard to read

#

Like what's a cog

twin widget
#

okay okay

final iron
twin widget
#

Isn't that what you just sent me 33 minutes ago

#

34 now

#

I need to give this a good read

#

AHA

#

CommandTree.sync

#

Is that what I'm supposed to look for 😭

final iron
twin widget
#

am i supposed to look for commandtree.sync

#

i dont understand big bro 😭

final iron
#

I linked you a specific example on how to create slash commands outside of cogs

twin widget
#

ok

#

my dumbahh is never gonna make more slash commands again 😭

final iron
#

They're very similar to prefixed commands

twin widget
#

THEN WHY ARENT THEY AS SIMILAR 😭 😭

#

why do i have to sync them in on_ready 😭

#

:0

#

i think i struck gold

#

is this what i need?

quick brook
#

Please consider reading the examples given below

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

twin widget
#

no i screenshotted the code

#

i still havent pasted it in yet

quick brook
twin widget
quick brook
#

That one above

twin widget
#

yes

#

im trying to read

quick brook
twin widget
#

so

#

there is no reading involved

#

and i have the coding power of a potato

#

so i need to talk about my findings

twin widget
final iron
quick brook
final iron
#

It specifically tells you to not sync your commands in on_ready, so I'm not sure where you're getting the idea that you should

twin widget
#

okay okay

#

reversed

#

what else[

quick brook
#

copy_global_to only copies the global commands to your guild. It doesn't sync it for you

twin widget
#

why do i need all that for slash commands

quick brook
twin widget
#

arent normal commands sent to discord too

final iron
#

No

quick brook
#

Prefixed is handled internally by dpy. Slash commands are handled by Discord directly

twin widget
#

why arent slash commands handled by dpy

final iron
#

Because they're integrated in the UI

twin widget
#

OHHHHHHHHHHHHHH

final iron
#

How would they appear in Discord's UI if Discord isn't aware they exist

twin widget
#

thank you for explaining

#

anyways

#

im gonna send you all of the bots code

quick brook
#

im gonna be busy for the whole entire day but later today i can code review it

twin widget
#

be aware i've used an example from rapptz's github page

#

so

final iron
#

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

glad cradle
slate swan
glad cradle
serene egret
#
        @discord.ui.button(label="Claim Ticket", style=discord.ButtonStyle.primary, custom_id="claim")
        async def claim(self, interaction: discord.Interaction, button: discord.ui.Button):
            user_name = interaction.user.name
            if interaction.channel.name == f"{interaction.user.name}-ticket":
                embed = discord.Embed(title=f"You can't claim the ticket, <@{interaction.user.id}>", color=0x7289da)
                await interaction.response.send_message(embed=embed)
            else:
                await interaction.message.edit(view=ClaimButtonTwo())
                embed = discord.Embed(title=f"The ticket claimed by {interaction.user.name}",color=0x7289da)
                await interaction.response.send_message(embed=embed)
                await interaction.channel.edit(topic=f"Claimed by {interaction.user.name}")

why the the channel name is come_-ticket and this is equal to {interaction.user.name}-ticket and this isnt work?

slate swan
#

cause you cant put dots in channel names

#

and your name is come_ excluding dots

serene egret
#

ok

frozen trellis
#

can someone send me the code for copying someone elses messages like if they say “wsg” then ur account copies it and sends it too more like mocking

frozen trellis
#

well how do i figure it out

final iron
#

So a user will do something like !mock you're so dumb, and the bot replies with you're so dumb?

frozen trellis
#

like for example, i do !mock @slate swan And my account starts sending the same messages as him

final iron
frozen trellis
#

continually

#

until i stop code

frozen trellis
#

i have been trying for like 3 hours:(

#

and im kinda new so i dont know

#

i have tried so many stuff and it just wont work

#

it would he appreciated if you could help

final iron
frozen trellis
#

like 2 minutes

final iron
#

Okay, that makes it easier

final iron
frozen trellis
#

I deleted all of it:(

#

i gave up like 10 minutes ago

#

after continuous trying man

#

i can send you one i saved tho

#

If you want

final iron
#

So, you could track the users to mock with a list

#

Let’s create the command first

frozen trellis
#

okay come dms if you want

final iron
#

Do you know how to create them?

frozen trellis
final iron
#

Yes

frozen trellis
#

Yeah i know that

final iron
#

Alright, write one real quick and send the code

frozen trellis
#

wait ill send in dms

#

this is what i had a few minutes ago

final iron
#

Send it in here

frozen trellis
#

ok

final iron
#

There’s no point in using DMs

frozen trellis
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.author.id == YOUR_USER_ID:
        channel = bot.get_channel(YOUR_CHANNEL_ID)
        await channel.send(message.content)

    await bot.process_commands(message)

bot.run('YOUR_BOT_TOKEN')
#

I dont want it on a bot account tho

#

because i cant really add it into other servers

#

Idk if the code is right

final iron
#

Well unfortunately we don’t help people create self bots :/

frozen trellis
#

will it work on a bot

#

?

#

cuz i can do it on a bot too just in my seever

final iron
frozen trellis
#

Would be appreciated mane

final iron
#

Do you know about the commands extension?

frozen trellis
final iron
#

It’s the proper way to create prefixed commands with discord.py. Creating them in on_message has a lot of downsides

#

Let me find you the docs and some examples real quick

frozen trellis
#

Okay man thank you

final iron
#

Here’s a structure I would recommend

#

Create a bot variable with the list of people you want to be mocking

#

The command will add a person to that list

#

In your on message you check if they’re in your list, and if they are you send the message

dire mason
#

Can someone explain cogs to me?

quick brook
#

?tag cogs vs ext

Difference between cogs and extensions

Extensions are files that are loaded, think of them as modules that the discord.py library imports when you call load_extension. After the import happens, a setup function is called, and is passed the Bot instance that it was loaded into....essentially module.setup(bot). That is it, there is no more to extensions...typically this setup function calls add_cog which will be described next, however there is no requirement that they do so.

A Cog is a class that inherits from commands.Cog and is added to the bot's list of cogs through add_cog, these classes typically house commands and act as a "category" for these commands. It can also house listeners for events such as on_message or on_member_join, etc.

tl;dr Extensions are imported modules, cogs are classes

dire mason
#

hmm

quick brook
compact stag
#

hey, looks like that my discord bot is only seeing themselves in a guild? they have the intent set to see members, but it's being funky

#

figured it out -- turns out i had to specify discord member intents in the file's intents, strange that it was working yesterday but didn't today

quick brook
compact stag
#

this is in DMs only, just for me, and i don't think bots are capable of integrating commands in DM channels beyond on_message events

quick brook
compact stag
quick brook
#

Slash commands is a different story that I never tested, but I've tested prefixed commands and know it works

compact stag
#

noted

final iron
#

blud done got his messages deleted

#

Don't tell me you got muted lol

dire mason
#

nah

#

forgot to remove my token LMAO

#
Traceback (most recent call last):
  File "C:\Users\brian\PycharmProjects\NoteWizard\main.py", line 16, in <module>
    @bot.event()
     ^^^^^^^^^^^
TypeError: Client.event() missing 2 required positional arguments: 'self' and 'coro'
import colorama
from colorama import Fore, Style

import discord
from discord.ext import commands

TOKEN = ""

bot = commands.Bot
class NoteWizard(commands.Bot):
    def __init__(self):
        super().__init__(
            intents=discord.Intents.all()
        )

@bot.event()
async def on_ready():
    print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
    game = discord.Game("Playing Music")
    await bot.change_presence(status=discord.Status.online, activity=game)

async def setup_hook(self):
    await self.load_extension("cog_ext")


NoteWizard().run(TOKEN)
final iron
#

Oh boy

#

Lots of wrong things

dire mason
#

Am I that dumb?

#

no

#

I deny you wanting to change stuff

final iron
#

First, if you're subclassing commands.Bot() you'll need to create cogs

#

bot = commands.Bot makes literally 0 sense

#

I know you did that because when you tried to create the event you got an undefined/attribute error

dire mason
#

but

final iron
#

You'll also want to put setup_hook inside your NoteWizard class as outside of the class it won't be called

dire mason
#

but, like @bot.event()

final iron
#

?

#

The error doesn't matter

#

To fix your other issues the event will be removed anyway

#

Furthermore, you shouldn't be changing your presence in on_ready for a couple of reasons, just do it in setup_hook or better yet, do it in your Bot() constructor

#

And, unless you do need every single intent you shouldn't be using all()

dire mason
#

@final iron stop making my life hard

final iron
#

?

#

You came for help and you got help

vocal laurel
#

also the error u were looking for was that bot.event() calls it even tho its meant to be bot.event

final iron
#

It won't ever be called anyway

vocal laurel
#

ye

#

thats only for a command which he prob got confused between

final iron
#

What?

#

No, it won't ever be called because bot isn't an instance of commands.Bot()

dire mason
#

Stop making me feel like im stupid

vocal laurel
vocal laurel
dire mason
#

Im jokimg

final iron
dire mason
#
import colorama
from colorama import Fore, Style

import discord
from discord.ext import commands

TOKEN = ""
class NoteWizard(commands.Bot):
    def __init__(self):
        super().__init__(
            intents=discord.Intents.all()
        )

    async def setup_hook(self):
        await self.load_extension("cog_ext")

NoteWizard().run(TOKEN)

@final iron Look better?

vocal laurel
dire mason
#

Where would I put the on_startup event?

final iron
#

Nothing

dire mason
#

the one that prints that its online?

final iron
dire mason
#

Not yet.

#

I want to add it.

#

Where would it go?

final iron
#

Well it doesn't exist

#

Unless you're creating a custom event

dire mason
#

Im saying, im gonna add it

#

Would I put it in the Cog?

final iron
#

It's not a thing

#

You cannot add it

#

Doesn't exist

dire mason
#

what I just had?

vocal laurel
#

if a on_startup event in ur meaning means when the bot starts up on, then you are talking about setup hook

dire mason
#

@bot.event()
async def on_ready():
print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")

vocal laurel
#

setup hook only runs once and then is when the bot starts up

final iron
#

on_ready is different from on_startup

vocal laurel
final iron
#

Anyway, you would have it in a cog

vocal laurel
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
vocal laurel
#

read the bottom part

dire mason
#

so

#

It'll be bad to add?

#

It wont be reliable?

vocal laurel
#

no

#

its just a warning

final iron
dire mason
#

Yeah

vocal laurel
#

so if ur putting smth that u only want to happen once, then you should prob put in setup_hook

dire mason
#

okay/

#

So i'll put it in that class?

vocal laurel
#

what? and what class

dire mason
#

class NoteWizard(commands.Bot):
def init(self):
super().init(
intents=discord.Intents.all()
)

vocal laurel
#

so what are you going to put in it?

dire mason
#

I meant under it

vocal laurel
#

same thing

dire mason
#

But the on_ready event.

vocal laurel
#

ok sure thats fine just dont put the decorator

#

but if you want, you can put it in a cog as a listener

dire mason
#

which is more effiecent?

vocal laurel
#

they both do the same thing

#

its up to u if u want more code in main file or not

dire mason
#

main file would be better

vocal laurel
#

ok sure

dire mason
#

In my opion since it'll be a little more organized.

vocal laurel
#

i disagree but if thats what u wanna do then sure

dire mason
#

and the decorator is the @bot.event?

vocal laurel
#

yes

dire mason
vocal laurel
#

but if u wanted to hear what i would do, i would create a file in the cogs folder called events.py and put all my events in there that way its easier but thats just how i would do it

dire mason
#

But since im not that smart

#

that'll just drive me insain

vocal laurel
vocal laurel
dire mason
#

Eh what the fuck, alright help me with it

vocal laurel
#

ok

#

do u have a cogs file setup?

dire mason
#

Yeah

vocal laurel
#

and a file inside of it called events.py?

dire mason
#

Do you want me to create a directory? or just another file

#

oh

vocal laurel
#

oh mb i meant cogs folder

dire mason
#

haha 😅

vocal laurel
#

so create a cogs folder and inside of that create a file called events.py or whatever u wanna call it

dire mason
vocal laurel
#

no no u want a folder called cogs

#

and inside of that folder u want that events.py file

dire mason
vocal laurel
#

yes

dire mason
#

alr

vocal laurel
#

ok show me ur main.py file code (also u can delete cog.py)

dire mason
#

thats used for all client sided events such as on_start and such wise?

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

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.guild and message.guild.me.guild_permissions.ban_members:
            await message.author.ban(reason="no speek") # very good reason

    # doing something when the cog gets loaded
    async def cog_load(self):
        print(f"{self.__class__.__name__} loaded!")

    # doing something when the cog gets unloaded
    async def cog_unload(self):
        print(f"{self.__class__.__name__} unloaded!")

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

But what about all this in my cog.py file?\

#

This is my main.py

import colorama
from colorama import Fore, Style

import discord
from discord.ext import commands

TOKEN = ""
class NoteWizard(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="w.",
            intents=discord.Intents.all()
        )

    async def on_ready(self):
        print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")

    async def setup_hook(self):
        await self.load_extension("Cog.ext")

NoteWizard().run(TOKEN)
vocal laurel
#

hmm

dire mason
#

@vocal laurel

#

ofc

vocal laurel
#

in ur setup_hook u need to load the ext cogs.events

#

so Cog.ext -> cogs.events

dire mason
vocal laurel
#

now u wanna add ur on_ready as a listener as u did with ur on_message

#

and with ur setjup func in ur events.py file, make sure u do await bot.add_cog(WizardCog(bot))

dire mason
#

you want the load and unload thing also?

vocal laurel
#

wym

dire mason
#
# doing something when the cog gets loaded
    async def cog_load(self):
        print(f"{self.__class__.__name__} loaded!")

    # doing something when the cog gets unloaded
    async def cog_unload(self):
        print(f"{self.__class__.__name__} unloaded!")
dire mason
vocal laurel
#

ok

#

u can leave that

dire mason
#

yes or no

#

alr

dire mason
# vocal laurel u can leave that
import colorama
from colorama import Fore, Style

import discord
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_start(self):
        print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")

        async def cog_load(self):
            print(f"{self.__class__.__name__} loaded!")

        async def cog_unload(self):
            print(f"{self.__class__.__name__} unloaded!")
            
async def setup(bot):
    await bot.add_cog(WizardCog(bot))
#

looks all good with you?

vocal laurel
#

yes

#

wait no

dire mason
#

wonderful

vocal laurel
#

in the brackets of the listener put in "on_ready" that way it knows that ur talking about on_ready and not on_startup

dire mason
#
@commands.Cog.listener(on_ready)
    async def on_ready(self):
        print(f"{Fore.GREEN}Note Wizard ONLINE{Style.RESET_ALL}")
dire mason
vocal laurel
#
@commands.Cog.listener("on_ready")
async def on_startup(self):
#

cuz on_startup doesnt exist like told before

dire mason
#

hm

vocal laurel
#

so when u put in the event in the brackets, then discord knows what event ur talking about

dire mason
#

wow, how the fuck am I going to manage to make a bot

dire mason
naive briar
dire mason
#

Im a dumbass see and not smart.

vocal laurel
dire mason
#

yeh

dire mason
vocal laurel
#

u want slash or prefixed?

dire mason
#

slashed

vocal laurel
#

then u would create app_commands

dire mason
#

yes

naive briar
#

Any

vocal laurel
#

u can create a new file just for app commands

dire mason
#

would it be too complex to add a new file

vocal laurel
#

not rlly

naive briar
#

It would be the same for every extension file

vocal laurel
#

later on it would be easier to find the app commands

dire mason
#

Under cogs or under the project directory

naive briar
#

Anywhere you want it to be

vocal laurel
#

if ur gonna create a new file then just do it under cogs

naive briar
#

Pop kitty

shrewd fjord
#

Mb, this sticker may trigger some epileptic person 😔

dire mason
#

so would I do the decorative?

vocal laurel
#

huh?

dire mason
#

uhh

#

idk whats it called

#

@app_commands()

#

that

vocal laurel
#

u would use @app_commands.command()

naive briar
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
vocal laurel
#

instead of bot.tree.command

dire mason
#

!d interactions

unkempt canyonBOT
#

Application Commands

dire mason
# vocal laurel instead of bot.tree.command

Do you mind explaining the whole

async def ping(interaction: nextcord.Interaction):

in this interaction example I found via tge discord.py api

@bot.slash_command(guild_ids=[TESTING_GUILD_ID])
async def ping(interaction: nextcord.Interaction):
    """Simple command that responds with Pong!"""
    await interaction.response.send_message("Pong!")
naive briar
#

That doesn't look like discord.py

dire mason
#

uhh, yeah

naive briar
dire mason
#

yeahhhhhh

#

um

final iron
#

Nextcord has a different implementation

dire mason
final iron
#

Ignore it. It’s a different library

dire mason
#

okayyy

#

guess i'll go find it from the actual docs

vocal laurel
#

!d discord.Interaction

unkempt canyonBOT
#

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

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

New in version 2.0.
vocal laurel
#

@dire mason

dire mason
#

come the fuck on

vocal laurel
#

?

naive briar
#

I don't appreciate this kind of language very much

vocal laurel
#

what

dire mason
dire mason
vocal laurel
#

cuz i normally typehint interaction : discord.Interaction

#

so its very easy to find

dire mason
vocal laurel
#

theyre?

#

who is theyre

dire mason
#

well

#

shhhhhhh

vocal laurel
#

ok..

snow coral
#

i keep getting a timeout error here and i dont know why

@bot.command()
async def wordbomb(ctx):
    await ctx.send("Do you want to play Word Bomb? React with 👍 to join!")

    def check(reaction, user):
        return user != bot.user and str(reaction.emoji) == '👍' and reaction.message.id == ctx.message.id

    try:
        reaction, user = await bot.wait_for('reaction_add', timeout=15.0, check=check)
    except TimeoutError:
        await ctx.send('No one joined the game. The game has ended.')
    else:
        players[user] = 1
        await ctx.send(f"{user.mention} has joined the game!")``` (this isn't the full code btw)
naive briar
naive briar
#
def check(reaction, user):
    return user != bot.user and str(reaction.emoji) == '👍' and reaction.message.id == ctx.message.id

You're checking for it in the command message (ctx.message.id)

snow coral
#

ohhhhh

snow coral
#

nvm i got it

shrewd fjord
dire mason
shrewd fjord
#

Mhm

naive briar
#

And?

dire mason
#

How would you check if the user already has a interaction with you? I want to see if they do and if they do I want to update the previous reply.

quick brook
#

In the context of music bots, you need to be aware that streaming from YT, Spotify, or any other popular streaming sites prohibits streaming content from their sites. This also violated Discord TOS, so Discord has been lately taking aggressive action to take down bots who offer these services. (Case study: See why Groovy got shut down)

dire mason
quick brook
dire mason
#

oh come the hell on

#

Im confused

meager rock
#

!ytdl for YouTube

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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

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

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

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

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

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

So they hate discords use of theyre music

quick brook
# dire mason oh come the hell on

These streaming services are the juggernauts in this field, and they have the ability to file lawsuits and DMCA strikes and copyright strikes. So unless you want to hire a lawyer and attempt to win a losing battle, it's just best not to even bother with it

dire mason
#

But I had a great name

#

Dang

quick brook
#

THIS IS NOT LEGAL ADVICE
If you're making a "music bot", you should probably consider the implications on the terms of service you have agreed to.

  1. Redistributing copyrighted material (such as music) without the permission of the copyright holder violates international copyright law.
  2. Essentially all popular streaming services (YouTube, Spotify) explicitly forbid in their TOS any redistribution of the content they host without their permission.
  3. Discord developer TOS (which you have agreed to) forbid you using your bot to violate law or break the terms of service of other platforms, which applies to points 1 and 2 above.
  4. Discord has been taking increased action against bots violating these terms and has said this is not allowed in no unspecific wording.

Do with this information what you will, but consider the fact that organizations with far more money and power will put mounting pressure on discord if people continue to use bots to violate their copyrights.

meager rock
dire mason
#

Yeah

quick brook
#

My biggest tip for bot devs is if you want to make a good bot, make something original that solves an issue or aids with something. Ask around in communities and develop features that help aid or solve that problem. Just like a good essay, you need to know your audience before you make the feature

#

A good example is Gnome's TTS Bot. The problem being that muted users were getting ignored in no-voice-channels, and users were also getting ignored in the text channels within voice channels. Now with TTS Bot, all you need to do is let that bot into your server, join a vc and run the command to join that server, and then speak in the text channels within the voice channels. Although robotic sounding, now others can listen to your ideas or what you have to say

#

Similarly, I developed a simple module aimed towards larger servers just like this one that aims to fix an issue that I had to deal with for over an year

shrewd fjord
#

paragraph pro

vocal laurel
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
quick brook
#

Pretty much. It boils down to Mircoeconomics in essence

harsh orbit
#
@bot.command()
async def set_avatar(ctx, url):
    if ctx.author.id in owners:
        await bot.user.edit(avatar=url)
        await ctx.message.add_reaction("✅")
    else:
        await ctx.message.add_reaction("🔒")

why this command not working?

quick brook
harsh orbit
#

its administartor + Im setting a correct avatar link in command also no errors

quick brook
harsh orbit
#

the avatar not changing

quick brook
#

So is your author id within the owners list? Also you can just use @commands.is_owner to allow for the owner of the bot only to execute the command

buoyant quail
#

!d discord.ClientUser.edit it doesn't say that you are allowed to use just url

unkempt canyonBOT
#

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

Edits the current profile of the client.

Note

To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.

The only image formats supported for uploading is JPEG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
buoyant quail
#

though weird that you didn't get ValueError for wrong format then

turbid condor
#

Might have an eh

harsh orbit
#

I used the command in another project and its showed this error

[2023-09-29 02:03:37] [ERROR   ] discord.ext.commands.bot: Ignoring exception in command set_avatar
Traceback (most recent call last):
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Hadi\PycharmProjects\test something\main.py", line 123, in set_avatar
    await bot.user.edit(avatar=url)
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\user.py", line 423, in edit
    payload['avatar'] = _bytes_to_base64_data(avatar)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\utils.py", line 627, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\utils.py", line 613, in _get_mime_type_for_image
    if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: startswith first arg must be str or a tuple of str, not bytes

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

Traceback (most recent call last):
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Hadi\PycharmProjects\test something\venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes

IDK why in the main project didnot showed

buoyant quail
#

You have an error handler in the main one maybe

harsh orbit
buoyant quail
#
with open('some_filename', 'rb') as fp:
    data = fp.read()
edit(avatar=data)

and for using an url, just get the content from there

quick brook
buoyant quail
#

Don't even need to do that
?

harsh orbit
buoyant quail
quick brook
#

There is probably a cleaner impl using discord.Asset and discord.File instead

harsh orbit
quick brook
harsh orbit
#

where

#

like that?

response = requests.get(url)```
quick brook
#

Also instead of pointing to an url, I would suggest type hinting the arg using discord.Attachment instead. Then all you would need to do is just send the new pfp as an file

harsh orbit
naive briar
#

The actual command or the message that invoked the command?

slate swan
brazen raft
#

Might as well recommend using aiohttp which is a dependency of discord.py

harsh orbit
slate swan
#

!blocking

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!

undone lion
#

Hi, I was wondering if someone knows what the rate limit/frame rate you can achieve by editing a message over and over with a bot?

final iron
shrewd apex
sick birch
fiery girder
#

!d discord.on_message_delete

slate swan
#

How can I make the event ignore some function or temporarily disable it?

naive briar
naive dragon
#

New here, have just a general question.
I've gone through most of the basic concepts in Python, and am looking to get started in working on a bot project;
what's the general roadmap that new self-learners take while trying to make something on their own?

I've looked at youtube but there's mostly just out of date stuff that's like older than 1.50 so it's missing info about intents etc.

sick birch
#

But discord.py is more of an advanced library so it's generally expected that you know your way around Python pretty well and you know how to read documentation efficiently

naive dragon
sick birch
unkempt canyonBOT
#
Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

sick birch
#

Don't take this to mean I'm telling you not to write Discord bots, though. I'm merely pointing out what's typically expected

#

Plenty of people make discord bots as beginners

naive dragon
#

thank you for the response, appreciate it

sick birch
#

In the early stages of learning it helps to have a goal or something to keep you motivated. If you're learning just for the sake of learning, you'll probably end up getting burnt out quite fast

naive dragon
# sick birch In the early stages of learning it helps to have a goal or something to keep you...

the projects thing you listed is good for me for sure.

I want to learn to work with python more whether it's making discord bots or pausing on that for the moment to learn and do something else.
As long as I feel I'm progressing and not wasting my time. just reading for hours on google about issues in bots for 4+ hrs out of my day without touching my code editor makes me wanna give up which is why I came to this Discord for extra advice on it.

sick birch
slate swan
sick birch
#

Yeah. Pretty much anything you do will get you closer to that goal

naive dragon
sick birch
#

Yeah. That seems like a lack of experience with the language itself

naive dragon
#

and ultimately i learn nothing if i dont apply it

#

So then how did you learn through starting with discord bots?

#

assuming by starting, you mean at the same level i am now which is very minimal

sick birch
naive dragon
#

You just read theDocs ?

#

and then could construct it?

sick birch
#

No, it took about a year or so

#

It's a much slower process and also has room to learn bad habits and practices

naive dragon
final iron
#

Especially with discord bots, basically every single tutorial either uses bad practices or outdated code

sick birch
# naive dragon before you could make anything work?

Well, I could make things work by googling the parts that weren't working, but I wouldn't really understand why or how it worked. That's really the intuition that needs to be developed before you can start building things fully on your own, and fixing things without having to google it

naive dragon
slate swan
#

15 hours tutorials pain

naive dragon
#

in total almost 20 hrs of videos that just kind of feel like lectures on just the basic concepts

slate swan
#

that's my definition of pain

final iron
#

Tbh you’ll gain more knowledge if you’re actually doing mini projects, instead of watching lectures

naive dragon
#

I was also writing along with them

#

if i was just staring at the screen without doing anything else i'd forget it the next day

#

don't most people do that when learning? take notes to reinforce or also write the code using said concepts yourself?

slate swan
#

Not everyone nope

#

Some people watch some 24 hours tutorials named "PYTHON FULL COURSE IN 24 HOURS 2023" and hope that at the end of the video they know everything

naive dragon
#

I gues you're insinuating that's what I am.

#

Alright anyways, thanks for the responses yall take care

glad cradle
#

you reinforce a lot of what you have learned while coding

slate swan
#

Nope, if you're taking notes etc. it's amazing

#

Meant some people that come in this channel asking help, and they did exactly that

compact stag
#

alright, so i'm working on a discord bot that streams a certain application, but it looks like in discord.py that isn't supported, unless i'm missing something in the docs, can anyone confirm?

buoyant quail
#

bots can't stream videos, that's the discord api itself

quick brook
compact stag
quick brook
compact stag
#

shit.

glad cradle
#

also it's pretty useless since there's the YouTube Activity

compact stag
#

yeah but i wouldn’t be streaming youtube videos, it’d be my screen

#

i’ll just stream it myself for now and just have people send inputs while watching my stream instead of the bot’s stream

quick brook
#

kinda still useless imo since twitch exists for that

latent pier
#

My cog isn't responding it was working before but not anymore neither i made any changes

My cog

class anti(commands.Cog): 
  def __init__(self, client: MyBot):
    self.client = client

  async def on_ready(self):
    print('Anti is loaded')

  @commands.command()
  async def Hello(self, ctx):
    await ctx.send('done done')

My __init__ file

from .commands.anti import anti
from core import MyBot

async def setup(bot: MyBot):
  await bot.add_cog(anti(bot))

MyBot() is my bot's subclass

meager rock
#

the setup function is usually supposed to be in the extension file itself

latent pier
#

It was working before but suddenly stopped working

meager rock
#
  • um do you have proper intents in the bot? (Message Content intent is the required one here)
  • Does the "Anti is loaded" part get stdout-ed
latent pier
hushed galleon
#

i would guess it might be getting ratelimited like usual for replit, but you cant tell because client.start() doesn't setup logging

shrewd apex
#

load_extension("cogs") - didn't u have to pass the file path seperated with .

shrewd apex
meager rock
#

cogs here is acting as a module itself since it has a setup function in the init

hushed galleon
shrewd apex
#

just scrolled

shrewd apex
meager rock
#

you can in normal commands

hushed galleon
latent pier
quick brook
#

case_insensitive is for prefixed commands

shrewd apex
#

🙏 i see

latent pier
#

I have both type of commands

shrewd apex
#

weird but ok 👀

quick brook
#

it would only work for prefixed but not work for slash

latent pier
#

Makes sense

quick brook
shrewd apex
hushed galleon
#

they're loading the cogs package directly, so it should be reading the setup() from cogs/__init__.py

quick brook
#

ah

latent pier
#

What next?

latent pier
hushed galleon
#

run your bot as usual, tell us if your command works, and show the log output

#

oh yeah didn't notice it the first time but your on_ready() won't print without a @commands.Cog.listener() decorator

latent pier
#

I got it confused with bot subclass

latent pier
#

How

hushed galleon
#

i would still guess discord ratelimited your bot, you just didn't have a way to tell if it was happening

#

i can't recall how writing to files work in replit so i suggest using discord.utils.setup_logging(), or at least don't specify a filename in basicConfig()

latent pier
#

I've been facing this issue since yesterday and maybe no resson for rate limit because it's just temporary testing bot

latent pier
#

I never used logging before

#

Is there a way i can print it? Like if i want to make it log on console instead of file?

hushed galleon
#

that's what setup_logging and basicConfig does by default

#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2.0.
latent pier
#

Ohh okay

#

Thanks for help

kindred epoch
#

any free recommended places to host a bot?

quick brook
#

Please make sure you read this fully

When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not use them. Why? Let me explain.

Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.

If you are still looking for a host after reading this, then you have some options. And here are them:

  1. Pay up - Pay up and use a VPS provider. My pick is Heznter, but see ?tag vps for the full list (if you are on the Python discord server, then see !hosting for your options). More than likely if you are not an eligible HS or college student, this is your option.

  2. Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so. Raspberry Pis oftentimes are great for this.

  3. GitHub Student Developer Pack - IF you are a enrolled student in an HS or college (you will need to either provide an valid student ID or proof of education of your HS or college), then you may apply for this deal. More info about this can be found here. The deal offers $200 free credits on DigitalOcean for 1 year, so if you are a student and need to host your bot, go for it.

#

@kindred epoch read the message above

kindred epoch
#

lol alr ty

quick brook
late reef
#

How would you make your discord bot send a message with this kind of format? Like with the line on the side, and the darker shaded background? (OWO bot for reference)

late reef
sick birch
unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
sick birch
#

Note the colour kwarg

late reef
#

Hmm, I've never used one of those before. Have any examples of how I would apply that to a message?

sick birch
late reef
#

Idk, I'm just trying to make my discord bot send a message in that format. Say I wanted to send:

Hello!
I am a bot!
I do bot things!

but as an embed

quick brook
#

by default it is enabled

hushed galleon
late reef
#

Can you edit embeds?

quick brook
hushed galleon
#

well, embeds can be modified in-place but you still need to edit the message for your changes to take effect

quick brook
#

true

hushed galleon
#

for example: ```py
embed = discord.Embed(description="Hello world!")
message = await channel.send(embed=embed)

embed.description = "foobar2000"
await message.edit(embed=embed)```

stray mural
#

so I have an issue with making an activity for my bot
this is the code i use

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="_", intents=intents)
client = discord.Client(intents=intents)

async def load():
    await bot.load_extension(f"cogs.<COG-NAME>")

async def main():
    activity = discord.Activity(type=discord.ActivityType.competing, name="working again!")
    await bot.change_presence(status=discord.Status.online, activity=activity)
    await load()
    await bot.start("<TOKEN>")

asyncio.run(main())

the console returns me the following error AttributeError: 'NoneType' object has no attribute 'change_presence', implying that the bot object is non-existent which doesnt make sense as the cog I load works flawlessly, which uses the botobject.

quick brook
#

and also you dont need line 3

final iron
#

Your intents variable is also useless as you could just pass discord.Intents.all() as your intents

stray mural
final iron
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) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#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) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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.
final iron
#

activity and status kwargs

stray mural
#

thanks

slate swan
#
async def on_timeout(self):
  print("timeout")
  embed= discord.Embed(
      title = "❗ | 시간초과",
      description = f"답장이 너무 오래걸려 프로세스가 종료되었습니다.",
      color = discord.Color.from_rgb(255, 0, 0)
  )
  embed.set_footer(text=f"{Ftmsg}")
  await interaction.response.edit_message(embed=embed,view=None)
  return
#

How do I fix it to work?

quick brook
#

like fix the canbus to allow the cancoders to work?. Point is i dont know what you want that should get fixed and idk the error as well

slate swan
fiery girder
#

i want to test something on my bot can anyone help me test

quick brook
slate swan
#

Create a second account, etc.

slate swan
#

The documentation is for 2.x so take guess bravemmlol

slate swan
#

That document doesn't solve it

#

I looked at that document and tried it for 40 minutes

#

But I couldn't find an answer.

quick brook
#

i already know of a way to pretty much do what you want, but i want to let you figure out your own implementation of it

slate swan
#

😢

#
view.message = await interaction.response.send_message(embed=embed,view=view)

Is it correct to use this code?
Continuously self.message value is shown as None

quick brook
#

send_message returns None, so you will probably want to modify it to take in an InteractionMessage instead. Note that all interactions can only be responded to once unless you make a followup request

slate swan
#
await interaction.response.send_message(embed=embed,view=view)
view.message = await interaction.original_response()

I understand up to here
But I'm not sure how to use self.message

#

The value of self.message is <InteractionMessage id=123 channel=<TextChannel id=123 name='channelname' position=0 nsfw=False news=False category_id=None> type=<MessageType.chat_input_command: 20> author=<Member id=123 name='bot name' global_name=None bot=True nick=None guild=<Guild id=123 name='server name' shard_id=0 chunked=False member_count=123>> flags =<MessageFlags value=0>>

#

These value were obtained using print()

naive briar
naive briar
#

!d discord.InteractionMessage

unkempt canyonBOT
#

class discord.InteractionMessage```
Represents the original interaction response message.

This allows you to edit or delete the message associated with the interaction response. To retrieve this object see [`Interaction.original_response()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.original_response).

This inherits from [`discord.Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) with changes to [`edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) and [`delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) to work.

New in version 2.0.
slate swan
#

ohh i got it

#

thank you Noelle, Catlover

quick brook
#

Np

strong venture
#

Hi, i have a little issue with the reaction listener. So when I generate a new region message and i react to it everything works fine adding me the roles i selected. The issue starts when i reload my bot, it's like it ignores the reactions from that message or idk.

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
slate swan
#

See the first paragraph

#

Explains why it's not dispatching the event

slate swan
#

And the code is?

slate swan
#

Modals cannot contain user selects

#

Modals can only contain text inputs

#

!d discord.ui.TextInput

unkempt canyonBOT
#

class discord.ui.TextInput(*, label, style=<TextStyle.short: 1>, custom_id=..., placeholder=None, default=None, required=True, min_length=None, max_length=None, row=None)```
Represents a UI text input.

str(x) Returns the value of the text input or an empty string if the value is `None`.

New in version 2.0.
young dagger
#

Anyone else getting [Errno 111] Connection refused with mongodb?

mighty pilot
#

Can you change the button style inside on_timeout? I gave it a try and it didn't work, just wondering if there's some workaround

real oriole
#

ok so i have a proplem with

#

@client.command()
async def pack(ctx):
packs = {
"Bronze": 10000,
"Silver": 15000,
"Gold": 25000,
"Special": 50000
}

pack_list = ', '.join([f"{pack}({price})" for pack, price in packs.items()])

await ctx.send(f"Available packs: {pack_list}\nPlease reply with the pack name.")

def check(m):
    return m.author == ctx.author and m.channel == ctx.channel

try:
    reply = await bot.wait_for('message', check=check, timeout=30)
except asyncio.TimeoutError:
    await ctx.send("You took too long to reply.")
    return

selected_pack = reply.content.capitalize()

if selected_pack not in packs:
    await ctx.send("Invalid pack name.")
    return

cost = packs[selected_pack]

# Check if the user has enough money
user_id = str(ctx.author.id)

db = sqlite3.connect("data.db")
cursor = db.cursor()

cursor.execute("SELECT money FROM info WHERE id=?", (user_id,))
user_money = cursor.fetchone()[0]

if user_money < cost:
    await ctx.send(f"You don't have enough money. You currently have {user_money}.")
    cursor.close()
    db.close()
    return
#

selected_card = random.choice(cards_in_pack)

embedVar = discord.Embed(title=f"Unpacking a card from {selected_pack} pack",
                         color=0xff00ff)
embedVar.add_field(name=f"Card Name", value=selected_card[0], inline=False)
embedVar.add_field(name=f"Score", value=selected_card[1], inline=True)
embedVar.add_field(name=f"Position", value=selected_card[2].upper(), inline=True)
embedVar.add_field(name=f"Price", value=f"${selected_card[3]}", inline=True)
embedVar.set_image(url=selected_card[4])

await ctx.send(embed=embedVar)
#

at the start as u see it should detect the reply

#

but it doesnt detect

#

how can i make it detect the reply?

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.

lunar vine
#

send docs

mighty pilot
#

!d discord.Interaction.response

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

maiden fable
mighty pilot
maiden fable
#

Code?

young dagger
mighty pilot
# maiden fable Code?

Not at my computer rn, daughters nap time so I need to get her to sleep. But it's nothing abnormal I set a view timeout to 5 sec with a green button for testing and on timeout the button is unchanged, but will error on press. But if I try to change self.children[0].style in the on_timeout it doesn't error and doesn't do it

turbid condor
# lunar vine send docs

I meant to say that u should just use a button callback which uses interaction response instead of bot.wait_for

lunar vine
#
                user_identification_view = UserIdentificationView()
                await interaction.channel.send(embed=identification_embed, view=user_identification_view)
                await asyncio.sleep(20)
                break
             except asyncio.TimeoutError:
                # Handle the case where the user did not respond within the specified timeout
                await interaction.channel.send("Interaction timed out; go ahead and use this one.")
            while True:
             def amtcheck(message):
                 return (
                    message.channel == interaction.channel
                    and message.author == interaction.user
                    and message.content.strip().isdigit()  # Ensure the response is a valid number 
                    )
             
             try:
                    amount_embed = discord.Embed(
                    title="Amount",```
#

these are two diff embeds and they r sending at the same time

sick birch
lunar vine
#

but idk what u mean by wait for

maiden fable
sick birch
#

Because of that, though, you're not provided with an interaction object

lunar vine
#

me or him

#

robin u didnt actually spend money on discord shop?

sick birch
#

Why does it matter?

mighty pilot
lunar vine
#

thought it was just a money grab but; are u talking 2 me or him

maiden fable
#

Him

lunar vine
#

because we are both dealing with interactions

quick hatch
#

Can i ask how to made self bot?

lunar vine
quick hatch
lunar vine
#

tos!1!

quick hatch
#

What?

lunar vine
#

its against terms of service

quick hatch
lunar vine
#

also whats the point of selfbotting its just a waste of time

quick hatch
#

Srry

lunar vine
#

whatever u can do a bot can do way better

quick hatch
lunar vine
#

No problem

mighty pilot
# maiden fable Well I'll have to see some code because I remember changing the style to disable...
@bot.tree.command()
async def test(interaction:discord.Interaction):
    await interaction.response.send_message(view = myview(timeout=5))

class myview(discord.ui.View):
    @discord.ui.button(style = discord.ButtonStyle.green, row=1, label = 'testing')
    async def mybutton(self, interaction:discord.Interaction, button:discord.ui.Button):
        await interaction.response.send_message(content= "pushed the button", ephemeral= True)
    async def on_timeout(self):
        self.children[0].style = discord.ButtonStyle.grey
#

Button stays green on timeout

#

Oh I need to edit the response. Nvm.

sick birch
maiden fable
#

Was finding the docs for that, kinda forgot where they were

mighty pilot
real oriole
mighty pilot
#

Helps people read your code, instead of it looking like a bunch of text on a screen

real oriole
#

ok wait

mighty pilot
#

Also, have you tried putting in some prints to see what's getting triggered, if the bot is detecting a reply at all? And do you have message content intents?

real oriole
real oriole
mighty pilot
hushed galleon
#

hmm, command is decorated with client but you're accessing the wait_for method from bot...

#

those aren't two bot objects you're using, right?

mighty pilot
#

Ooo good catch

real oriole
#

not bot

final iron
#

So you have 2 instances

real oriole
#

so i should change it to client.

mighty pilot
#

No error because it's in a try block

mighty pilot
real oriole
#

then it will detct the message?

mighty pilot
#

Try and see?

real oriole
#

ok

final iron
#

You still shouldn’t have 2 bot instances

#

And your commands.Bot instance shouldn’t be called client as discord.Client exists

slate swan
#

a discord admin ?

#

it says claim your account, am logged here

final iron
quick brook
#

what is this

languid siren
#

What's some reasonable price to host a discord bot online?
For example a simple one that scrapes some data and shows them in discord (no databases etc).

I am using pythonanywhere with 6.5€/month but I'm not satisfied. The consoles keep crashing.

#

I'm new in hosting my bots. They are actually the first things I make myself that are useful to more people (not just me, running a script when I want to).

cloud dawn
#

Netcup vps

#

Depending on how many servers it is in Discord bots use little resources.

languid siren
quick brook
languid siren
#

Ok that will do it then. Thanks 👍

quick brook
#

Np

languid siren
cloud dawn
#

netcup is cheaper tough

quick brook
quick brook
languid siren
#

I want something that runs 24/7 without resetting its consoles like pythonanywhere (it only gives you the always on feature for just one app).

cloud dawn
quick brook
#

Their servers run 24/7. All you need to do is to ssh into it, and set it up

languid siren
#

I am sure it's a pain for a beginner, right? Pythonanywhere was really simple. But I think it's worth it.

quick brook
#

You can use something like systemd to run your bot as a process and manage it via that way

languid siren
#

I don't even know what ssh is lol. Will learn.

cloud dawn
cloud dawn
slate swan
#

ssh is wonderful

feral timber
upbeat star
quick brook
upbeat star
#

oh so just no more updates

quick brook
upbeat star
#

tf

#

so then why the big announcement on the discord.py server ages ago

quick brook
quick brook
upbeat star
#

yeah lol i don't use discord much

quick brook
#

last commit was 24 minutes ago on the discord.py repo

final iron
#

Then like 8 months later he came back

upbeat star
#

oh lol

final iron
#

I think it had to do with how he thought the other forks were shit

sick birch
#

No I think.. he just had other responsibilities

final iron
#

He made it seem like the leave was permanent

hushed galleon
#

<t:1630036800:d> https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1
<t:1647921600:d> https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
as per the newer gist:

... as time went on it became increasingly clear that the Python bot ecosystem has been too fragmented. I was hopeful that after half a year that there would be a clear alternative library that most users can transparently migrate to, but it seems that this never ended up materialising. In order to prevent more turbulence in the ecosystem, it made sense to try to remedy the current, unfortunate, situation.

final iron
#

My motivation to work on Discord has been dwindling over the past year, since the verification system was introduced. Persistent tone deafness, deadlines, lies, gaslighting, and rapid changes without proper consultation by the Discord employees make it hard to have the motivation necessary to work with the frequent changes and the limitations being placed on me.

#

tldr intents and just Discord staff being ass is what got him all worked up

hushed galleon
#

arguably it might be a safer choice to use an alternative given that danny didn't have any major contributor of the library that was willing to take over development when he left, but i believe it still remains as the most popular library for python discord bots, hence why most of the help here involves it

formal basin
#

How can I stop my discord bot getting rate limited in the future when it grows? I have on_message events

meager rock
idle lantern
#

Hi I've been getting this everytime I login to discord

#

Did i messup with my bot?

shrewd apex
#

whats this screenshot of? a modal?

quick brook
#

is this some figma design?

formal basin
#

and i cant put it back online

glad cradle
shrewd apex
formal basin
#

its been 2 hours

shrewd apex
#

it depends on discord

#

bots are ratelimited by application id and tokens

#

so u can just wait it out

formal basin
#

only 160

shrewd apex
#

were u using replit?

formal basin
#

so i cant shard

formal basin
shrewd apex
#

or do u have some task which makes a bunch of requests?

formal basin
shrewd apex
#

might be that then why not work on optimisation of ur bots events aspects then

#

add some cool down bucket or limiter

formal basin
shrewd apex
#

anything that makes a request to the discord api

formal basin
shrewd apex
#

generally when ur awaiting and requesting something

shrewd apex
formal basin
#

getting the message content?

formal basin
#

so like awaiting something from a different api?

shrewd apex
#

say await bot.fetch_channel() any data ur requesting from discord

shrewd apex
formal basin
#

oh ok

formal basin
shrewd apex
#

i mean based on any active server say 2-3 messages per second thats like 12 requests

#

and thats 160 servers

#

so u might log the requests a bit

formal basin
#

would that be an request?

shrewd apex
#

yes

#

it sends message then sleeps and deletes again so 2 reqd

formal basin
#

Ok ill delete that

shrewd apex
#

reqs*

formal basin
#

i dont really need it

glad cradle
meager rock
#

Sometimes your host can also be the problem if they use shared IPs

glad cradle
#

d.py ratelimit implementation is shit

formal basin
#

@shrewd apex is getting a user id or user permission a request?

#
if message.author.id == self.bot.user.id or message.author == message.author.bot:
             return
     ```
#

how many requests per second?

#

a verified bot can have?

formal basin
shrewd apex
#

i said when ur awaiting right here u already have the object ur just accessing properties

formal basin
#

what about that

#

oh

#

how many requests per scond can a verified bot have?

buoyant quail
#

The same amount as not verified

formal basin
buoyant quail
#

ye

formal basin
#

wait

#

I thought if your bot is verified its harder to get rate limited?

quick brook
#

50 is the global rate limit. the rate limits are dynamic iirc

formal basin
#

I just realised

#

my host is having issues

#

thats why its rate limited

quick brook
formal basin
quick brook
formal basin
#

its a good host

buoyant quail
#

Free and good don't exist together :p

quick brook
formal basin
quick brook
#

you are better off moving to a proper vps provider instead

buoyant quail
formal basin
#

with them

formal basin
quick brook
#

anyways, see your options here

formal basin
#

well theres no free ones

quick brook
formal basin
#

im telling you diva hosting is good

#

its free

#

and good ping

quick brook
quick brook
formal basin
quick brook
# formal basin i got 2.5 GIB disk

Please make sure you read this fully

When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not use them. Why? Let me explain.

Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit (see ?tag replit for more info) use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.

If you are still looking for a host after reading this, then you have some options. And here are them:

  1. Pay up - Pay up and use a VPS provider. My pick is Heznter, but see ?tag vps for the full list (if you are on the Python discord server, then see !hosting for your options). More than likely if you are not an eligible HS or college student, this is your option.

  2. Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so. Raspberry Pis oftentimes are great for this.

  3. GitHub Student Developer Pack - IF you are a enrolled student in an HS or college (you will need to either provide an valid student ID or proof of education of your HS or college), then you may apply for this deal. More info about this can be found here. The deal offers $200 free credits on DigitalOcean for 1 year, so if you are a student and need to host your bot, go for it.

formal basin
#

and ram

#

thats the difference

quick brook
#

I only pay like $7 in total

#

for a VPS provider that actually knows what they are doing. Triple RAID replication, GDPR complaint, etc

formal basin
#

you can buy extra server without paid plan

quick brook
formal basin
quick brook
formal basin
#

the went bankrupt because everyone was using the free plan and only 6 people were using paid

#

thats how good the free plan is

formal basin
#

1,000 using free plan

quick brook
#

you have 6 people using your paid plan, you make no profit

quick brook
formal basin
#

they had to use their own computer

quick brook
# formal basin Yeah i know

can you stop about shilling that host. i'm being serious. i dont give two shits about your fucking shitty promotions

glad cradle
#

bruh

#

it's his choice, i don't see anything wrong there

naive briar
slate swan
#

yoo its _snipy_

#

my fav dunder person 😺

quick brook
meager rock
glad cradle
burnt coral
#

the software you host are bounded to a port, that's where you access your application, it certainly does matter

glad cradle
#

ports are things only in the local computer so it doesn't matter, ratelimits are shared across same IP addresses

meager rock
#

atleast for the discord API

burnt coral
#

oh, that i cannot speak for, apologies

burnt coral
glad cradle
#

i mean ports are under that same IP address

shrewd apex
#

ports would matter if ur using third party webhooks and such which requires either domain or ip and port an example is topgg

quick brook
#

Probably gonna stop helping people on this channel