#discord-bots

1 messages · Page 80 of 1

primal token
#

on_ready!

slate swan
primal token
light jungle
#

I have a question, is it possible to send a message after a person has replied to a bot message through the "reply" item?

#

I advise you to watch the tutorial on how to simply launch a discord bot and display a message, and after that google those things that you are interested in doing (if you didn’t find anything, like in my case, then look for help)

#

in general, although I am far from an expert, my 1 hour was the same. Well, again, about my message, ask around, I'm a so-so teacher

#

I've been in this thread for a month and a half

#

overall a newbie

plucky knoll
#

I think that you are trying to edit the variable mess which is an interaction, not a message.

honest shoal
#

where have you defined mess?

slate swan
#

hi anyone know how can i stop the error show cause its not an error

silk fulcrum
#

you were already answered

slate swan
silk fulcrum
#

bruh

honest shoal
#

why are you using ctx if it's an interaction, and you cannot edit interaction msg directly

silk fulcrum
#

or smth like that

slate swan
silk fulcrum
slate swan
honest shoal
#

😵

primal token
#

Its not weird, its terrible

slate swan
#

@bot.event
async def on_command_error(ctx, error):
pass

#

and the error stop show

maiden fable
#

message content intent

radiant parrot
#
async def send_mute(user, reason: str):
    channel = client.get_channel(925912014398844998) # channel mute case put in
    em = discord.Embed(title="**MUTED**",
                       color=discord.Color.red())
    em.add_field(name='Member:', value=f'{user}')
    em.add_field(name='Duration:', value='1 day')
    em.add_field(name='Reason:', value=f'{reason}')
    em.set_footer(text=f'Provided by Donks#1048 • {current_time}')
    em2 = discord.Embed(title="**MUTED**", description=f"You have been muted because: {reason}",
                        color=discord.Color.red())
    await channel.send(embed=em)
    await user.send(embed=em2)

@client.command()
@has_permissions(manage_channels=True)
async def mute(ctx, user: discord.Member):
    date = timedelta(minutes=1440)
    await user.timeout(date)```
#

Why isnt this muting user?

scarlet girder
#

Hi

outer parcel
#

the way i muted a member was with this

#

So do

#
await user.timeout(discord.utils.utcnow()+date)

#

make sure all intents are enabled for bot

radiant parrot
#
    async def button_callback_2(interaction):
        await interaction.response.send_message(f'Disapproved and muted user!')
        await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')```
outer parcel
#

So you know where you got the token for the bot

#

if you scroll below you see this

#

just tick intents

#

and it should work

#

otherwise im not sure

#

after enabling them

#

you know the area where you initialised the client

#

like client = discord.Client()

#

Put intents = discord.Intents.all() above it

#

and then change client to
client=discord.Client(intents=intents)

#
intents = discord.Intents.all()

client = discord.Client(intents=intents)
#

if it is still confusing

#

nice

slate swan
#

i’m currently getting this error:
TypeError: TypedDict does not support instance and class checks
I found this report but i’m not sure how i fix the error: https://bugs.python.org/issue44919

#

guys how do i make my bot send command without prefix

split merlin
#

Hello, I have been away from discord.py for a few months and when i came back, i noticed that my code isn't fully working like before i left
what's not working anymore is how i access my db
i use aiosqlite as my database, how i access it is like this

async def start():
    await client.wait_until_ready()
    client.db = await aiosqlite.connect("test.db")

@client.command()
async def test(ctx):
  print(1)
  async with client.db.execute("SELECT * FROM test") as cursor:
      print(2)
      tests = await cursor.fetchall()
  print(3)

async def main():

    async with client:
        client.db = await aiosqlite.connect("test.db")

        client.loop.create_task(start())

        await client.start(TOKEN)


if __name__ == "__main__":
    asyncio.run(main())

    asyncio.run(client.db.close())

print(1) does print but it stops after that, meaning the command stops at async with part, so i am not sure why it happened since it used to work fine like 1-2 months ago

slate swan
#

How do you make a command without prefix ?

#

yes

#

ok

silk fulcrum
#

command_prefix=""?

slate swan
sick birch
#

Many of them breaking changes

split merlin
#

for it to stop it

sick birch
#

You probably want to move your database connection into setup hook

split merlin
#

hmm how so?

split merlin
#

i tried sqlite3 and the same thing happened

faint sapphire
#

hey, i use my raspberry pi to host a discord bot,
i sometimes have issues with the Pi and want to use heroku as a backup sometimes
rn my main has 0 credits for the free working dyno
i made an alt on heroku but the bot wasnt running, so i also made an alt on github to connect to a diff account, still doesnt work
any suggestions?

iron sorrel
split merlin
faint sapphire
#

still offline tho

#

i have requirements file, procfile, and runtime file

sick birch
sick birch
split merlin
sick birch
unkempt canyonBOT
#
I don't think so.

No documentation found for the requested symbol.

sick birch
#

smh

#

!d discord.Client.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/api.html#discord.Client.login "discord.Client.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 "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/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
split merlin
#

oh thanks

sick birch
#

if you want an example:

class MyBot(commands.Bot):
  ...

  async def setup_hook() -> None:
    # setup anything you need to here

bot = MyBot(...)
bot.run(...)

@split merlin

split merlin
#

alrigjt thanks

faint sapphire
#

is it okay if i have a command, when its used, the script calls a function that does the following:
-does webscraping (ab 11 pages or 22 pages)
-updates data in an sqlite3 database (ab 300 tuples or 600)

its gonna be a long pause, but idk how to make it do that whilst being able to respond to other commands

sick birch
#

I suppose.. I haven't seen it used that way, so I'm not 100% sure. You should be using setuphook just to be sure

somber imp
faint sapphire
#

ok thanks

somber imp
#

What about that?

sick birch
#

!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...
somber imp
#

Yeah that's correct. But that wasn't op's problem. It was a function blocking the event loop

sick birch
#

You're right but this isn't about defering it's about blocking the event loop

split merlin
sick birch
#

For databases and discord bots usually a good idea to go with an asynchronous version. Aiosqlite and asqlite are popular

sick birch
unkempt canyonBOT
#
Resources

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

somber imp
#

I wonder which module allows for webscraping asynchronously

slate swan
#

im stuck can someone help me understand what to do now?
this is my code: https://paste.pythondiscord.com/okidiyeral
and thats what i want to achieve:

For every user i want to create this row with
His number defined in embed above, values buttons about modes values ({"bedwars": True, "duels": True}), save button

On values button click i want to change value to negative from current one

On save button click i want to save current player mode values and save them back to database

i wrote all comments directly in code in that paste link

somber imp
#

You know you can only have 5 rows of buttons right

So you can have only 4 users on there (1 row is the top row)

slate swan
#

Yes the maximum amout of users will be 3

slate swan
somber imp
#

Hmm

#

I haven't read the code yet, but thought of giving a little heads up

slate swan
#

does anyone know how to get an actual member object from a ping? im saving it as "<@167826whatevernumbers>" But when I try to set permissions for that user it tells me it needs to be a role; or maybe a way to convert that to the member object?

primal token
slate swan
#

The numer after @ is an id you can get member object you Can do await bot.get_user(id)

slate swan
#

Or bot.fetch_user(id)

primal token
#

they both return a User object?

slate swan
#

That's most likley the same

primal token
#

They're not the same.

slate swan
#

so take out the <@ > and use the number in the get_user function?

primal token
#

Its a method and to be specific its name is a snowflake and it returns an instance of User , which you specified you wanted an instance of Member object, no?

slate swan
#

okidoki, shall try

primal token
#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
primal token
#

this is what you're looking for, no?

slate swan
# unkempt canyon

Maybe, if that returns it as a member then yeah thats what im looking for, got a lil lost with what Down said, but its alright, ill try this out in a moment

primal token
#

It can return Member | None

slate swan
primal token
#

sure

slate swan
#

Its complicated i would say

primal token
#

The issue?

slate swan
#

im explaining all in the code

#

i noticed im doing something wrong on line 52

#

there are comments everywhere almost so

#

anyone know how i can fix that

tawdry tendon
#

Ye

#

Download it

slate swan
#

i have do the pip thing but i got

#

ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32)
ERROR: No matching distribution found for pywin32>=223

primal token
# slate swan there are comments everywhere almost so

Just dont subclass discord.ui.Button its unnecessary and unneeded, just use the decorator discord.ui.button that registers the button to the View subclass it's inside in, so you can access all the values in any button

slate swan
primal token
slate swan
#

it can be 1 or it can be 3

primal token
slate swan
primal token
#

saving*

slate swan
#

yeea

#

i want to add also Save all below

#

to save all changes

#

its gonna be hard to code i think

primal token
#

@slate swan upon thinking, why not just pass each config button instance to the save button?

slate swan
#

does self.add_item return instance?

primal token
slate swan
#

i think this is too many combining

#

im thinking with creating a class of User

#

and then creating it all inside it

primal token
primal token
slate swan
#

so i have access to it inside that class but how can i add that to View crying why it must be so hard

#

anyone know how i can fix that

slate swan
primal token
# slate swan so i have access to it inside that class but how can i add that to View <:crying...
 for i, (uuid, user) in enumerate(users.items(), 1):
            self.add_item(nextcord.ui.Button(label=i, style=nextcord.ButtonStyle.blurple, row=i)) # add numbers corresponding to a player defined in embed above View
            
    for mode, value in user.items():
        self.add_item(config:=ConfigButton(mode=mode, value=value, row=i)) # add switchable config buttons    
    self.add_item(SaveButton(label="Save", row=i, config)) # add save buttons

and then upon the callback of the save button just check the values of the passed button

slate swan
slate swan
slate swan
primal token
#

Alright

wicked kayak
#

if sum1 knows the command lmk pls

primal token
wicked kayak
slate swan
primal token
primal token
slate swan
#

cause now it would pass only last one or error

primal token
#

can you explain your issue?

slate swan
#

its indented outwards

primal token
slate swan
#

the SaveButton is not in the for loop adding ConfigButton

primal token
slate swan
#

?

#

no its not

primal token
#

what

slate swan
#

you are looking on wrong for loop

primal token
#

Yeah youre saving the button inside of the parent for loop as i said?

slate swan
#

!e ```py
for i in range(9):
print(i)

print(i)

unkempt canyonBOT
#

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

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 8
slate swan
#

it will only add last element

primal token
#

its inside of the parent loop?

slate swan
#

but the parent loop doesnt matter

#

we are looking into the nested loop

primal token
#

I'm so confused

crimson plover
#

How do i make commands non case sensitive? for example if i did /help it will pull up the menu but i also want it to work if they did /HeLp

crimson plover
#

all

slate swan
#

slash commands already work like that...

crimson plover
#

theseare prefixed

slate swan
#

you can pass argument to bot

crimson plover
#

its for prefixed commands

primal token
slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
slate swan
primal token
unkempt canyonBOT
#

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

crimson plover
#

ah tyvm

slate swan
#

yeah this

crimson plover
#

❤️

#

i was looking for it i guess im just freaking blind

#

sorry for the trouble

slate swan
#

@primal token your solution works

primal token
#

😭

slate swan
#

at least for now lol

primal token
#

I love how i'm confused but yet i helped you😭

slate swan
#

now yet another hours need to be spent on adding Save all and adding members

#

☠️

primal token
#

lovely😭

crimson plover
#

hm i think im dumb... what am i doing wrong here then... figured that would be simple

#

i see that it says this.. Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well. but i set it in the group command as well

slate swan
#

RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('cogs.mod2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
crimson plover
#

So if i do this
helpcmd command is not case insensitive but the console and rcon are.. so i can do +helpcmd RcOn or +helpcmd CoNsOle and they work fine with that code but not the helpcmd itself... if i did +HeLpCmd.. or +hELpcMd RcOn

primal token
#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

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

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.

Note

This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.

Changed in version 2.0: `member_id` parameter is now positional-only.
primal token
#

use this, only if Guild.get_member returns None so you dont need to do unneccesary calls ^

slate swan
#
member = guild.get_member(float(newString.split(" ")[0]))

just to make sureee this is how its supposed to look right?

primal token
slate swan
#

gotcha, the split is just because im taking a message with 2 pings and I want to individually make them into a variable, but okay gotcha, ill check out the fetch_member thing

crimson plover
#

Nevermind I got it working..... had to change something i didnt even think about

#

i had to do this now everything works non case sensitive..

#

just posting in case anyone else runs into this problem

slate swan
#

this worked thank you RosyLove

potent reef
#

wth does int ents mean it won't let me start my discord bot without it and i googled it and nothing good poped up

oblique laurel
#

Change to the developer terms of service? What is changing?

lone lichen
naive briar
#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
clever dune
#

@rancid inlet pls help

rancid inlet
clever dune
#

Ok

rancid inlet
clever dune
#

K

shrewd apex
clever dune
#

for pip i mentioned pep

#

Mis typed

slate swan
acoustic parcel
#

i havent used python in a few weeks and now none of my code is running. It says the error is from "client = discord.Client()" and intents is mandatory or smth. when i type "client = discord.Client(intents = intents)" theres an error on the line in "client.run(token)". send help ty

slate swan
acoustic parcel
jagged adder
#
@bot.command(name='vault')
async def vault(ctx):
    await ctx.send("**__Enter password to continue...__**")
    pswd_check = []

    async def check(message):
        print('checking if func working')
        passwords = ['table']
        for word in passwords:
            if word in message.content:      pswd_check.append(word)
                break
    await bot.wait_for('on_message', check=check)

how come the wait for check is never even called? it seems to still wait for it, as a print after the bot.wait_for isnt called

#

the reason i say it doesnt call the check, is because the print at the top of the check func never prints

primal token
jagged adder
#

yeah i think i just figured out that was part of my problem

#

ok i have one other issue; the bot.wait_for seems to be on a loop; i cant get to code beneath it

jagged adder
jagged adder
naive briar
#

Replace break with return True

jagged adder
#

ahhh so the wait for is waiting for something to return true or false

#

that makes sense

#

since i wasnt returning a value it would of automatically returned false.

#

ah great, cheers!

worthy mortar
#

Good resources hosting a discord bot in EC2?

sick birch
#

What are you looking for? Just install python and run it as usual

jagged adder
#

i have

    def check(message, user):
        if user.bot is False:
            for word in passwords:
                if word == message.content:
                    pswd_check.append(word)
                return True

    await bot.wait_for('message', check=check)

why does this come up in the terminal;
TypeError: check() missing 1 required positional argument: 'user'

#

my checks have never needed arguments before

#

apart from message anyway

naive briar
jagged adder
#

alright

primal token
jagged adder
#

in this example here, how would i go about deleting the previous set of entries? ie keep the most recent 2, but delete the prior set to avoid spam

#

this isnt in a set channel, so i cant just delete all

#

i know how to delete the current set, but idk how id remove the ones above

jagged adder
#

tho is content part of a msg...?

#

or the whole

naive briar
jagged adder
#

simply that depending on what pswd is entered, it opens a different door so to speak.
like so;

    if pswd_check.count('exit'):
        await ctx.channel.send('*Closing Vault...*')
        return
    
    if pswd_check[0] in ['table', 'chair']:
jagged adder
#

i can manage my seperate rooms

#

if content means the entire msg, i can then just append the message in the way that noid was suggesting

slate swan
#

how can I get disk usage , memory usage and cpu usage by the bot and send it?

vale wing
unkempt canyonBOT
#

Cross-platform lib for process and system monitoring in Python.

jagged adder
vale wing
jagged adder
#

oh ye

jagged adder
vale wing
vale wing
somber garnet
#

How to add buttons in discord bot?

#

Can anyone send the docs for buttons in discordpy?

naive briar
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
vale wing
dull knot
#
    """"Hack Command"""
    @commands.slash_command(name="hack", description="Hate someone? Hack their account!")
    async def HackUser(self, inter, target: disnake.Member):

        Embed1 = disnake.Embed(title="",
                              description=f":Load: Hacking {target.display_name}...",
                              colour=disnake.Colour(0x2f3136))

        Embed23 = disnake.Embed(title="",
                              description=f":Load: Injecting malware: Trojan, Viruses, Worms, Ransomware...",
                              colour=disnake.Colour(0x2f3136))
        Message = await inter.channel.send(embed=Embed1)
        await asyncio.sleep(3)

        await Message.edit(embed=Embed23)
        await asyncio.sleep(3)

This sends and edits the msgs but for some reason, when I do the interaction, it sends this.

What do u guys think is the problem?

vocal snow
#

You aren't responding to the interaction

dull knot
#

Wym?

vale wing
#

Pro naming convention

vocal snow
#

!d discord.InteractionResponse

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").

New in version 2.0.
vestal dagger
vocal snow
#

You need to call some Interaction.response.x to respond

dull knot
#

Wait. Lemme try

vocal snow
#

And respond within 3 seconds

jagged adder
#

how would i go about pulling a user ping from a message, and using that in a diff func?

#

so for example if someone else pinged me;
@jagged adder like so; is there a way to pull the id of the person that was pinged (not the message author) and then use that id for something? ie so the bot can say
"pst @jagged adder, someone wants you"
as an example

#

@vocal snow u seem to know your shit when it comes to this kind of thing; got any ideas?

vocal snow
jagged adder
vestal dagger
jagged adder
#

ah

vestal dagger
jagged adder
#

where do i put the message.mentions tho

vestal dagger
jagged adder
#

im using a bot listener atm

#

but pretty much yes

#
@bot.listen('on_message')
async def ping(ctx):
    if ctx.author.id in [..., ...]:
        l = ctx.mentions
        print(l)
#

otherwise it breaks my commands

#

made an edit, and now i see the list u were talkin about

vestal dagger
#

mentionedperson = message.mentions[0] is how I would do it

jagged adder
#

yeah i was just testing with the above

vestal dagger
#

kk nice

jagged adder
#

and then if i do print(l[0].id), boom i got the id

#

nice

#

well tyvm

vestal dagger
jagged adder
#

now to mention them using the id...

vestal dagger
shrewd apex
#

@shrewd apex

jagged adder
#

yup

#

done

#

cheers yall!

vestal dagger
#

nice

buoyant quartz
jagged adder
#

now the only thing left is sending an automatic msg to my sister at a set time tmrw; everything else has been designed and finished! (for context, i am creating a little bday surprise within my bot for her bday)

jagged adder
#

id like to thank the various peeps who have helped me out over the last couple days in getting this together and working; cheers yall!

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

naive briar
#

You can set the button's callback function

view = View()
button = Button(label="Ping")
view.add_item(button)

async def button_callback(interaction: discord.Interaction):
    await interaction.response.send_message("Pong!")
button.callback = button_callback
mild nimbus
#

missing 1 required keyword-only argument: 'intents'

#

what do i do?

naive briar
slate swan
#

does anyone have a src for a Premium system for .redeem and .gen

mild nimbus
#

what line

#

figured out tyyyyyyyyyyy

naive briar
mild nimbus
#

i have another issue

naive briar
#

By putting inside your bot or client constructor I mean

client = discord.Client(intents=discord.Intents.default())
pulsar solstice
#

how to send message in discord,py with out ctx ot message attribute?

naive briar
mild nimbus
pulsar solstice
naive briar
mild nimbus
pulsar solstice
#

I have a interaction in a class

naive briar
#

It contains your bot's token

pulsar solstice
#

delete it before I use it XD

mild nimbus
#

ill just reset it

pulsar solstice
#

but no worries I will not do anything

mild nimbus
#

already did lol

naive briar
#

That's sad

pulsar solstice
mild nimbus
#

alright so what do i do?

naive briar
pulsar solstice
#

ok okaay

#

lemme try

mild nimbus
#

WORKEDDDD

pulsar solstice
dull knot
#

Is there a way to disable this? Sends twice because I'm hosting the bot using this hosting site

naive briar
#

What's the hosting site

mild nimbus
pulsar solstice
mild nimbus
dull knot
mild nimbus
#

imma continue making my bot thanks for help , cya!

dull knot
pulsar solstice
naive briar
naive briar
#

Well then I can't help with that

dull knot
#

Here's the code for conifrmation:

        Random = ["Heads!", "Tails!"]
        Randomize = f"{random.choice(Random)}"

        EmbedFlip = disnake.Embed(title="",
                              description="*The coin is flipping...*",
                              colour=disnake.Colour.random())

        EmbedResult = disnake.Embed(title="",
                              description=f"**__{Randomize}__**",
                              colour=disnake.Colour.random())

        Message = await ctx.send(embed=EmbedFlip)
        await asyncio.sleep(3)

        await Message.edit(embed=EmbedResult)
#

Ouch. Welp. I guess I'll have to look for google answers lol

#

Also noticed that it only sends twice for prefix cmds lol.

pulsar solstice
#
Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task  
    await item.callback(interaction)
  File "c:\Users\8ster\Bot\main.py", line 80, in variable
    await interaction.followup("HEY")
TypeError: 'Webhook' object is not callable
naive briar
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
pulsar solstice
naive briar
#

Since the interaction.followup is a webhook object, you have to use that

pulsar solstice
#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 82, in rock
    await discord.Webhook.send("I LOST :-(")
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1673, in send
    if self.token is None:
AttributeError: 'str' object has no attribute 'token'```
#

why do I need token here

naive briar
#

I mean

pulsar solstice
#

bruh

naive briar
#

Use interaction.followup.send

slate swan
#

I swear nobody starts discord bots after learning OOP lmao

pulsar solstice
#

we have to do a lot in a limited day BRUH

shrewd apex
#

how is that an excuse for not learning relevant knowledge to what u are attempting to do

pulsar solstice
#

i tried to start leraning it for 4 days

#

I GAVE UP

dull knot
#

Bruh lol. At least learn and try kek

pulsar solstice
#

now I just seek to through documentation and write code

dull knot
#

Anyways. Question:

What does sync_commands do?

pulsar solstice
dull knot
dull knot
pulsar solstice
#

like the sync with the program commands

slate swan
slate swan
dull knot
#

Disnake

#

Can't really write code rn since I'm at phone so for now, I'll just ask what it does

slate swan
# dull knot Disnake

it's just a setter if disnake should automatically sync the slash commands with the discord api for you or not

bot = commands.Bot(...)
bot.sync_commands = False

that's how you use it

dull knot
#

Alright. Noted

slate swan
#

it's defaulted to True too

dull knot
#

Oh, so then I shouldn't need to bother lol

#

Thanks for the help

slate swan
shrewd apex
dull knot
slate swan
#

no someone who understands discord bots well

#

no just asking there cause my channel is based on discord bots ...

naive briar
unkempt canyonBOT
#

Hey @dim geyser! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

dim geyser
#
import os
from neuralintents import GenericAssistant

chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_mode()

print("Client running...")

client = discord.Client()

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

    if message.content.startwith("$aibot"):
        response = chatbot.request(messge.content[7:])
        await message.channel.send(response)

client.run(#token)
#

i keep getting no model named discord

#

help please

naive briar
#

Ah, well, first thing is you should use bot.event instead of bot.listen; second, there's no such event as on_button_callback.

shrewd apex
#

u have to add callback for button

#

no not an event

#

wait lemme check pycord docs

dim geyser
#

can someone help me now?

#
import os
from neuralintents import GenericAssistant

chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_mode()

print("Client running...")

client = discord.Client()

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

    if message.content.startwith("$aibot"):
        response = chatbot.request(messge.content[7:])
        await message.channel.send(response)

client.run(#token)
#

i get no model called discord

dim geyser
#

i already installed discord and neuralintents

#

why wont anyone respond to me

naive briar
shrewd apex
#

same as dpy callback

vale wing
dim geyser
shrewd apex
#

well pycord discord disnake nextcord 99% of the time similar syntax

dim geyser
#

and pip install neuralintents

vale wing
dim geyser
#

pycharm

#

i guess thats the problem?

#

what editor should i use

naive briar
#

You can use on_interaction and check the interaction type if it's from a component

vale wing
dim geyser
#

so now i have to create a resources.txt

#

but where

vale wing
#

And you might mess it up if you don't know how it works decently well

slate swan
shrewd apex
#

nope u still have few stuff u did wrong

dim geyser
#

what editor should i use?

vale wing
#

Pycharm is okay

dim geyser
#

then how do i fix it

shrewd apex
#

just use pycharm

vale wing
#

@dim geyser what message do you get after pip install

dim geyser
#

just pip install?

slate swan
shrewd apex
#

i always find vsc linter for python too slow

dim geyser
#

ERROR: You must give at least one requirement to install (see "pip help install")

shrewd apex
slate swan
paper sluice
shrewd apex
#

assign callback to button and its not ctx its an interaction object

vale wing
#

I need the message you get after installing literally any package

shrewd apex
#

and its interaction.data["custom_id"]

vale wing
#

@dim geyser

hollow ice
#

help me fix it??

see code:

bad_words = ['hii', 'world', 'never']

@client.event
async def on_message(message):
  await client.process_commands(message)
  for bad_word in bad_words:
    if bad_word in message.content.lower().split(" "):
      await message.delete()
      bad_word_embed = discord.Embed(title = "Bad Word", description=f"{message.author.mention}, please do not say any bad words")
      await message.channel.send(embed=bad_word_embed, delete_after=5.0)
vale wing
#

How is client defined

slate swan
#

client = discord.Client uwu

hollow ice
#

what?

vale wing
#

Imagine if uwu was a keyword

hollow ice
#

this automod is bad word and auto delete

slate swan
#

just use discord's automod-

shrewd apex
#

just use discord inbuilt automod ducky_drawing

hollow ice
#

yes

vale wing
#
package main
import "fmt"

func main() {
    var bruh uwu
    fmt.Scan(&bruh)
    fmt.Println(bruh)
}```
vale wing
paper sluice
#

🤢

shrewd apex
vale wing
#

That is go!

hollow ice
vale wing
shrewd apex
#

where ur eols ;-;

vale wing
#

Link in bio

shrewd apex
#

evenfix bio flex pithink

vale wing
#

Cuz you won't understand its code I am 69% sure

shrewd apex
#

i am 96%

vale wing
hollow ice
#

bruh! show me code!! is good work

shrewd apex
#

end of line

vale wing
hollow ice
#

ok

paper sluice
#

epic promotion time

hollow ice
vale wing
#

Just star them all 😉

vale wing
glad cradle
#

hey 9047064c7ec960627a11743bfa49b0af3e8dd702ef771cec3e908b5cd28b477e

hollow ice
#

@vale wing can help me??

code:

class myclient(discord.Client):
    def __init__(self,*, intents: discord.Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        self.tree.copy_global_to(guild=all)
        await self.tree.sync(guild=all)
naive briar
#

Eh

#

You need to assign the callback to the button for it to work

shrewd apex
#

no offense but this is what happens when u start of with no basics u stumble at every step

#

u changed the param to Interaction but in ur function u left it as ctx

#

so u will get ctx undefined error

#
button = discord.ui.Button()
button.callback = callback
naive briar
#

Change the button.callback by doing something like

button = discord.ui.Button(...)
button.callback = callback # your callback function

view.add_item(button)
#

What can I tell ya

#

Your button at line 123 is unused

#

And your button at line 137 has no callback function

feral lichen
#

this dude exenifix always in here man

naive briar
#

You need to assign the callback to it for it to work, but you're just creating a button and instantly adding it to the view without the callback

feral lichen
#

^

#

its jus this one dude thats an expert essentially at dpy and hes always helping in here for months lol

unkempt canyonBOT
#

Hey @dim geyser!

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

dim geyser
#

can someone help?

dim geyser
#
import os
from neuralintents import GenericAssistant

chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_model()

client = nextcord.Client()


@client.event
async def on_message(message):

    msg = message.author

    if msg == client.user:
        return

    if message.content.startswith("bot"):
        response = chatbot.request(message.content[2:])
        await message.channel.send(response)

client.run("#token")```
dim geyser
#

a chatbot

#

everything is fine until i get that error

#

for some reason

#

it tells me to install ntlk and i have absolutely no idea what that is

feral lichen
#

is it trying to respond with what is what i meant

#

the message or half or?

dim geyser
#

this is the whole thing

#

just two files

dim geyser
feral lichen
#

curious

dim geyser
#

yeah talk with them

#

also i got this when i debugged

feral lichen
#

uhhh idk man

dim geyser
#

its with chatbot.train_mode()

feral lichen
#

maybe try installing it ?

#

pip install nltk

#

and then import it but idek

dim geyser
slate swan
dim geyser
#

oh

naive briar
dim geyser
dim geyser
slate swan
#

now ```py
import nltk
nltk.download("omw-1.4")

naive briar
dim geyser
#

i should do that on the terminal?

feral lichen
naive briar
#

It's telling you in the error message ducky_beer

slate swan
#

then write these lines

#

else you can write it in a py file and run it

dim geyser
#

I LOVE YALL SO GODDAMN MUCH

#

MWAH

maiden fable
#

What's the error in console?

naive briar
paper sluice
naive briar
#

There's no event named button_callback

paper sluice
#

gfu

#

good for you

#

or u

maiden fable
#

Lmao

#

That was.... uh

naive briar
#

I'm gonna keep the screenshot of that

#

You just need to assign a callback to the button

#

I've explained it to you before

naive briar
shrewd apex
#

moment when thinking is our super power

naive briar
#

Check if the interaction.type is component

#

Like

if interaction.type.value != 3:
    return

Return if the type of interaction is not component

#

Idk if the on_interaction will affect your slash commands or not if you have one

vale wing
#

!d disnake.on_button_click

unkempt canyonBOT
vale wing
#

Ok only disnake has this

silk fulcrum
unkempt canyonBOT
#

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

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

Warning

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

New in version 2.0.
vale wing
#

Disnaek gud lib 🥵

naive briar
#

🫠

maiden fable
#

🫡

slate swan
#

disnake 💀

shrewd apex
#

well if u want an event so bad u can dispatch ur own custom event

#

but i don't see how having a button press event is more useful than interacting in callback

glad cradle
slate swan
jagged adder
#

How would i go about setting up an event or task that will go off at a set time? ie 12pm on x date, either using epoch or some such

mental hollow
#

https://paste.pythondiscord.com/hapijitoqa <— is my current snipe command code. My main error is when I delete any message in "server one" and then use the snipe command in "server two", the deleted message from server one displays in the response from snipe in server two. How can I limit this so it only shows deleted messages from the guild the snipe command is executed in? Also, can I optimise this code in any way? I feel like it’s quite unnecessarily long.

naive briar
#

That's a bunch of global variables

naive briar
mental hollow
naive briar
#

!dict

unkempt canyonBOT
#
Did you mean ...

» iterate-dict
» dictcomps
» dict-get

naive briar
#

But basically it's key-value database

slate swan
slate swan
jagged adder
naive briar
slate swan
#

it's not a database

naive briar
#

Maybe because I'm just bad at python

jagged adder
#

and yes, somewhat; im having issues filling in the gaps online tho, so i was seeing if anyone else had an idea

slate swan
#

I'll give you an example

#
from discord.ext import tasks
from datetime import datetime

@tasks.loop(time=datetime.fromtimestamp(123456789)) #epoch value
async def my_task() -> None:
  ...

my_task.start()

easy as that

jagged adder
#

so does the my_task.start() begin the loop process?

#

and keeps running it indefinitely

naive briar
#

Until you call task.cancel

#

Yeah

jagged adder
#
time=datetime.fromtimestamp(123456789)
``` is defined as an unexpected argument tho
naive briar
jagged adder
#

ill prob need to have an if in there

naive briar
jagged adder
#

ie if datetime.now() == x

naive briar
#

Ah, I misunderstood that

jagged adder
#

i can have it loop, but it needs to check if it equals the correct time at the point it loops

#

otherwise its kinda useless

silk fulcrum
#

yes, it won't

#

at least because Role can't be created like this

#

Role(id) is not a thing

#

also it's interaction.user

#

not interaction.author

#

no

#

!d nextcord.Guild.get_role

unkempt canyonBOT
silk fulcrum
#

no bruh

#

no bruh

#

first of all interaction.user

#

second it's not nextcord.get_role(id)

#

it's guild_object.get_role(id)

#

interaction.guild can be a guild object for example

#

🗿 you must be joking

#

bruh, idk how to explain that so you would understand

#

do you even know what are instances?

#

no?

#

So let's make an example:

class Apple:
    def __init__(self, *very_important_params) -> None:
        self.appleness: int = 100
        self.info = very_important_params

    def eat(*, full: bool = False):
        ...
``` This an `Apple` class right? Not an instance.
And now let's make an instance of this class:
```py
fresh_apple = Apple("very important param")``` So now, `fresh_apple` will be an instance of `Apple` class.
And so we can use it as we want with knowing that it has attrs and methods like `Apple` class, for example we can do `fresh_apple.eat(full=True)`
Here is an article about that: <https://towardsdatascience.com/practical-python-class-vs-instance-variables-431fd16430d>
#

@slate swan

polar scroll
#

how do i make it so it reads my token saved in another txt file?

silk fulcrum
#

config.py>>>>

#

.env>>>>>>>

polar scroll
#

It doesn't matter how, just wanna make my text safe ☠️

silk fulcrum
polar scroll
#

Ok, how exactly

silk fulcrum
polar scroll
#

ok, now i need to know about slash commands, i have been looking at learning them for a whole week, but i cant seem to undestand

polar scroll
#

discord-slash-command

silk fulcrum
polar scroll
#

its... a library..

#

that was created to help with slash commands

#

its not official ofc

silk fulcrum
#

Why not use a normal lib? Like discord.py, hikari, disnake, e.t.c

polar scroll
#

i am

#

im using .py

silk fulcrum
#

Then why do you need discord-slash-command?

polar scroll
#

following with that state, i cant seem to make slash commands, neither undestand the codes on yt tutorial

silk fulcrum
rare echo
#

-slash-command was for when discordpy wasn’t supporting

silk fulcrum
polar scroll
#

alright, so in .py... how do i make slash commands?

silk fulcrum
polar scroll
#

alr

silk fulcrum
#

Full code of this button's callback please

#

And I think code-blocks are better than ss here

rare echo
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

silk fulcrum
#

Where does this ctx come from? (line 143)

ionic edge
#
    await cursor.execute("INSERT INTO starboard (guild, channel) VALUES ($1, $2)",(context.guild.id,channel.id,))
sqlite3.IntegrityError: NOT NULL constraint failed: starboard.starLimit```
silk fulcrum
#

Most likely
It should give an error tho, if there is no ctx

ionic edge
#

am getting this error

#

CREATE TABLE IF NOT EXISTS `starboard`( `guild` INT(11) NOT NULL, `channel` INT(20) NOT NULL, `starLimit` INT(20) NOT NULL );

#
    @checks.not_blacklisted()
    async def set(self, context: Context, channel: discord.TextChannel) -> None:
        
        """
        Set the starboard channel.

        :param context: The hybrid command context.
        :param channel: The channel to set as the starboard channel.
        """
        connection = sqlite3.connect("database/database.db")
        cursor = connection.cursor()
        await cursor.execute("INSERT INTO starboard (guild, channel) VALUES ($1, $2)",(context.guild.id,channel.id,))
        cursor.commit()
        await context.send(f"Starboard channel set to {channel.mention}.")```
silk fulcrum
#

You are using pycord right?

#

Then I'm not sure what should you replace it to, search in docs what is a method to respond with an Interaction

tidal hawk
#

Just change the Interaction param to ctx xD

#

cursed tho

silk fulcrum
silk fulcrum
polar scroll
#

im getting a small error when doing

from dotenv import load_dotenv

load_dotenv()```

it highlights the word "dotenv" in "from dotenv" as an error, do i need to download it? also, how am i supposed to get my token in my .env file?
gusty shard
#

i want to make my bot give the users have x on their inv

{
    "875620201142562837": {
        "inv": {
            "blabla": 5
        },
        "has_x": true
    },
    "871068768254722129": {
        "inv": {
            "blabla": 5
        },
        "has_x": false
    }
}```
thats what values looks like
gusty shard
#

how can i make my bot add 1 to blabla every user who has x every hour

polar scroll
ionic edge
#
sqlite3.IntegrityError: NOT NULL constraint failed: starboard.starLimi```
#

CREATE TABLE IF NOT EXISTS `starboard`( `guild_id` INT(11) NOT NULL, `channel_id` INT(20) NOT NULL, `starLimit` INT(20) NOT NULL );

#

    @starboard.command()
    @checks.not_blacklisted()
    async def set(self, context: Context, channel: discord.TextChannel) -> None:
        """
        Set the starboard channel.

        :param context: The hybrid command context.
        :param channel: The channel to set as the starboard channel.
        """
        print(channel)
        print(context.guild.id)
        db_manager.set_starboard_channel(context.guild.id, channel.id)
        embed = discord.Embed(
            title="Starboard Channel Set",
            description=f"The starboard channel has been set to {channel.mention}",
            color=0x9C84EF
        )
        await context.send(embed=embed)```
#

set a starboard channel

#

it will store the channel and server id in the database

slate swan
#

How can I make it so that only the user who invoked the command can interact with the buttons

tidal hawk
#

Perhaps it gave you a error bcs you are making query without giving starLimit a value @ionic edge

#

And you specified that the value can't be null

polar scroll
#

whats a cog?

heavy folio
slate swan
#

help?

#
  File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1055, in on_connect
    await self.sync_commands()
  File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 657, in sync_commands
    app_cmds = await self.register_commands(
  File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 485, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(self._bot.user.id, guild_id)
  File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
maiden fable
#

Why do you have two bots defined in your file?

#

No

#

Remove the client variable

#

Whole traceback please

#

The whole error

#

It's known as a traceback, since it can trace back to the line which caused the error

#

!tracebacl

unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

maiden fable
#

Cool

slate swan
#
async def on_member_join(member):```

how do i make this for specific server?
ionic edge
#

which database ??

slate swan
#

What theme are you using?

#

Looked like the font is different for me

ionic edge
#

like ttgus only

slate swan
#

i mean its alredy enabled

#
async def on_member_join(member):```

how do i make this for specific server? discord.py
white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 499, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem\modules\mod\cog.py", line 196, in timeout
    if time < timedelta(days=28):
TypeError: '<' not supported between instances of 'datetime.datetime' and 'datetime.timedelta'```
silk fulcrum
silk fulcrum
#

Of course it is not printed, this callback is not attached to any button.
Seems like you removed button.callback = button_callback for some reason

#

It's the best docs out there imo

#

What is hard in reading them

#

You just need to know basic OOP

#

What yert

#

Oh yeah, you are trying to attach the callback before it is defined, you need to put that after your async def button_callback(...): func

silk fulcrum
#

if member.guild.id == my_guild_id: do stuff
@slate swan

slate swan
winged coral
#

It explains quite clearly in the parameters section

silk fulcrum
#

what is this yert

#

Like what do you want that line to do?

slate swan
silk fulcrum
#

Where do you think my_guild_id would be defined if you are trying to use it as a method bruh

winged coral
#

What? I literally can't explain in any more depth than the perfectly constructed explanation already does

silk fulcrum
#

That is definitely not how it works

slate swan
#
async def on_member_join(member):
    if member.guild.id == my_guild_id:```

like this?
winged coral
#

See the @ ? That signifies it's a decorator

#

You have not included a decorator

silk fulcrum
#

That was not a response to you

slate swan
winged coral
#

If you're too stupid to read the docs then you won't understand me either to be honest. The docs are very clear

#

You have two options, time-out for x or timeout until x

#

If you want for x, then use a timedelta

#

If you want until x, provide a datetime

silk fulcrum
winged coral
#

I've just explained your two options

slate swan
#

but i dont think its possible, with both bot command and bot event...

slate swan
#

i dont think i can combine bot event with bot command 😦

silk fulcrum
#

Just save what you want in DB or JSON and get that in an event

slate swan
#

the problem is i cant get databases to work and i arent familiar with JSON

silk fulcrum
slate swan
#

they. dont . work

silk fulcrum
rare echo
#

go to @novel apex then

#

dont just put it in chat

iron sorrel
#

how do we get all the members in a guild?

#

all the member ids in a guild? using api requests?

silk fulcrum
unkempt canyonBOT
silk fulcrum
#

oh, using api requests

iron sorrel
#

yes

torn sail
#

!d discord.Guild.fetch_members

rich geyser
#

hey

unkempt canyonBOT
#

async for ... in fetch_members(*, limit=1000, after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s members. In order to use this, [`Intents.members()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") must be enabled.

Note

This method is an API call. For general usage, consider [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members") instead.

New in version 1.3.

All parameters are optional.
iron sorrel
#

using api requests....

torn sail
iron sorrel
#

aiohttp

#

requests library even

torn sail
#

Ah lemme pull-up the docs

torn sail
iron sorrel
#

imma see that thanks

#

yk what my question is, how do user accounts get something which required privileged intents?

#

like when you scroll down on the right side here, it shows all the users,
but isnt it a privileged intent?

iron sorrel
#

what is a user bot?

silk fulcrum
#

selfbots ig

iron sorrel
#

selfbot?

torn sail
iron sorrel
#

thats impossible tho, when you put your token in the commands.Bot thing it says invalid token,,, i tried

#

😳

silk fulcrum
#

wtf 😳

torn sail
#

Yeah it’s now unsupported

silk fulcrum
#

oh i see

iron sorrel
#

my pea brain

#

gatekeeping operation?

torn sail
#

Gateway, like connect with a web socket to receive events and stuff

#

Well that’s not a great explanation

pliant gulch
#

I'm pretty sure the member list to the side of your client in the UX is a separate API used by actual users.
Sort of like how users have a search bar that uses it's own API vs a bot's search API (less powerful)

iron sorrel
#

may be

torn sail
#

I’ve seen a self bot library use it before

iron sorrel
#

library? selfbot what are you talking about

sick birch
#

You should be able to pull up the dev console on electron with a few tweaks to the files, and see the inbound and outbound requests to confirm that

iron sorrel
torn sail
#

I know the opcode for the get member sidebar list thing

iron sorrel
#

nothing here showing where the user data is actually coming from, right?

torn sail
#

But I’m just not gonna say it cause the rules here

iron sorrel
pliant gulch
#

Opcode 1 is heartbeat payload

iron sorrel
#

someone unironically called the ws heartbeats ping pong lol

pliant gulch
#

PING is an acryonym

wispy spade
iron sorrel
#

bytes bytes bytes, why is discord ws sending me like 10 packets every second?

#

what even is this shit 🤔🤔🤔🤔

pliant gulch
#

Just did a quick search, so this might be the member list to the side

slate swan
#

anyone know a good place to get examples from? (for example: moderation commands)

silk fulcrum
#

like RDanny

pliant gulch
#

I don't see it at all, mostly because that event is a DISPATCH Opcode

torn sail
#

Opcode 14

#

Is member sidebar list

pliant gulch
#

Opcode 14 is something else

torn sail
pliant gulch
#

I'm not reading the unoffical API docs I'm reading the data-mine

#

This was the one from the last 14 hours I think so this is pretty recent

pliant gulch
torn sail
#

Can you turn dms?

#

I was just about to send it

pliant gulch
#

Why not send it here?

torn sail
#

Cause won’t it break that rule

#

Cause self bots against tos

pliant gulch
#

I'm not sure how I'm selfbotting?

shell wing
#

can i make a cmd which bans a user and doesnt gets affected by the user changing there VPN..

pliant gulch
#

I didn't see any e.GUILD_MEMBER_LIST_UPDATE = 14 or whatever

torn sail
iron sorrel
#

ڮ:ҝ4ҍ4}÷ß

#

gotta love this

shell wing
#

send code

iron sorrel
gloomy sandal
#

I have a regular function that is called when i press 'p' on my keyboard, how do i make it so that my discord bot sends a message whenever I call that function. Im struggling because the .send() function has to be awaited and in an async function, but I cant call an async function when inside a normal function, asyncio.run() also doesnt work, throws an error

pliant gulch
#

I was thinking subscriptions in the sense of guild premium features

#

So that cleared up the confusion

feral frost
#

Type:
Timeout command

Code:

intents = discord.Intents.all()
bot.session = aiohttp.ClientSession()


async def timeout_user(*, user_id: int, guild_id: int, until):
    headers = {"Authorization": f"Bot {bot.http.token}"}
    url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
    timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
    json = {'communication_disabled_until': timeout}
    async with bot.session.patch(url, json=json, headers=headers) as session:
        if session.status in range(200, 299):
           return True
        return False


@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
    handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
    if handshake:
         return await ctx.send(f"Successfully timed out user for {until} minutes.")
    await ctx.send("Something went wrong")```

**Error:**
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Timeout context manager should be used inside a task
feral frost
#

?

iron sorrel
#

!code

unkempt canyonBOT
#

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.

feral frost
#

ok

feral frost
iron sorrel
#
warnings.filterwarnings("ignore", category=DeprecationWarning)
intents = discord.Intents.all()
bot.session = aiohttp.ClientSession()


async def timeout_user(*, user_id: int, guild_id: int, until):
    headers = {"Authorization": f"Bot {bot.http.token}"}
    url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
    timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
    json = {'communication_disabled_until': timeout}
    async with bot.session.patch(url, json=json, headers=headers) as session:
        if session.status in range(200, 299):
           return True
        return False


@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
    handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
    if handshake:
         return await ctx.send(f"Successfully timed out user for {until} minutes.")
    await ctx.send("Something went wrong")
pliant gulch
#

At face value this seems to work, but consider that create_task will schedule the task of start coroutine which does API connections etc, but it's still concurrent and non-blocking. Meaning get_channel is called before the bot's cache is populated

iron sorrel
#

why do you need to make web requests, isnt timeout supported in discord.py?

feral frost
#

idk i found this on internet

feral frost
#

it worked before

#

but not anymore

pliant gulch
iron sorrel
#
import asyncio as aio
import keyboard

bot = Bot()



async def main():
  aio.create_task(bot.start())
  await bot.wait_until_ready()
  channel = bot.get_channel(ID HERE)
  
  while True:
    if keyboard.getch() == "p":
      # or something idk
      await channel.send("hello")

aio.run(main())
#

this is just an example code tho

slate swan
#

!embed

#

guys i need help , how to create a message in embed

sick birch
#

interaction.user

silk fulcrum
#

interaction.user, not author, I told you about that.

feral frost
#

anyone knows a timeout command ?

slate swan
iron sorrel
# feral frost anyone knows a timeout command ?
import aiohttp
import discord
import datetime
import warnings
from discord.ext import commands

warnings.filterwarnings("ignore", category=DeprecationWarning)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=['$',], intents=intents)
bot.session = aiohttp.ClientSession()

@bot.event
async def on_ready():
    print(f"{bot.user.name} is ready to go!")

async def timeout_user(*, user_id: int, guild_id: int, until):
    headers = {"Authorization": f"Bot {bot.http.token}"}
    url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
    timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
    json = {'communication_disabled_until': timeout}
    async with bot.session.patch(url, json=json, headers=headers) as session:
        if session.status in range(200, 299):
           return True
        return False


@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
    handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
    if handshake:
         return await ctx.send(f"Successfully timed out user for {until} minutes.")
    await ctx.send("Something went wrong")

bot.run("BOT TOKEN")
silk fulcrum
#

well actually they are similar

shell wing
#

?tag embed

novel apexBOT
#

This is not a Modmail thread.

silk fulcrum
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
iron sorrel
#
em = discord.Embed(title="hello")
shell wing
#

ah yes that

slate swan
silk fulcrum
#

!d discord.ext.commands.Context.send

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

Sends a message to the destination with the content given.

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

For interaction based contexts this does one of the following...
silk fulcrum
#

embed kwarg

#

so .send(embed=your_embed)

slate swan
#

HI all, I'm trying to lock my reaction role embed down to messages the bot posts to (without the message id) but struggling on how to do this. I am not running into any errors, tracebacks so if anyone could advise be much appreciated 🙂

https://paste.pythondiscord.com/unahedixur code for the on raw reaction add event here.

gloomy sandal
#

i really hate this because discord likes doing events in response to other events, but when I want to send a message to a channel basically randomly (whenever i press a button), I have to go around a pile of obstacles

#

I wish i could have done this in js lol. however im stuck with python because i rely on it to do other things

silk fulcrum
feral frost
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Timeout context manager should be used inside a task

iron sorrel
#

why not just give moderators timeout permission lol

lime trench
#

WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 53.58 seconds
i haven't loaded up my bot in ages, it has 10 shards, why would i be receiving a rate-limit?
How could i fix it, i am using AutoShardedBot? I havent ran the bot in almost a week

maiden fable
slate swan
lime trench
maiden fable
#

are you doing too many await calls?

lime trench
#

i dumbed it down to ust starting up

#

i have one await call which is running the tkn

#
import asyncio
import logging
import discord
from discord.ext import commands

class bot(commands.AutoShardedBot):
    def __init__(self):
        super().__init__(
        command_prefix=commands.when_mentioned, 
        intents=discord.Intents(
            guilds=True,
            members=True,
            messages=True
        ),
        help_command=None)

async def startup():
    logging.info(f'Starting Up...')
    logging.info(f"Connected To {bot.user} with {len(bot.guilds)} servers")
    pass

bot = bot()

async def main():
    async with bot:
        bot.loop.create_task(startup())
        await bot.start('xxx', reconnect=True)

asyncio.run(main())```
#

do you see an issue here?

maiden fable
#

that is all yr bot.......?

vale wing
pliant gulch
#

So bot.user is None and bot.guilds will be an empty list

maiden fable
#

Ah, good catch with that

lime trench
#

oh, thank you

vale wing
#

That too

maiden fable
#

But that shouldn't be the cause of ratelimiting?

lime trench
#

yea..

pliant gulch
#

Oh I didn't see your above message about ratelimiting

maiden fable
#

Probably the lib is tryna cache too many guilds all of a sudden?

vale wing
#

Put it to on_ready cause why not

lime trench
#

no

maiden fable
#

That happened with my bot and I had to disable the caching

lime trench
#

im not using on_ready, thats terrible with dpy 2.0

pliant gulch
#

Can you show the ratelimit error?

lime trench
#

WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 54.05 seconds
WARNING:discord.gateway:WebSocket in shard ID 1 is ratelimited, waiting 49.15 seconds
WARNING:discord.gateway:WebSocket in shard ID 2 is ratelimited, waiting 48.28 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 46.46 seconds
WARNING:discord.gateway:WebSocket in shard ID 4 is ratelimited, waiting 48.83 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 49.14 seconds
WARNING:discord.gateway:WebSocket in shard ID 6 is ratelimited, waiting 48.92 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 46.61 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 48.04 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 48.24 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 48.67 seconds
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 1 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 11 is ratelimited, waiting 48.34 seconds
WARNING:discord.gateway:WebSocket in shard ID 2 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 12 is ratelimited, waiting 49.10 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 0.00 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 13 is ratelimited, waiting 48.39 seconds
WARNING:discord.gateway:WebSocket in shard ID 4 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 6 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 59.98 seconds

#

this is all it sends

vale wing
#

Gg

pliant gulch
#

How many guilds is this in?

lime trench
#

like 7k

pliant gulch
#

And do you disconnect from an error?

#

Or is it just warnings

lime trench
#

i believe

#

no, its just warnings

vale wing
#

Are there like heavy loading loops

lime trench
#

i dumbed it down to only the main.py file

pliant gulch
#

Okay it's fine to ignore it unless you are being disconnected. The wrapper is handling the ratelimits fine. Your getting these messages because discord.py does a GUILD_MEMBERS_CHUNK request everytime the bot is started up to populate member caches

#

You could pass an option to NOT CHUNK on startup which LOWERS your startup times but you will need to do custom chunking

#

Which is what I used to do

lime trench
#

hmmmm

pliant gulch
lime trench
#

yea

pliant gulch
#

I've written an example of that somewhere in this channel let me find it

#
bot = Bot(chunk_guilds_at_startup=False)
chunked: dict[int, tuple[discord.Guild, datetime.datetime]] = {}

@bot.event
async def on_message(message: discord.Message) -> None:
    if message.guild.chunked is False or message.guild.id not in chunked:
        chunked[message.guild.id] = message.guild, datetime.datetime.utcnow()
        await message.guild.chunk()

@tasks.loop(seconds=...)
async def check() -> None:
    for id, (guild, time) in chunked.items():
        if (datetime.datetime.utcnow() - time).seconds > 100:
            del chunked[id]
feral frost
lime trench
#

ok, thank you

pliant gulch
#

But honestly I wouldn't use that at all, not unless your start up times are way to long

#

Or if your being disconnected which you shouldn't be

maiden fable
#

Not interaction.user

#

@slate swan

slate swan
#

i've been getting the same error for days when a user interacts with a button. i've uninstalled py-cord and reinstalled it and removed any of the discord packages:
TypeError: TypedDict does not support instance and class checks

vocal snow
#

!sql injection

unkempt canyonBOT
#

SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
PEP-249 - A specification of how database libraries in Python should work

vocal snow
#

you have an extra pair of parentheses after send_message

hushed coral
#

How can I make a task loop so it sends a message every x amount of seconds

left idol
#

is it possible to check exactly when a user left the server?

zealous jay
#

I forgot how to check if the bot has permissions

#

use if instead of elif

#

you use elif in case you already have an if

#
if a == b:
  print('something')
elif a == c:
  print('something else')
else:
  print('idk')
#

@slate swan

sick birch
#

I don't know if it's that or on_member_remove

#

!d discord.on_member_remove

unkempt canyonBOT
#

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") leaves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

If the guild or member could not be found in the internal cache this event will not be called, you may use [`on_raw_member_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_member_remove "discord.on_raw_member_remove") instead.

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

you're right

errant coral
#

Anyone here know how to make classes/button with nextcord because i made so it send a embed after you click on a button and now i want to make a button in that embed that goes to another embed. Hard to explain

left idol