#discord-bots

1 messages ยท Page 295 of 1

quick brook
#

np

final iron
#

Does discord.utils.get only get objects that are already cached, or can it be used on any object?

#

Or am I thinking about fetch_message

slate swan
#

when u send an embed msg with bot, how do u do so if 20 secs passed bot "forgets" that msg?

#

like, reaction does not work anymore

upbeat ice
#

you should defer the interaction and followup

slate swan
#

i should what? XD

upbeat ice
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
slate swan
#

ty

#

and can i not have a prefix?

upbeat ice
#

generally th ough reactions timeout after 3 seconds

slate swan
#

like, if $p is a command, can i just do p?

upbeat ice
#

i believe you have to have a prefix

#

short of putting all your commands in on_message events - which i do not recommend

slate swan
#

i see

final iron
#

I'd read this though

#

!d discord.ext.commands.Bot.command_prefix

unkempt canyonBOT
#

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate โ€œdynamicโ€ command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as itโ€™s likely to cause performance issues and unintended command invocations.

upbeat ice
slate swan
final iron
upbeat ice
final iron
#

huh

upbeat ice
#

okay fine - the api wrapper lol

slate swan
#

i guess he means wrapper by api

drifting arrow
#

What causes this? discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction? I am using interaction.defer
and It happens so rarely. Never for me tho.

upbeat ice
drifting arrow
#

I cant show the traceback, already deleted it.

#

I can share that portion of the code tho.

upbeat ice
#

best guess is that your code is taking longer than 3 seconds to defer

drifting arrow
#

hhmm

#

alright i'll change where I defer then

south pendant
#

Hello, I was wondering if anyone knows if discord is still in a sandbox enviroment thats the info I am getting from chatgbt or if that has changed/updated struggling to get info on this past 2021.

upbeat ice
final iron
#

Like I understand what it is, but I don't see how it's applicable for discords API

south pendant
final iron
#

Like it opens a website, inside Discord?

south pendant
# final iron Like it opens a website, inside Discord?

no no opens a google extenstion of meta mask (crypto wallet) without opening up a google browser with a website its pretty complex but for some reason chatgbt says this is not possible due to discord sandbox enviroment so I am just trying to figure out is this true or whats up with that situation

final iron
#

I'm not sure what a sandbox environment has to do with this

#

Either you're not making any sense, or I'm out of my depth

#

We will wait for somebody else to see which is true

#

Because honestly, I have no clue

drifting arrow
#

whelp. here's an error I cant figure out how to fix ;-;

#
Traceback (most recent call last):
  File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\example.py", line 25, in <module>
    example = asyncio.run(api.player_identifiers(player_id=random_player_id))
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\battlemetrics.py", line 677, in player_identifiers
    return await _make_request(method="GET", url=url, data=data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Declan\Desktop\discordbots2\battlemetrics_wrapper\battlemetrics.py", line 91, in _make_request
    response = await r.json()
               ^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\aiohttp\client_reqrep.py", line 1120, in json
    return loads(stripped.decode(encoding))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
               ^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 6949234 (char 6949233)
#

;-; no idea how to fix.

drifting arrow
#

It's being pulled from an API lol

#

this kind of error pops up occasionally because the size of the json response is massive

#

As u can see, in this 1 response, almost 7million characters.

#

!pastebin

final iron
#

Alr I don't need it lol

#

I'm not to experienced with this type of stuff

#

Could you share the code? Maybe I could spot something

drifting arrow
south pendant
south pendant
# final iron Why wouldn't it be possible

mainly because I dont want to have a webpage/website open up rather I just want the crypto wallet/transaction and thats what chatgbt say is not possible due to sandbox enviroment

final iron
#

Is there an API?

south pendant
final iron
#

So you need to use a Google extension without opening a web browser?

sick birch
final iron
#

This probably

quick brook
#

looking at the dpy masterclass and just noticed that in the using intents section, the prefixed commands calls all intents

#

u just need message_content and that's it

#

in fact i actually don't recommend using .all() bc it's actually a footgun

#

i had this one bot owner who just shoved .all() intents and grew to 100 servers, and never got the intents verified

#

and thus the bot is offline

#

i'll write a database section in a bit

#

once i finish with work

final iron
#

If I somehow get it to 100 servers I want it to be verified

quick brook
#

yea

final iron
#

So when I do that, how should I format it?

#

Because I just don't want to have a shit ton of ... = True in my code

#

Subclass?

quick brook
#

idk. discord.Intents.default() enables all of the intents except presence, member, and message_content

final iron
#

Yeah but I mean, I'm going to go through each one and disable/enable it

#

i.e I'll set typing to False

quick brook
#

lemme look through the source for discord.Intents for a sec

#

typo oops

final iron
#

big typo

quick brook
#

happens all of the time to me

torn sail
#

You can set intents in the Intents constructor

final iron
#

!d discord.Intents.default

unkempt canyonBOT
#

classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents) with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content).
final iron
#

Oh true

quick brook
#

that option also works

final iron
#

I might subclass for shits and giggles anyway

quick brook
#

yea i was thinking the same

final iron
#

idk I feel like it just looks neater

quick brook
#

agreed

wispy pasture
#

what things does a mod-log has?
to name a few:
message delete
edit
join
leave
what else?

shrewd apex
quick brook
shrewd apex
#

thats fair but if their bot actually grows to about 100 servers i think they would be aware

quick brook
#

you need to set the precedent within the code saying that "hey you should use discord.Intents.default() instead" and then explain why

shrewd apex
#

or atleast a decent amount of coding experience

shrewd apex
shrewd apex
quick brook
shrewd apex
#

aight cool

shrewd apex
quick brook
shrewd apex
#

ah ok

quick brook
#

and for the advanced bot example, you know there is something called async with

shrewd apex
#

yeah

quick brook
#

in fact, aiohttp.ClientSession() automatically supports closing with ctx managers

#

and that's the recommended way of doing it

shrewd apex
#

thats true

#

but if u have a lot of dependencies which form connections and require cleanup its tidier defining it

#

u can always override the aexit method anyways

quick brook
#

most of them support ctx managers iirc

#

asyncpg does

#

i plan on writing a primer on how to effectively use databases with dpy since most bots end up using databases in some form or way

shrewd apex
#

make one with mongo and one with pgsql

#

from setup to connection and writing

quick brook
#

only asyncpg and asqlite bc folks have reported connections constantly dropping and mysql has no atomic ddl. and also no mongo

#

only sqlite and pg

shrewd apex
#

that would be a cool tutorial

#

sql db providers are generally paid so a bunch of ppl use mongo

quick brook
#

This is the reason why I refuse to cover mongodb support:

MongoDB is a NoSQL database that stores data as documents in BSON format. Not recommended in general as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.

quick brook
#

done and simple. and then just restrict all connections to only localhost

#

also motor is basically pymongo but wrapped in an run_in_executor

#

i would be interested if something wrote a full cython/c/rust version of motor but only using the direct i/o instead

shrewd apex
#

ok ok just saying cause its still a pretty popular choice and beginners generally dont have vps or much knowledge about this so i would prefer a comparison and a tutorial for both cases

quick brook
shrewd apex
#

yeah but it still makes it an option

#

i mean its still viable with an orm right

#

like prisma altho the python client is in dev state iirc

quick brook
#

generally speaking of ORMs just add more complexity than needed. ORMs require the firsthand knowledge of SQL. If you don't know SQL, then there isn't any point of using an ORM because the concepts are fudmentally the same

#

directly using drivers is the most simple options

shrewd apex
#

i mean if u want to use asyncpg and benefit from relational models u will still need sql and db knowledge

#

no way around it

quick brook
#

that's the point. ORMs also completely limit your control when it comes to the scope of what you can do

shrewd apex
#

yeah

#

but for beginners i doubt they would stumble upon a case where they need to make raw queries

#

but entirely upto what you prefer to use ig

quick brook
#

i mostly prefer raw drivers such as asyncpg

shrewd apex
#

same but i dont always have a vps or vm at my disposal ๐Ÿ˜”

#

so i end up using a bunch of diff db

#

mongo, sql, firebase (this one is decent for web dev)

quick brook
shrewd apex
#

dont have financial freedom to make that choice ๐Ÿ’€ parents gonna kill me, I'll just host stuff on my rpi when i buy a heatsink this year later

quick brook
shrewd apex
#

yeah

quick brook
#

i personally just go with vps providers and then go from there.

shrewd apex
#

thats cool

quick brook
#

what i end up doing is creating vms that replicate the environment of the production server that i plan on running and then do all of my configuration on the vm server

#

by the time the production server goes live, I already have all of the configs i need ready to go

shrewd apex
#

ig I'll get a vm in future setup docker then should be good to go I'll prolly get hetzner, or digital ocean

quick brook
#

both are good options tbh

shrewd apex
left dew
#

how do i delete a message that has been sent by await interaction.response.send_message(embed=em)?

buoyant quail
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
left dew
buoyant quail
#

If you use something like followup, it returns the message as usual sends

#

so you do message = await interaction.followup.send(...) and await message.delete()

left dew
buoyant quail
#

Show your code

left dew
#
class Agree2(discord.ui.View):
    def __init__(self, user1_id, user2_id):
        super().__init__(timeout=None)
        self.user1_id = user1_id
        self.user2_id = user2_id
        self.user1_has_agreed = False
        self.user2_has_agreed = False

    @discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
    async def button_callback2(self, button, interaction):
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        msg = await interaction.followup.send(embed=em)
        if interaction.user.id == self.user1_id:
            self.user1_has_agreed = True
        elif interaction.user.id == self.user2_id:
            self.user2_has_agreed = True

        if self.user1_has_agreed and self.user2_has_agreed:
            await interaction.message.delete()
            await msg.delete()

            amount_em = discord.Embed(title="Amount", description=f"Below please send the **amount** you would like to spend on this item", color=nocolor)
            c = await interaction.channel.send(embed=amount_em)
            while True:
              def check_message(m):
                return m.channel == interaction.channel 
              reply = await interaction.client.wait_for("message", check=check_message)
              amount = reply.content
              if amount.isdigit():
                amount = float(amount) 
                await c.delete()
                await reply.delete()
                conf = discord.Embed(description=f"Is `{amount}` the **correct** amount you want to purchase this items for", color=discord.Color.orange()) 

                user1 = i["ticket_author"]
                user2 = i["user_added"]
                agree_view2 = Agree_To_Amount(user1, user2)

                await interaction.channel.send(embed=conf, view=agree_view2)
                break
              else:
                await reply.delete()
                await interaction.channel.send(f"{reply.author.mention} The amount **must** be a number!", delete_after=5)```
buoyant quail
left dew
#

oh

#

when ive used await interaction.response.send_message(embed=em), it sends the embed for each user but i jsut cant find out how to delete both

buoyant quail
#

That can't be possible.
send_message will work only once, second would give an error

show the code you had before editing

#
async def foo(interaction: discord.Interaction):
    await interaction.response.send_message("hi 1")
    await interaction.response.send_message("hi 2")

sends hi 1 and gives error

discord.app_commands.errors.CommandInvokeError: Command 'foo' raised an exception: InteractionResponded: This interaction has already been responded to before
left dew
#
class Agree2(discord.ui.View):
    def __init__(self, user1_id, user2_id):
        super().__init__(timeout=None)
        self.user1_id = user1_id
        self.user2_id = user2_id
        self.user1_has_agreed = False
        self.user2_has_agreed = False

    @discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
    async def button_callback2(self, button, interaction):
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        await interaction.response.send_message(embed=em)
        if interaction.user.id == self.user1_id:
            self.user1_has_agreed = True
        elif interaction.user.id == self.user2_id:
            self.user2_has_agreed = True

        if self.user1_has_agreed and self.user2_has_agreed:
            await interaction.message.delete()
            await interaction.delete_original_response()


            amount_em = discord.Embed(title="Amount", description=f"Below please send the **amount** you would like to spend on this item", color=nocolor)
            c = await interaction.channel.send(embed=amount_em)
            while True:
              def check_message(m):
                return m.channel == interaction.channel 
              reply = await interaction.client.wait_for("message", check=check_message)
              amount = reply.content
              if amount.isdigit():
                amount = float(amount) 
                await c.delete()
                await reply.delete()
                conf = discord.Embed(description=f"Is `{amount}` the **correct** amount you want to purchase this items for", color=discord.Color.orange()) 

                user1 = i["ticket_author"]
                user2 = i["user_added"]
                agree_view2 = Agree_To_Amount(user1, user2)

                await interaction.channel.send(embed=conf, view=agree_view2)
                break
              else:
                await reply.delete()
                await interaction.channel.send(f"{reply.author.mention} The amount **must** be a number!", delete_after=5)```
#

i only use it once

#

but it sends 2 because its waiting for 2 reactions

slate swan
buoyant quail
#

You said you sent them with interaction.response.send_message ยฏ_(ใƒ„)_/ยฏ

left dew
#

i have

buoyant quail
#

You did that with channel.send , no?

left dew
#

huh

#

i didnt send anything with channel.send

buoyant quail
#
            `await interaction.channel.send(embed=conf, view=agree_view2)`

ducky_sus

#

so it returns the message and you can do anything you want with it (delete in your case)

#
message = await interaction.channel.send(embed=conf, view=agree_view2)
await message.delete()
buoyant quail
naive briar
#

Me when I send a message and delete it immediately ๐Ÿˆ

slate swan
slate swan
#

๐Ÿคซ

left dew
buoyant quail
#

ah i understood what's going on

#

Then fetch the message to delete it later

#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
buoyant quail
#

On first click you save message, on second click you save the message. And then delete them both

left dew
#

save the message id?

buoyant quail
#

saving just the message object would be easier

#

because for message only id is not enough

left dew
#

so like store them in a reference?

naive briar
#

Variable

left dew
#
class Agree2(discord.ui.View):
    def __init__(self, user1_id, user2_id):
        super().__init__(timeout=None)
        self.user1_id = user1_id
        self.user2_id = user2_id
        self.user1_has_agreed = False
        self.user2_has_agreed = False
        self.message_references = []

    @discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
    async def button_callback2(self, button, interaction):
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        message = await interaction.response.send_message(embed=em)
        self.message_references.append(message)

        if interaction.user.id == self.user1_id:
            self.user1_has_agreed = True
        elif interaction.user.id == self.user2_id:
            self.user2_has_agreed = True

        if self.user1_has_agreed and self.user2_has_agreed:```
#

that?

buoyant quail
#

this fetches the responded message

#

send_message doesn't return it

naive briar
#

response.send_message doesn't return the sent message

left dew
#

im confused

#

so i useawait original_response()?

buoyant quail
#

it's a method
but yes

left dew
#

i dont understand what you're saying

naive briar
#

It's a method of interaction objects

slate swan
#

its not a function its interaction method

naive briar
left dew
#

if send_message doesnr return it then what do i use?

naive briar
#

Use for what

slate swan
left dew
#

how does that send the message

naive briar
#

It doesn't, it fetches the sent message

left dew
#
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        await interaction.response.send_message(embed=em)
        msg = await original_response() ```
#

like that?

naive briar
#

No, it's a method

left dew
#

and i store the msg?

#

oh

#

then what do i do

naive briar
#

I

buoyant quail
#

use it as method pithink

left dew
#

i dont know what that means

buoyant quail
#

in that code you'd get error because original_response is not defined

naive briar
#
function()

instance.method()
#

See the difference

left dew
#

msg = await interaction.original_response()

naive briar
#

Yes

left dew
#

okay

#

and then i'd store the msg?

buoyant quail
#

yes

left dew
#

store them in a variable?

buoyant quail
#

yes

left dew
#

cuz there's 2 users

slate swan
#

If its the same message then one varriable ja enough

buoyant quail
#

The thing you did first with the list was easier

#

But if you want you can do like that ofc

left dew
#

i dont know how i'd delete it tho

#

is it just msg.delete or

buoyant quail
#

yes.
you already did it multiple times even before asking, just in your original code

#

why don't you know it now pithink

left dew
#

i get an attribute error

#

AttributeError: 'Interaction' object has no attribute 'orginal_response'

#

oh

#

nvm

lofty lance
#

@slate swan hey sir can we have a vc chat
i want to discuss soemthing related to my bot to ya

left dew
buoyant quail
left dew
#

jee how didnt i see that

left dew
buoyant quail
#

Show current code

left dew
#
    @discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
    async def button_callback2(self, button, interaction):
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        await interaction.response.send_message(embed=em)
        msg = await interaction.original_response()
        user1 = msg
        user2 = msg
        if interaction.user.id == self.user1_id:
            self.user1_has_agreed = True
        elif interaction.user.id == self.user2_id:
            self.user2_has_agreed = True

        if self.user1_has_agreed and self.user2_has_agreed:
            await interaction.message.delete()
            await user1.delete()
            await user2.delete()```
buoyant quail
#

Because your user1 and user2 is the same one message

left dew
#

so i have to do 2 msg = await interaction.original_response()?

buoyant quail
#

No. You have to set first variable first time and second variable second time. That's why using a list was much easier

left dew
#
class Agree2(discord.ui.View):
    def __init__(self, user1_id, user2_id):
        super().__init__(timeout=None)
        self.user1_id = user1_id
        self.user2_id = user2_id
        self.user1_has_agreed = False
        self.user2_has_agreed = False
        self.message_references = []

    @discord.ui.button(row=0, label='Agree', style=discord.ButtonStyle.green, custom_id="agree", disabled=False)
    async def button_callback2(self, button, interaction):
        em = discord.Embed(description=f"{interaction.user.mention} has reacted to 'Agree'", color=discord.Color.green())
        await interaction.response.send_message(embed=em)
        msg = await interaction.original_response()
        self.message_references.append(msg)
#

that?

buoyant quail
#

yes

left dew
#

then

           for message_reference in self.message_references:
                await message_reference.delete()```
buoyant quail
#

yes

left dew
#

yessss it worked

#

tysm ๐Ÿ™Œ๐Ÿผ

wispy pasture
wicked atlas
# wispy pasture so this is my code: https://srcb.in/b4Y2OMPwkP and the bot keeps on sending emb...

because that's what you told it to do?

  async def update_timeout_countdown():
        while get_remaining_time().total_seconds() > 0:
            formatted_remaining = f"<t:{int(timeout_until.timestamp())}:R>"
            
            embed = discord.Embed(
                title="User Timed Out",
                color=discord.Color.green()
            )
            embed.add_field(name="User", value=member.mention)
            embed.add_field(name="Moderator", value=ctx.author.display_name)
            embed.add_field(name="Reason", value=reason)
            embed.add_field(name="Time Remaining", value=formatted_remaining)
            
            await ctx.send(embed=embed)
            
            await asyncio.sleep(60)  # Update every 1 minute
        
        await member.edit(timed_out_until=None)
    
    asyncio.ensure_future(update_timeout_countdown())
#

You also shouldn't need to update that timestamp, since it's a fixed point in time discord just changes what it displays

wicked atlas
#

and timeouts expire by themselves, yeah?

wispy pasture
sick moat
#

What's a free way to host a discord bot? Python anywhere won't let you use websocket on free plan. Replit works but crashes even with the uptimebot manager and keep_alive.py. I need something free and simple for hosting the python scripts

meager chasm
#

!hosting

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.

meager chasm
#

some vps providers have free tiers

turbid condor
#

But free hosting has a downside that it uses shared ip

slate swan
#

gcp

turbid condor
#

Gcp the one by google?

slate swan
#

yes

turbid condor
#

Doesn't it have credit system and i think you receive 300 credits free?

slate swan
#

yeah

#

300$ to spend

#

if you play it good you have half a year free VM

turbid condor
#

๐Ÿค”

#

Welp I'll stick to using my old phone for hosting

slate swan
obsidian fable
#

is it possible to make ui.Button redirect to another link?

buoyant quail
#

Wdym by "another link"? You can redirect to anywhere

obsidian fable
#

and it brings you outside of discord

buoyant quail
#

Yes
And what do you want instead?

obsidian fable
#

I want that but idk how

buoyant quail
obsidian fable
#

thank you

young dagger
#

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

young dagger
slate swan
#

!e 1 + None

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     1 + None
004 |     ~~^~~~~~
005 | TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
slate swan
#

you are trying to add those two

#

total_members = sum([guild.member_count for guild in client.guilds]) here

#

meaning for some guild .member_count is None

#

!d discord.Guild.member_count

unkempt canyonBOT
#

property member_count```
Returns the member count if available.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be specified.

Changed in version 2.0: Now returns an `Optional[int]`.
slate swan
#

Type
Optional[int]

#

just add simple if in that listcomp

young dagger
#

@slate swan Is this it?

slate swan
#

yeah i guess if guild.member_count is even less and will work

#

cause when this will be 0 it will make 0 difference to sum func

sick birch
#

You can also sum guild.member_count or 0

slate swan
#

!e ```py

print([x or 0 for x in [None, 1, None]])

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0, 1, 0]
slate swan
#

.topic

lament depotBOT
#
**What's one feature you wish more developers had in their bots?**

Suggest more topics here!

sick birch
#

Good practices

slate swan
sick birch
#

So many git repos that are just some python files thrown around

slate swan
#

and not naming Bot instance client

sick birch
#

No proper project structure, no workflows, no linting

cloud dawn
#

nsfw features

winter hare
#

i even changed the token and it still showed up

final iron
winter hare
#

is there a way for me to check

final iron
#

How do you not know

winter hare
#

3.10.11

quick brook
quick brook
# sick moat What's a free way to host a discord bot? Python anywhere won't let you use webso...

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 uses 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 uni 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

  3. GitHub Student Developer Pack - IF you are an eligible student in an verified HS or college (you will need to either provide an valid student ID or proof of education of your HS or college. school transcripts work in this case), then you may apply for this deal. The deal offers $200 free credits on DigitalOcean for 6 months, so if you are a student and need to host your bot, go for it.

quick brook
shrewd apex
#

oracle is free

#

but u need a credit card

quick brook
#

Gotta use a credit/debit card + questionable privacy policies

shrewd apex
#

i mean even for most offers with aws, gcp, azure all u need credit card

quick brook
#

That's standard

shrewd apex
#

mhm

quick brook
#

It's to prevent spam and stuff

winter hare
#

changed wifi still didnt work

shrewd apex
#

are u using some vpn?

winter hare
#

no

shrewd apex
#

do u have any firewall or some antivirus which might be blocking your python programme?

cold sonnet
#

Asher

shrewd apex
#

tcp 443 port is the default port for https requests if its blocked it would likely lead to failing https requests

shrewd apex
cold sonnet
#

hi

shrewd apex
#

hello ๐Ÿ‘‹

winter hare
shrewd apex
#

u might wanna check your ssl certs then

hasty coral
#

im writing a command for the economy side of my bot but i keep getting the same error message.

code:

@bot.tree.command(name='steal', description='Steal from a User')
@app_commands.checks.cooldown(1, 1800, key=lambda i: (i.user.id))
@app_commands.describe(member = 'member')
async def steal(ctx:discord.Interaction, member: discord.Member):
    probability = [1,6]
    chance = random.randint(probability)
    if chance > 2:
        with open('userBalances.json', 'r') as f:
            balances = json.load(f)
        user_id = str(ctx.user.id)
        user_balance = balances.get(user_id, 0)
        member_id = str(member.id)
        member_balance = balances.get(member_id, 0)
        if member_id in balances:
            if member_balance > 0:
                stolen_amount = [1,int(member_balance)]
                amount_stolen = random.randint(stolen_amount)
                user_balance += amount_stolen
                balances[user_id] = user_balance
                with open('userBalances.json', 'w') as f:
                    json.dump(balances, f, indent=4)
                member_balance -= amount_stolen
                balances[member_id] = member_balance
                with open('userBalances.json', 'w') as f:
                    json.dump(balances, f, indent=4)
                embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} has stolen {format(amount_stolen, ',')} Coins from {member.mention}!", color=discord.Color.brand_green())
                await ctx.response.send_message(embed=embed)
            else:
                embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
                await ctx.response.send_message(embed=embed)
        else:
            embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
            await ctx.response.send_message(embed=embed)
    else:
        with open('userBalances.json', 'r') as f:
            balances = json.load(f)
        user_id = str(ctx.user.id)
        user_balance = balances.get(user_id, 0)
        member_id = str(member.id)
        member_balance = balances.get(member_id, 0)
        if member_id in balances:
            if member_balance > 0:
                stolen_amount = [1,(user_balance)]
                amount_stolen = random.randint(stolen_amount)
                user_balance -= amount_stolen
                balances[user_id] = user_balance
                with open('userBalances.json', 'w') as f:
                    json.dump(balances, f, indent=4)
                embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} was caught stealing from {member.mention} and was fined {format(amount_stolen, ',')} Coins!", color=discord.Color.brand_red())
                await ctx.response.send_message(embed=embed)
            else:
                embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
                await ctx.response.send_message(embed=embed)
        else:
            embed = discord.Embed(title='Steal Coins', description=f"{ctx.user.mention} the user {member.mention} does not have any Coins for you to steal!", color=discord.Color.brand_red())
            await ctx.response.send_message(embed=embed)
#

Error:

Traceback (most recent call last):
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'steal' raised an exception: TypeError: randint() missing 1 required positional argument: 'b'
slate swan
#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
hasty coral
#

i know how to use it. it just wont detect the value

slate swan
#

randit takes 2 integers a and b, whereas you've passed a list

hasty coral
#
stolen_amount = [1,(user_balance)]
amount_stolen = random.randint(stolen_amount)
hasty coral
quick brook
buoyant quail
hasty coral
hasty coral
buoyant quail
#

Sure, show it

final iron
#

!e

import random
_list = [1, 4]
print(random.randint(1, _list))
unkempt canyonBOT
#

@final iron :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     print(random.randint(1, _list))
004 |           ^^^^^^^^^^^^^^^^^^^^^^^^
005 |   File "/lang/python/default/lib/python3.11/random.py", line 362, in randint
006 |     return self.randrange(a, b+1)
007 |                              ~^~
008 | TypeError: can only concatenate list (not "int") to list
quick brook
glad cradle
quick brook
#

Json is a data serialization format, that turns primitive data structures into a string.
A database is a formalized system designed to store and retrieve data, with a substantial
number of features and functionalities designed to support doing so at various scales,
and with a large number of guarantees.
A Json file as-a-db* is fundamentally flawed due to its lack of atomic writes
which results in data corruption and loss when:
โ€ข The disk runs out of storage
โ€ข The program crashes during the write
โ€ข The computer crashes during write
โ€ข Two programs try to write to the file at the same time
Additionally:
โ€ฃ All reads require the entire file to be read
โ€ฃ All reads require the entire structure to be loaded into memory *this does make it fast!
โ€ฃ All writes require the entire file to be re-written
The Json module makes no effort to ameliorate any of these concerns, because json-as-a-db falls
completely and entirely out of the scope of the standard.
If you need the file to be portable and want minimum setup, use sqlite, a standard designed to
solve all these issues.
*Using the json stdlib module

#

SQLite is the recommended option here

quick brook
slate swan
#

!e

from random import randint
print(randint(*[1, 6]))
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

2
slate swan
#

Do this if you really really want to pass it as a list

final iron
#

What's * again? Does it unpack the list?

glad cradle
#

yeah

final iron
#

cool

buoyant quail
#

(any iterable object)

final iron
#

The nested if statements are killing me

quick brook
#

I still don't understand why op needs to use JSON as a db. Like the size of your bot doesn't matter

final iron
#

I dunno, I guess they think it's okay because their bot isn't going to be used much

buoyant quail
#

because you don't need to know anything for it
you can use mongodb then though

quick brook
#

SQLite with WAL enabled is already pretty fast

final iron
#

No need to learn SQL or anything

slate swan
#

from experience, don't use mongoDB for a discord bot in my opinion

quick brook
#

Mongo is trash anyways

#

It's an well maintained db but not suited for the task of dbots

#

Most data you will find you need to store is relational, meaning that they form relationships

#

And if you are looking for MongoDB bc of it's clustering and sharding abilities, PostgreSQL can do the exact same thing

slate swan
#

pymongo/motor-asyncio annoys me with dodgy type hinting, at least that's my experience

quick brook
#

Also motor is pretty much trash as well bc of the lack of type hinting

#

They still use mypy

slate swan
#

.topic

lament depotBOT
#
**What feature would you like to see added to the library? What feature in the library do you think is redundant?**

Suggest more topics here!

slate swan
#

i still dont know why discord.py dont want to add getch methods

buoyant quail
#
class MyCoolBot(Bot):
    async def getch_channel(self, id):
        return self.get_channel(id) or await self.fetch_channel(id)
#

done pixels_snek_2

slate swan
#

yeah i know its easy to add i just dont know why discord.py dev team doesnt want to add that builtin

buoyant quail
#

to not have too much function mb
get and fetch and getch

#

though it could go to utils

slate swan
buoyant quail
#

Interesting

slate swan
#

i really dont get what decisions are supposed to make with it

slate swan
buoyant quail
#

mhm

slate swan
#

(Danny is owner of discord.py if you are not aware)

buoyant quail
#

decisions pithink

slate swan
#

not only channels but Member, User, Message

buoyant quail
#

iterate over methods and if it starts with get and there is the same thing with fetch, create a getch

slate swan
#

and what is worse there is for example Message which is not accessable via Bot instance so you cant really make custom method for it unless it would accept the abc.Messageable

buoyant quail
#

for that just setattr

slate swan
#

nah, modify source

buoyant quail
#

not interesting

unkempt canyonBOT
#

disnake/guild.py lines 3464 to 3466

async def get_or_fetch_member(
    self, member_id: int, *, strict: bool = False
) -> Optional[Member]:```
slate swan
#

now i see what "decistions" must be made

buoyant quail
#

i don't :p

glad cradle
slate swan
glad cradle
#

yeah!

slate swan
#

so it still returns Optional xd

buoyant quail
#

That looks fine for me
Though since usually mine ids are correct (h), then it means it some id given by the user, so i'd use strict and get an error

glad cradle
#

if strict is enabled

slate swan
#

raise BrainIssue() from e

slate swan
quick brook
#

with this design, I implement my coros to have the same exact design principle

slate swan
quick brook
#

now with get_or_fetch_* methods, it first does an cached lookup and then if not found, contact the API

#

that's pretty much the point

#

in my case, when I have a feature that can be enabled/disabled (this is implemented as a check), what I do instead is my coro first looks up the cached config or value on Redis, and returns that. If not found, it will get the data from Postgres instead, and then update or create a new value based on the key on Redis

#
async def get_or_fetch_enabled_status(
    guild_id: int, pool: asyncpg.Pool, redis_pool: ConnectionPool
) -> Union[bool, None]:
    query = """
    SELECT pins
    FROM guild
    WHERE id = $1;
    """
    key = f"cache:kumiko:{guild_id}:guild_config"
    cache = KumikoCache(redis_pool)
    if await cache.cache_exists(key=key):
        return await cache.get_json_cache(key=key, path=".pins", value_only=False)  # type: ignore
    else:
        status = await pool.fetchval(query, guild_id)
        if status is None:
            return None
        await cache.merge_json_cache(key=key, value=status, path=".pins")
        return status
#

this is the best example of what I mean

#

the caching library depends on redis-py, but the KumikoCache class is custom

slate swan
#

ise e

#

one thing that is bothering me there

#

why Union[bool, None] instead of Optional[bool]

quick brook
#

Optional[bool] boils down to Union[bool, None]

slate swan
#

yeah i know it does

#

just curious why not using Optional

quick brook
#

unless you are inclined to make a PR fixing all of the instances where that happens (which is a lot spanning 9.3K lines of code), i probably won't change it

slate swan
#

bet

quick brook
#

i think that's the simplest answer on why

slate swan
#

what the repo link though

quick brook
#

feel free to make a PR

#

there is a good chunk of code i still have to clean up but it's not really my priorities rn to do that

slate swan
#

yeah 3k commits

#

maybe ill do that when im bored

quick brook
glad cradle
quick brook
fallen pulsar
#

Hi everyone, I've coded an embed with a button when you press it, a message comes up. unfortunately interaction fails. somehow i can't give my bot an administrator in the application. or is it something else. thank you very much for your help ps i'm from germany.

fallen pulsar
#

@bot.command()
async def regeln(ctx):
# Erstelle ein Embed mit den Regeln
embed = discord.Embed(
title="Server Regeln",
description="Bitte lies die Regeln sorgfรคltig durch und bestรคtige, dass du sie akzeptierst, indem du auf den Button klickst.",
color=discord.Color.blue()
)
rules = [
"Regel 1: Keine Beleidigungen oder Diskriminierung.",
"Regel 2: Kein Spam oder Flooding im Chat.",
"Regel 3: Respektiere die anderen Mitglieder.",
"Regel 4: Halte dich an die Channel-Themen.",
]
embed.add_field(name="Regeln:", value="\n".join(rules), inline=False)

# Erstelle einen Button fรผr die Bestรคtigung
confirm_button = discord.ui.Button(
    style=discord.ButtonStyle.primary,
    label="Akzeptieren",
    custom_id="accept_rules"
)

# Erstelle eine Ansicht mit dem Button
view = discord.ui.View()
view.add_item(confirm_button)

# Sende das Embed und die Ansicht in den aktuellen Kanal
await ctx.send(embed=embed, view=view)

@bot.event
async def on_button_click(interaction: discord.Interaction):
if interaction.custom_id == "accept_rules":
# Bestรคtigungsbutton wurde geklickt
await interaction.response.send_message("Du hast die Regeln akzeptiert!", ephemeral=True)

slate swan
#

there is no such event as on_button_click

fallen pulsar
quick brook
subtle spade
#

Is it possible use a variable like this? This gives a error

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'role' where it is not associated with a value

role = int(1146549387628122286)

@bot.command()
async def bm(ctx):
# ADMIN ROLE
role = discord.utils.get(ctx.guild.roles, id=role)

quick brook
subtle spade
#

yes

#

Like this

if role in ctx.author.roles:
run commands
else:
do not

subtle spade
#

Ok, but I want to have the role ID in a variable. If I want to change the role ID I just have to change the variable and not in all the commands

#

Is that possible?

#

Same here

restart_feed_channel = bot.get_channel(1146109246115680386)

I want to have the channel ID in a variable as well

quick brook
#

dont think you can change the id of a role

#

what i would recommend doing is making constants and storing the variables in there if you dont need to change them

fallen pulsar
#

hello does anyone know how to host the bot on a v server

cloud dawn
main holly
#

@bot.tree.command()
async def sendticketpanel(interaction: discord.Interaction):

embed = discord.Embed(
    title="Create a Ticket",
    description="Click the button below to create a ticket:",
    color=0x0000ff
)

button = Button(label="Create a ticket", style=discord.ButtonStyle.green)
view = View()
view.add_item(button)

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

user = interaction.user
guild = interaction.guild

ticket_channel_name = f"ticket-{user.name}"
existing_channel = discord.utils.get(guild.text_channels, name=ticket_channel_name)

if not existing_channel:
    ticket_channel = await guild.create_text_channel(ticket_channel_name)

    support_team_role_name = "Support Team"
    support_team_role = discord.utils.get(guild.roles, name=support_team_role_name)
    if support_team_role is None:
        support_team_role = await guild.create_role(name=support_team_role_name)

    await user.add_roles(support_team_role)

    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        user: discord.PermissionOverwrite(read_messages=True, send_messages=True),
        support_team_role: discord.PermissionOverwrite(read_messages=True, send_messages=True)
    }
    await ticket_channel.edit(overwrites=overwrites)
#

what i do wrong bruh the embed sends and the button

#

when i click da button nothing happens

upbeat gust
#

you don't assign a callback in your code

main holly
upbeat gust
#

and where's the code to make the channel?

main holly
#

oh shit

#

ohhhh hold on

robust fulcrum
#

Can we host discord bot on our mobile phone ๐Ÿค“?

quick brook
#

U could but not recommended

quick brook
obsidian fable
#
@commands.hybrid_command(name="test", description="test")
async def test(interaction: discord.Interaction):
    await interaction.defer(ephemeral=False)

    user = interaction.author
    for activity in user.activities:
        if isinstance(activity, Spotify):
            await interaction.send(f"You are listening to {activity.title} by {activity.artist}")
        else: 
            await interaction.send("You are not listening to Spotify")

is this the correct usage for the discord.Spotify class? doesnt seem to output anything

final iron
#

Might be a stupid question, but how would I pass the function as choices for an app command?

    async def shipping_line_choices(
            self,
    ) -> list[app_commands.Choice[str]]:
        all_lines = [line for lines in self.shipping_lines.values() for line in lines]
        all_lines.sort()

        return [
            app_commands.Choice(name=line, value=line)
            for line in all_lines
        ]
#

I've never worked with choices before

sick birch
#

They need to be displayed on discord

quick brook
#

Is this for autocomplete?

final iron
#

It was originally for autocomplete, then I'm miragiting it to choices

#

I removed a few unneccesary bits

final iron
#

For each of them

quick brook
#

I mean you probably can use the func that gives the choices. So u can use shipping_line_choices and since that returns a list of app_commands.Choice, it should work

#

Ofc I haven't tested this so idk if it would actually work or not

final iron
#

I was trying to do that, but if I call the function I get a await error, but I can't await it because it's outside of a function

#
    @app_commands.choices(country=DeclarationCalculator().shipping_line_choices)
#

Unless I'm doing it wrong

quick brook
#

Ah I see. I don't think you need your func to be async unless there is a part of your choice that needs to be awaited

final iron
#

True

#

Nothing is coming up now for the option

#

nvm

#

This is why they say don't code at night

#

You make stupid mistakes

final iron
golden portal
#

idk what fork that is, but you possibly need presence intents

quick brook
final iron
#

Robin gave me his blessing

#

I will roll with it for now

rugged shadow
#

or presence, i forgot

turbid condor
turbid condor
#

What do you mean 16 of them?

#

Then plz don't randomly ping

obtuse pumice
#

Hellow I'm doing scrapping but problem is that cookie is session cookie it expired in few minutes how to retrieve new cookie1 and auto update in my code anyone know or help me

slate swan
#

I've got a verified discord bot but when I try use it the commands takes around 10 minutes to execute

#

And sometimes don't at all

#

No error can someone help?

fallen pulsar
#

Hello how can I fix the bug that when I press the button again, the interaction failed

onyx elk
#

can someone give me a slash command template

slate swan
onyx elk
#

like a slash /say prompt:

onyx elk
formal basin
#

how do i check before a slash command is completed

#

like an event

buoyant quail
#

!d discord.ext.commands.before_invoke

unkempt canyonBOT
#

@discord.ext.commands.before_invoke(coro)```
A decorator that registers a coroutine as a pre-invoke hook.

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

New in version 1.4.

Changed in version 2.0: `coro` parameter is now positional-only.

Example
formal basin
#

!d discord.on_interaction

unkempt canyonBOT
#

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

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

Warning

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

New in version 2.0.
formal basin
#

hmm

buoyant quail
#

tree has interaction_check
so do what you want and return just True

formal basin
#

but the command still executes

#

no i want to check for something before the command executes

buoyant quail
#

check is called before the command

formal basin
#

and if it true then dont execute

buoyant quail
#

though looks like using on_interaction would be the same thing

formal basin
buoyant quail
buoyant quail
formal basin
#
@bot.event
async def on_interaction(interaction: discord.Interaction):
   if interaction.channel.is_nsfw():
        await interaction.followup.send("zagzag does not support nsfw channels.", ephemeral=True)
#

this is my code

mental hollow
#

how do i loop through users with a specific role?

formal basin
#

if this turns true

#

it still executes the command

#

and sends the "zagzag does not support nsfw channels."

#

how can I make it stop executing it

buoyant quail
#

use interaction_check for tree

#

and you need to return value

buoyant quail
#

!d discord.app_commands.CommandTree.interaction_check

unkempt canyonBOT
#

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

A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.

The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
slate swan
formal basin
buoyant quail
#

no

#

it's a method of the tree

slate swan
#

you "override" it and add custom logic

buoyant quail
#

easiest way would be subclass it
or setattr, why not

formal basin
#

so what do I use?

slate swan
#

tree.interaction_check = my_custom_check i guess

#

where my_custom_check is coro that accepts interaction

formal basin
#

would my_custom_check = await interaction_check(interaction, nsfw)

cold sonnet
mental hollow
cold sonnet
#

!d discord.Role.members

unkempt canyonBOT
cold sonnet
#

yes

buoyant quail
cold sonnet
#

iterate if you wanna sound real smart

slate swan
#
async def my_custom_check(interaction):
    ...
formal basin
#

oh

#

i see

#

i thinl

cold sonnet
#

my_custom_check = interaction_check works tho

#

just doesn't make sense

#

oh right down said that

#

for a use that makes sense

formal basin
slate swan
#

you can check everything you want

formal basin
#

yeah

slate swan
#

for example if only one person can use commands you would do return interaction.user.id == 12345

formal basin
#

how to i stop the interaction from executing

#

i dont understand

slate swan
#

you return False

buoyant quail
#

return False

formal basin
#

what do i return false?

slate swan
#

imagine before the interaction is invoked it checks if interaction_check returns True

#

if it returns False it aborts

unkempt canyonBOT
#

discord/app_commands/tree.py lines 1209 to 1212

async def _call(self, interaction: Interaction[ClientT]) -> None:
    if not await self.interaction_check(interaction):
        interaction.command_failed = True
        return```
formal basin
#

yeah but if i check for if the channel is nsfw it and it returns true

#

it will still execute

slate swan
#

why is that?

formal basin
#

cause its true

slate swan
#

what is True

formal basin
#

if the channel is nsfw

slate swan
#

??

formal basin
#

you say if it is true

slate swan
#

but you know you dont have to do return interaction.channel.nsfw you can do more than that

formal basin
#

it still execute

slate swan
#

for example you can invert it

formal basin
#

if the interaction is an interaction

robust fulcrum
#

Guys how can I host a discord bot on a mobile phone?

slate swan
#

Ask @turbid condor

#

Step 1: Don't do it

slate swan
#

It checks if it should invoke the command

#

It checks if the interaction_check returned true

glad cradle
robust fulcrum
glad cradle
#

termux + proot-distro with arch or ubuntu

#

ah

robust fulcrum
#

Hmm imma try

formal basin
buoyant quail
#
async def my_custom_check(interaction):
    return not interaction.channel.is_nsfw()

Not so hard lemon_pensive

turbid condor
#

Otherwise I don't recommend doing it on personal use phone

robust fulcrum
#

Phones have which architecture? Arm?

turbid condor
#

Yeah

slate swan
turbid condor
#

Then again I don't recommend using a phone that u have to use for some other purpose

slate swan
#

What's so hard in understanding

  • if interaction_check returns True -> command does run
  • if interaction_check returns False -> command does not run
turbid condor
#

Cuz u will need the app open 24/7 to keep the bot running continuously

#

In the foreground not background

formal basin
#

like ```if not interaction.channel.is_nsfw:

robust fulcrum
slate swan
formal basin
onyx elk
onyx elk
turbid condor
robust fulcrum
formal basin
robust fulcrum
#

Should I get raspberry? It's way too expensive

turbid condor
slate swan
turbid condor
#

Otherwise you can use aws it has 1 year free trial

robust fulcrum
turbid condor
#

Or gcp

onyx elk
slate swan
formal basin
#

idk how to use it

slate swan
turbid condor
formal basin
turbid condor
formal basin
robust fulcrum
turbid condor
robust fulcrum
#

Why will a student have a card , they TF should understand

slate swan
#

,

turbid condor
robust fulcrum
#

U student?

turbid condor
#

Yeah

robust fulcrum
#

Which grade?

buoyant quail
turbid condor
#

University

robust fulcrum
#

Oh lol , i in 9 grade

turbid condor
robust fulcrum
#

Why they need card though they can get our verification from GitHub student

turbid condor
#

Welp it's their ToS

robust fulcrum
#

Hmm

turbid condor
#

Can't do anything about that

robust fulcrum
#

What's benefit of GitHub student then

#

Only jetbrains or copilot

turbid condor
#

Lots of benefits if u know how to utilize them

robust fulcrum
#

Which benefits, they all need cards probably

turbid condor
#

Nope not all

robust fulcrum
#

Like namecheap , heroku , etc

turbid condor
#

Welp as far as I'm concerned for me it provided with 3 domains for websites

formal basin
#
@bot.event
async def on_interaction(interaction: discord.Interaction):
   channel = interaction.channel

   if channel.is_nsfw():
       interaction.command_failed = True
       await interaction.followup.send('zagzag does not support NSFW channels.', ephemeral=True)
       return
   


   ``` this code works but the command executes after
slate swan
#

I believe there's a built-in decorator for NSFW commands

formal basin
#

how can i make the commands stop executing?

formal basin
slate swan
#

Hmmm

formal basin
#

i just need to know how to make it stop executing

slate swan
#

!d discord.app_commands.CommandTree.interaction_check Overwriting this method might be an option for you

unkempt canyonBOT
#

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

A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) should be processed by the tree.

The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
formal basin
#

await self.interaction_check(nsfw) wouldnt work

slate swan
#

You don't call it yourself

#

The library calls it to check whether a command should be invoked, you can overwrite the method to implement your own logic

#

The default implementation just returns True

formal basin
#
async def on_interaction(interaction: discord.Interaction):
   channel = interaction.channel

   if not channel.is_nsfw():
       await self.interaction_check(interaction)
       return
    else:
          await interaction.followup.send('zagzag does not support NSFW channels.', ephemeral=True)```
hushed galleon
#

as per delliott's explanation, you should override the CommandTree class that's used by your bot which will let you change what interaction_check() does

#

for example: ```py
class MyCommandTree(app_commands.CommandTree):
async def interaction_check(self, interaction):
if interaction.user.id == 1146836125290344540:
await interaction.response.send_message("I don't like you in particular")
return False

    return True

bot = commands.Bot(tree_cls=MyCommandTree, ...)```

young dagger
#

Is it better to do:

        if account_age.days > 30 and member.avatar:
            return

        unverified_role = discord.utils.get(guild.roles, id=769451860884062228)
        if unverified_role:
            await member.add_roles(unverified_role)

or

        if account_age.days <= 30 or not member.avatar:

            unverified_role = discord.utils.get(guild.roles, id=769451860884062228)
            if unverified_role:
                await member.add_roles(unverified_role)
slate swan
hushed galleon
young dagger
buoyant quail
#

Easier to read
Especially when it grows

young dagger
#

Makes sense, thanks

quick brook
#

Explain what you mean by that

young dagger
slate swan
#

nice url lol

#

QOOQ

quick brook
sick birch
#

That try except is huge

#

Also empty exception

formal basin
quick brook
slate swan
#

This is on_interaction and Like i said it does not decide whether command is invoked or not

young dagger
buoyant quail
young dagger
# sick birch That try except is huge

What exception would you use? What do you think about this:

    except discord.NotFound:
        pass

    except discord.Forbidden:
        pass

    except Exception as e:
        print(f"An error occurred: {type(e).__name__} - {e}")```
sick birch
#

There should be some sort of feedback instead of ignoring exceptions

slate swan
#

Or if you really wanna do nothing about some exceptions use contextlib.suppress

lyric sigil
#

i have this error trying running my program on vscode

#

i tried to uninstall and reinstall but not working

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

slate swan
#

Install it using this

lyric sigil
#

not working either

#

i have python on my pc and the extension on vscode

slate swan
#

do python -V

#

What's the output

lyric sigil
#
PS C:\Users\canai\Desktop\Partins_bot> python -V
Python 3.11.5
slate swan
#

Now, in vscode press Ctrl shift p

#

Type in Interpreter

#

Find setting Like Python: Set Interpreter or something about that

#

And select it to the 3.11.5

lyric sigil
#

okay and now

slate swan
#

and now run the script?

lyric sigil
#

same error

slate swan
#

What did you set the interpreter to

#

What options you Had

lyric sigil
#

okay i changed it to another because i had 2 options and now for some reason its working

#

Thanks !

slate swan
#

๐Ÿ‘

quick brook
lyric sigil
#

Do someone know a good repo who has a ticket system for my bot ?

eager mural
#

hello I can't find the function to give the number of channels on the server could someone help me

unkempt canyonBOT
eager mural
#

ty

tall temple
#

can someone give me a method to get every banned member's id in a server in a list

tall temple
unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).

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

Changed in version 2.0: Due to a breaking change in Discordโ€™s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
eager mural
#

pk ?

tall temple
#

HMMMM

left dew
#

does anyone know how to get rid of these types of errors? i have to click the button a few times for it to work
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

quick brook
#

If you're currently using channels to implement "tickets" (short lived conversations between a subset of people), please consider using discord's thread feature instead. Threads were made for exactly this purpose: to have a short, separate discussion with a subset of people. Trying to use channels for this is antiquated and has several limitations:

  • There is a strict limit on the number of channels in a server/category as well as the rate they can be created
  • Channel names can have strict limitations on partnered servers. There are certain numbers which can cause your channel to fail in creation
  • Threads have a much cleaner permissioning and archiving process

While you may be used to channels or prefer the UI, please consider if this is the correct tool for what you're trying to accomplish.

quick brook
# left dew does anyone know how to get rid of these types of errors? i have to click the bu...

all interactions must be responsed in 3 seconds or less. There are two things that could be happening here that would cause the error:

  1. You have blocking code
  2. Your code is not blocking, but is taking a very long time for some reason. In this case, you will need to defer the interaction. Deferring the interaction allows you to have up to 15 mins to respond, which will you will need to use await interaction.followup.send() in order to respond to the interaction
lyric sigil
quick brook
#

you can think of tickets as either fourm posts or short-lived threads

lyric sigil
#

but i asked for a repo -_-

left dew
quick brook
quick brook
left dew
#

can i use await interaction.channel.followup.send()?

left dew
#

oh

quick brook
left dew
#

ok ty

quick brook
#

np

full tinsel
#

Hey, is it possible to code Modals Pagination? Already spent 1 hour on trying to find out how to do it

quick brook
#

have an pagination menu within modals? nope you cant

tall temple
stiff herald
#

guys recently an customer ask me a nomination system, the fields exceed the discord limits in the forms plus there are requirements as well, and I don't have any very good idea how to handle it: How to show the fields and requirements? (PS: don't want to use google form)

onyx elk
#
@client.tree.command()
@app_commands.describe(
    channel='The voice channel to lock.',
    allowed_roles='Roles allowed to join the locked channel.'
)
async def lockvc(interaction: discord.Interaction, channel: discord.VoiceChannel, allowed_roles: discord.Role = None):
    """Lock a voice channel to prevent everyone from joining."""
    everyone_role = interaction.guild.default_role

    if not allowed_roles:
        # If no roles are specified, set the channel permissions to deny @everyone to connect
        await channel.set_permissions(everyone_role, connect=False)
        await interaction.response.send_message(f"{channel.mention} is now locked. `@everyone` can see but not join.")

    else:
        # If allowed roles are specified, set the channel permissions to allow those roles to connect
        await channel.set_permissions(everyone_role, connect=False)
        for role in allowed_roles:
            await channel.set_permissions(role, connect=True)
        
        allowed_role_mentions = ' '.join(role.mention for role in allowed_roles)
        await interaction.response.send_message(f"{channel.mention} is now locked. Only ''{allowed_role_mentions}` can join.")```
#

the command works fine without the role selected

#

but when u add a role it breaks and says that

quick brook
stiff herald
onyx elk
quick brook
onyx elk
stiff herald
quick brook
hollow owl
#

Hello. I'm a python newbie, but I just want to edit an existing open-source bot for my discord. The thing I want to do is that every user from this list gets a list with the others and their roles. How should I start?

#

Lemme check the code

hollow owl
onyx elk
hollow owl
#

or you're talking about the game

hollow owl
#

Yeah: mid, jungle, adc, top, support are their choices

onyx elk
hollow owl
#

Let me do it simpler, I want to do so every user in the embed gets this list (embed)(Like @hollow owl - Mid, @onyx elk - Adc etc.)

onyx elk
hollow owl
#

multiple buttons, they aren't discord roles, just their choices for a League of Legends match

hollow owl
#

no need to worry, I don't know either, just trying to help a friend but I think I need to explore more the code first as I'm not sure how to explain xd

#

thanks for trying to help me and understand :))

onyx elk
#

sorry i coudlnt be more help

young dagger
stiff herald
hollow owl
young dagger
#

Why?

onyx elk
young dagger
#

@hollow owl Did you upload the code?

stiff herald
slate swan
onyx elk
slate swan
#

so one Role object is not

young dagger
#

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

onyx elk
hollow owl
young dagger
#

@hollow owl You just need something that randomize users in a specific voice channel?

hollow owl
#

mmm.. not really

#

just forgot about it, I'll try to stick myself

stiff herald
# onyx elk so how would i edit it
@client.tree.command()
@app_commands.describe(
    channel='The voice channel to lock.',
    allowed_roles='Roles allowed to join the locked channel.'
)
async def lockvc(interaction: discord.Interaction, channel: discord.VoiceChannel, allowed_roles: discord.Role = None):
    """Lock a voice channel to prevent everyone from joining."""
    everyone_role = interaction.guild.default_role

    if not allowed_roles:
        # If no roles are specified, set the channel permissions to deny @everyone to connect
        await channel.set_permissions(everyone_role, connect=False)
        await interaction.response.send_message(f"{channel.mention} is now locked. `@everyone` can see but not join.")

    else:
        # If allowed roles are specified, set the channel permissions to allow those roles to connect
        await channel.set_permissions(everyone_role, connect=False)
        await channel.set_permissions(allowed_roles, connect=True)
        
        allowed_role_mentions = allowed_roles.mention
        await interaction.response.send_message(f"{channel.mention} is now locked. Only ''{allowed_role_mentions}` can join.")
onyx elk
young dagger
hollow owl
#

thanks

stiff herald
hasty pike
onyx elk
stiff herald
#

Or general programming?

onyx elk
#

thank you for helping!

umbral bay
#

guys does anyone know if discord bots show activity field and display something like listening to spotify

slate swan
unkempt canyonBOT
umbral bay
#

i'll check it out

#

let me know if something like this even exists for twitch

umbral bay
#

hmm maybe im missing out something

#

this is what i have done so far:

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

    while not client.is_closed():
        stream_title = await fetch_stream_title()

        if stream_title:
            await client.change_presence(
                activity=discord.Streaming(
                    name=stream_title, url="https://www.twitch.tv/codemiko"
                )
            )
            print(f'Bot status set to "streaming" with title: {stream_title}')
        else:
            await client.change_presence(status=discord.Status.online)
            print('Bot status set to online (user not streaming)')

        await asyncio.sleep(60)  # Check every 60 seconds
      
# Run the bot
client.run(TOKEN)```
#

it will show the status, now i'm trying to put it in the activity tab and have the watch now button too

slate swan
#

!d discord.Streaming

unkempt canyonBOT
#

class discord.Streaming(*, name, url, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity) that represents a Discord streaming status.

This is typically displayed via **Streaming** on the official Discord client.

x == y Checks if two streams are equal.

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

hash(x) Returns the streamโ€™s hash.

str(x) Returns the streamโ€™s name.
slate swan
#

see what arguments it takes

umbral bay
#

alrighty

onyx elk
#

!d discord.ActivityType.playing

unkempt canyonBOT
onyx elk
#

!d await client.change_presence(status=discord.Status.dnd, activity=discord.Game(name="Roblox"))

#

!d status

unkempt canyonBOT
#

Rich can display a status message with a โ€˜spinnerโ€™ animation that wonโ€™t interfere with regular console output. Run the following command for a demo of this feature:

python -m rich.status
```  To display a status message, call [`status()`](https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.status) with the status message (which may be a string, Text, or other renderable). The result is a context manager which starts and stops the status display around a block of code. Hereโ€™s an example:

```py
with console.status("Working..."):
    do_work()
```  You can change the spinner animation via the `spinner` parameter...
onyx elk
#

!d discord.Status.dnd

unkempt canyonBOT
wispy solstice
#

Does anyone knows why imgur direct links isn't working in embed.set_image, ( some work and other no, is it only me? )

wispy solstice
onyx elk
#

embed.set_image(url=imgur_url)

#

like that

#

or sum like that

#

whatev u want really

wispy solstice
#

i did, but it's not showing image

onyx elk
wispy solstice
#

not rlly now, my pc is off

#

but it's like that

onyx elk
wispy solstice
#

print(data["Poster"]) > output: imgur link
embed.set_image(url=data["Poster"])

#

no exceptions raised

onyx elk
#

if image_url:
embed = discord.Embed(title=f"{prompt} has been generated!", color=discord.Color.blue())
embed.set_image(url=image_url)
embed.set_footer(text=f"ยปBOT BY ALF!ยซ")

        await interaction.response.send_message(embed=embed)
#

heres a code for my bot that generates images from my webserver

wispy solstice
#

it's somehow like this, but the image isn't been displayed ( i can access it from browser normally )

wispy solstice
#

idk if it's imgur's fault, or something else

wispy solstice
onyx elk
#

hmm

wispy solstice
#

checked with printing

onyx elk
#

when u on ur pc send code

wispy solstice
#

anyway ty

final iron
#

If the link works in your url, most likely it's an issue with Discord

meager rock
quick brook
#

ensure that the url points to an asset

meager rock
#

Url that points to the image address on Imgur won't work

harsh orbit
#

How can I know which servers the bot is located on? And how do I get their links?

unkempt canyonBOT
meager rock
#

this will return a list of Guild objects your server is in

#

For the invite you'll have to create an invite thru a channel in the guild

#

!d discord.abc.GuildChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

hi

#

how to use a serverbotter script .py btw

slate swan
#

What now

finite sage
#

Hello, I try to make it send a message every 10 second, but it say "improper token"

#

This is false, i have check the token 100 times, yes it is correct. Help !

#
import os
import discord
import random
import asyncio
from discord.ext import commands
from colorama import Fore, Style

token = input("[TOKEN:")
client = commands.Bot(command_prefix=commands.when_mentioned_or("$"))
os.system('cls')
os.system(f'-7TACEY PRESS')
os.system(f'mode 100,25')

SENTENCES = [
    "Hey",
    "Hi",
    "Lol",
    "Haha",
    "How are you doing today?",
    "What's up?",
    "How's your day going so far?",
    "Good morning!",
    "Good afternoon!",
    "Good evening!",
    "Hello there!",
    "Nice to meet you!",
    "I'm glad we could chat!",
    "Have a great day!",
    "See you later!"
]

async def send_messages(channel):
    for sentence in SENTENCES:
        await channel.send(sentence)
        await asyncio.sleep(10)

@client.event
async def on_ready():
    print(f""" \u001b[31m
{Fore.BLUE}                   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•—
{Fore.BLUE}                   โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ•—โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•
{Fore.BLUE}                   โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘    โ–ˆโ–ˆโ•”โ•   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• 
{Fore.BLUE}                   โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•    โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ•”โ•โ•โ•    โ•šโ–ˆโ–ˆโ•”โ•  
{Fore.BLUE}                   โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•   โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘  โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•‘   
{Fore.BLUE}                    โ•šโ•โ•โ•โ•โ•โ•    โ•šโ•โ•     โ•šโ•โ•   โ•šโ•โ•  โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ•โ•   โ•šโ•โ•   
{Fore.BLUE}                                                           
{Fore.BLUE}
{Fore.BLUE}                           MADE BY:{Fore.RED} ESCAPE/07TACEY
                                      ---------------------------------
""")

    channel = client.get_channel(985266327088410664)
    while True:
        await send_messages(channel)

client.run(token, bot=False)```
brazen raft
slate swan
#

self-botting susge

finite sage
#

It work like 5 months back

finite sage
#

its for bot

slate swan
#

read what Roie said then

finite sage
#

i know, i already remove that

#

but it say improper token

slate swan
#

post the full traceback

#

(looks like you're also forgetting to pass intents into the Bot constructor)

finite sage
#

no i dont need intents, its not bot

brazen raft
#

Instead of pasting the token for the line with input, save the token in a text file and read the text file for the token. Maybe input is messing with you or you're pasting unexpected characters

brazen raft
#

intents is a required keyword argument for the constructor of discord.ext.commands.Bot

slate swan
#

and use tasks loop approve

#

won't surprise me if that on_ready is causing all sorts of problems

finite sage
brazen raft
#

For better clarity and assurance you could move the sleeping into the infinite while loop

brazen raft
finite sage
#

It is ok, i do fix later

#

but that is main error

Traceback (most recent call last):
File "main.py", line 10, in <module>
client = commands.Bot(command_prefix=commands.when_mentioned_or("$"))
TypeError: init() missing 1 required keyword-only argument: 'intents'

brazen raft
#

See, intents is required. You need to add intents=your_intents_here in commands.Bot(...)

finite sage
#

You think that is for bot

latent anchor
#

do anyone know whats this error? my bot showed this for a very long time and it doesnt reply to commands now
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.

finite sage
#

enable it

latent anchor
#

how do i do that

finite sage
onyx elk
#

hi

latent anchor
brazen raft
latent anchor
#

ohh

#

ok thanks ill try it

finite sage
#

you think that would work if i do this

#

i copy that message request from network and i keep sending it in console

#

it will work i think

latent anchor
#

ah the code works fine after i added that
tysm

finite sage
#

OK

#

I need help someone help

#
import os
import discord
import random
import asyncio
from discord.ext import commands
from colorama import Fore, Style
from keep_alive import keep_alive

intents = discord.Intents.default()
intents.typing = True

token = input("TOKEN:")
client = discord.Client(intents=intents)
os.system('cls')
os.system(f'-7TACEY PRESS')
os.system(f'mode 100,25')

SENTENCES = [
    "Hey",
    "Hi",
    "Lol",
    "Haha",
    "How are you doing today?",
    "What's up?",
    "How's your day going so far?",
    "Good morning!",
    "Good afternoon!",
    "Good evening!",
    "Hello there!",
    "Nice to meet you!",
    "I'm glad we could chat!",
    "Have a great day!",
    "See you later!"
]

async def send_messages(channel):
    for sentence in SENTENCES:
        await channel.send(sentence)
        await asyncio.sleep(10)

@client.event
async def on_ready():
    print(f""" \u001b[31m
{Fore.BLUE}                   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•—
{Fore.BLUE}                   โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ•—โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ•
{Fore.BLUE}                   โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘    โ–ˆโ–ˆโ•”โ•   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• 
{Fore.BLUE}                   โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•    โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ•”โ•โ•โ•    โ•šโ–ˆโ–ˆโ•”โ•  
{Fore.BLUE}                   โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•   โ–ˆโ–ˆโ•‘     โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘  โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•‘   
{Fore.BLUE}                    โ•šโ•โ•โ•โ•โ•โ•    โ•šโ•โ•     โ•šโ•โ•   โ•šโ•โ•  โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ•โ•   โ•šโ•โ•   
{Fore.BLUE}                                                           
{Fore.BLUE}
{Fore.BLUE}                           MADE BY:{Fore.RED} ESCAPE/07TACEY
                                      ---------------------------------
""")

    channel = client.get_channel(985266327088410664)
    while True:
        await send_messages(channel)

keep_alive()
client.run(token)
``` I have made a bit changes since the last one
#

ERROR

#
  File "main.py", line 61, in <module>
    client.run(token)
  File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 860, in run
    asyncio.run(runner())
  File "/nix/store/5g6y3nzq80fkq54ahan2slc57j6327nj-python3-3.8.15/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/5g6y3nzq80fkq54ahan2slc57j6327nj-python3-3.8.15/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 777, in start
    await self.login(token)
  File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/client.py", line 612, in login
    data = await self.http.static_login(token)
  File "/home/runner/auto-typer-2/venv/lib/python3.8/site-packages/discord/http.py", line 807, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.```
quick brook
wispy solstice
#

Do I need to make 2 classes?

quick brook
#

Yes. You would want to make two select classes and then just add them to the view

wispy solstice
quick brook
quick brook
wispy solstice
#

ty

quick brook
#

Np

quick brook
quick brook
#

I would recommend just completely removing your message spam feature bc we all know how it will end up

quick brook
# finite sage I need help someone help

My dude you have created a spam bot. Why do you need to go through like 14 different messages every 10 seconds? On top of this, have fun with getting rate limited

#

As a result, I'm not helping you out

finite sage
#

And this error is very recent, I used this in April with 0 problems.

finite sage
#

I know how to copy and paste my token

finite sage
finite sage
meager rock
#

is this a selfbot, by any chance?

finite sage
#

Yes it is

meager rock
#

yeah discord.py doesn't support self bots, and we are not supposed to help with that here. Sorry

finite sage
#

there are working selfbots

meager rock
#

figure it out then lol, it's against rule 5 to discuss self bots here

finite sage
#

it is not self bot

naive briar
finite sage
#

lol

onyx elk
#

can someone tell me why this doesnt show in appspy @client.tree.context_menu(name='Shows user Join Date') async def show_join_date(interaction: discord.Interaction, member: discord.Member): member = member await interaction.response.send_message(f'{member} joined {discord.utils.format_dt(member.joined_at)}')

slate swan
#

Why do you even need the line member = member

onyx elk