#discord-bots

1 messages ยท Page 35 of 1

tidal hawk
#

is there a way to bot see user email & guilds for period of time after authorizing the permissions on oauth2 once?

#

Like then the user doesn't have to authorize it for a month

white perch
#
    @discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="๐Ÿชจ")
    async def rock_callback(self, interaction, _button):
        if not self.interaction.user in self.players:```
#
AttributeError: 'RPS' object has no attribute 'interaction'```
silk fulcrum
#

just interaction

white perch
#

oh okay

silk fulcrum
#

you get it as an arg

#

its not class attr

white perch
#

Got it

#
AttributeError: 'Button' object has no attribute 'user'```
#

What's the interaction.user called

#

interaction.member?

silk fulcrum
#

change _button and interaction places

white perch
#

Ohh

silk fulcrum
#

i forgot

white perch
#

Tysm, now i'll work on completing the entire code of the command- the core is now complete!

silk fulcrum
#

congrats

white perch
# silk fulcrum congrats
    @discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="๐Ÿชจ")
    async def rock_callback(self, _button, interaction):
        if not interaction.user in self.players:
            return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(self.ctx.guild.id))))
        if interaction.user == self.ctx.author:
            if self.answer_1 == "":
                self.answer_1 = "rock"
                return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(self.ctx.guild.id))))
                if not self.answer_1 == "" and self.answer_2 == "":
                    rock_callback.disable
            else:
                return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: You already selected `{self.answer_1}`.", colour=discord.Colour(error(self.ctx.guild.id))))```
#

how do i disable a button?

#

i tried doing rock_callback.disable

silk fulcrum
#

nope

white perch
#

Didn't work

#

self.rock_callback.disabled = True

#

Is that right ๐Ÿค”

silk fulcrum
#

well so to disable a button you need to edit a whole message and change view

silk fulcrum
white perch
#

oh

#

so i'd need to edit interaction.message if i'm correct

silk fulcrum
#

View has children attr, which returns list of buttons the view has, well not only buttons, select menus and etc

#

so you do self.children[0].disabled = True

white perch
#

oh

silk fulcrum
#

and then await message.edit(embed=embed, view=self)

white perch
#

Or the command

white perch
#

oh wait i think i understood

silk fulcrum
#

it's the message with the view you send

#

your await ctx.send(embed=..., view=view)

limber bison
#

message_contant instance is imp for cogs and on_message right ?

white perch
#
if not view.answer_1 == "" and view.answer_2 == "":
    await message.edit(embed=embed, view=self)```
#

and before that line message = await ctx.send(my embed here)

#

And this will be in my rps command right

silk fulcrum
#

where do you want the button to disable?

white perch
#

wait self might not be defined there

silk fulcrum
#

@limber bison stop spamming commands

limber bison
#

!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.
white perch
#

basically when both parties select an answer, i want it to disable all buttons

limber bison
silk fulcrum
#

ok

#

oh my gosh, this'll need a big explain

white perch
#

yup ;-;

#

Wait a minute

white perch
silk fulcrum
#

what message

white perch
#

the first embed in the picture

silk fulcrum
#

oh wait yes, i forgot that there is an attr in interaction, well it's actually called different

#

oh no there isn't

#

im still extra dumb

#

its original_response

#

which will return your ephemeral message

#

which noone needs

white perch
#

oh

#

wait

swift pumice
#

code of conduct

white perch
silk fulcrum
#

ui

#

hehe

slate swan
#

discord.ui.View

silk fulcrum
#

also on_timeout is on timeout

white perch
#

Cheeeeers

silk fulcrum
#

not on both players done

white perch
#

i got it working

#

Now it disables all buttons :) once both parties select a button

white perch
silk fulcrum
#

view.message = await ctx.send(embed=..., view=view)

#

and then in callback self.message

white perch
#

oh

white perch
shell wing
#
@bot.command()
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
    if not member or time == 0:
        return
    elif reason == None:
        reason = 'no reason provided'
    try:
        if time[2] == "s":
            time_in_s = int(time[1])
        if time[2] == "min":
            time_in_s = int(time[1]) * 60
        if time[2] == "h":
            time_in_s = int(time[1]) * 60 * 60
        if time[2] == "d":
            time_in_s = int(time[1]) * 60 * 60 * 60
    except:
        time_in_s = 0

    await ctx.channel.purge(limit=1)
    await ctx.send("ok")
    await member.timeout(time_in_s)
    await asyncio.sleep(time_in_s)
    await ctx.send("done")
    return

Error

Traceback (most recent call last):
  File "D:\New folder\pythonProject\venv\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\New folder\pythonProject\main.py", line 52, in tempmute
    await member.timeout(time_in_s)
  File "D:\New folder\pythonProject\venv\lib\site-packages\discord\member.py", line 971, in timeout
    raise TypeError(f'expected None, datetime.datetime, or datetime.timedelta not {until.__class__!r}')
TypeError: expected None, datetime.datetime, or datetime.timedelta not <class 'int'>

The above exception was the direct cause of the following exception:```
upbeat gust
#

you need to pass a datetime or timedelta, not an int

shell wing
#

how do i pass datetime ?

upbeat gust
#

you create a timedelta object

#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
upbeat gust
#

you already have time_in_s

#

so create a timedelta with that many seconds

shell wing
#

I havent ever used datetime module as such...got 00 info sry

silk fulcrum
#

there is literally an example

#

of how to create a timdelta instance

shell wing
limber bison
#

What is instance ?

silk fulcrum
limber bison
#

Valued object

silk fulcrum
# limber bison What is instance ?
class Mama:  # this is class
    pass

yes = Mama() # this is an instance of class Mama
no = Mama() # this is also an instance of class Mama```
limber bison
#

Ohk k

shell wing
# silk fulcrum `timedelta(seconds=time_in_s)` is this that hard to figure out?

sryy

@bot.command()
async def tempmute(ctx, member: discord.Member, time=0, reason=None):
    delta = timedelta(
        days=50,
        seconds=27,
        microseconds=10,
        milliseconds=29000,
        minutes=5,
        hours=8,
        weeks=2
    )
    if not member or time == 0:
        return
    elif reason == None:
        reason = 'no reason provided'
    try:
        if time[2] == "s":
            time_in_s = int(time[1])
        if time[2] == "min":
            time_in_s = int(time[1]) * 60
        if time[2] == "h":
            time_in_s = int(time[1]) * 60 * 60
        if time[2] == "d":
            time_in_s = int(time[1]) * 60 * 60 * 60
    except:
        time_in_s = 0

    await ctx.channel.purge(limit=1)
    await ctx.send("ok")
    await member.timeout(timedelta(seconds=time_in_s))
    await asyncio.sleep(timedelta(seconds=time_in_s))
    await ctx.send("done")
    return
#

so like this right ?

silk fulcrum
#

noway....

vale wing
#

Professional copypaster

silk fulcrum
#

how can people be that... not smart

limber bison
#

Right ?

vale wing
vale wing
silk fulcrum
vale wing
#

You can call instance an object and vise versa

limber bison
#

My client is instance of discord.Bot class

#

Hahahahaha

vale wing
silk fulcrum
#

๐Ÿค“

vale wing
#

That regex too long

silk fulcrum
#

whocares

#

its smooth and nice

vale wing
#

Mine is too

silk fulcrum
#

no yours is weird

vale wing
#

Your problem

silk fulcrum
#

what is d4h2

shell wing
# vale wing Professional copypaster

no ๐Ÿ˜ญ mf ๐Ÿ˜ญ im hiding from my parents, and just came online to see this answer by them ๐Ÿ˜ญ so im not putting all my mind into it

vale wing
#

There's no such thing

silk fulcrum
#

until tomorrow at 3 PM isnt this just so smooth?

shell wing
vale wing
silk fulcrum
#

wohcraes

rugged shadow
#

wohcraes

shrewd apex
#

!pypi durations-nlp

unkempt canyonBOT
vale wing
#

Imagine not creating time conversion from scratch

silk fulcrum
shrewd apex
#

thats on pypi

#

just pip install

silk fulcrum
#

๐Ÿ˜ณ

shrewd apex
#

master32 thinking dirty

silk fulcrum
#

๐Ÿ—ฟ

shrewd apex
#

smooth criminal ;-;

white perch
#

Which database should i use for a message counter

#

any recommendations?

silk fulcrum
#

wdym message counter

white perch
#

like this

#

i had an old code from 2020 which did count messages in a json file which has worked till now with no issues (this bot is in only one dead server)

#

but the thing is for a large scale bot it wont work properly, i need a better database

#

every time someone sends a message it appends their msg count in a database

tidal hawk
#

is there any work around for adding callback to an url button?

#

Like if he clicks the button, he'll activate a function and then be redirected

silk fulcrum
tidal hawk
#

duck

white perch
#

Thanks

robust fulcrum
#

Guys how to fix this error

#
@bot.command()
async def leaderboard(ctx):
  leader = []
  conn = bot.db
  cur = await conn.cursor()
  
  for i in  cur.execute("""SELECT user, points FROM leaderboard ORDER BY points DESC"""):
    leader.append(str(i).replace(",", str("|")+str("                                    ")+str("|" )))

  leaderV = "\n".join(leader)
  await ctx.reply(f"~    ๐Ÿ‘ค**[Player]**๐Ÿ‘ค                                     ๐Ÿ’ฏ**[Score]**๐Ÿ’ฏ      ~\n **-----------------------------------------------------------------------------** ```{str(leaderV)}```")

Here is my code

silk fulcrum
#

cur.execute() doesn't return list right away

#

you need to fetch it somehow

robust fulcrum
#

Tupple?

silk fulcrum
#

not sure what db you use so can tell how

silk fulcrum
robust fulcrum
silk fulcrum
#

then it's await cursor.fetchall()

robust fulcrum
#

Where do I add it?

silk fulcrum
#

btw you can do this to make it shorter ```py

cur = await conn.execute("""SELECT user, points FROM leaderboard ORDER BY points DESC""")
rows = await cur.fetchall()

for i in rows:```

robust fulcrum
#

Oh k

white perch
#

are you using repl.it for hosting the bot permanently or just for testing rn- repl.it is dangerous for hosting discord bots

robust fulcrum
#

Ty for help

silk fulcrum
#

np

white perch
#

yes you

robust fulcrum
#

Not my code tho

#

That's my friends

white perch
#

oh whoevers it is if theyre using it to host then alert them ๐Ÿ’€

silk fulcrum
#

well repl.it is not that dangerous at least cus it's https. but it is bad as a host

white perch
#

No i meant

#

everyone has a shared ip

#

and if youre not using an env variable and directly use token in your code then your token is public

silk fulcrum
#

yeah

white perch
#

anyone can use your token and hence the bot to do anything they want

#

basically abusing permissions the bot has in any server

#
  • anyone else abusing the service on repl.it and gets ratelimited, your bot gets ratelimited as well because of shared ip
silk fulcrum
#

yeah btw I forgot that sqlite3 is not async so aiosqlite is better, but for beginning it doesnt really matter. I used sqlite3 for more then a year

white perch
white perch
#

aiosqlite is a server db?

#

and sqlite is local?

silk fulcrum
#

its async

heavy folio
silk fulcrum
#

mysql :)

heavy folio
#

sigh

robust fulcrum
#

Do we need to buy server for postgre?

silk fulcrum
robust fulcrum
#

Rent?

silk fulcrum
#

on your host

robust fulcrum
#

Sqlite is better then

silk fulcrum
#

probably

#

but i use postgr and idc

#

the only thing that scares me is my Mem

mossy jacinth
#

Hey! How can i make it so only the people with permissions with Administrator can see this? And also the guy who created the ticket?

vocal snow
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a โ€˜secretโ€™ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
vocal snow
#

overwrites kwarg

#

there's an example in the doc

silk fulcrum
#

btw people with admin perms should see the channel anyway

#

iirc

upbeat gust
dull terrace
#

Anyone else get frustrated that 99% of people don't use half of the features of your bot, usually the stuff that you think is the most fun and took the longest to code 7739monkathink

vale wing
unkempt canyonBOT
vale wing
#

The thing I can think of

upbeat gust
#

yeah

dull terrace
#

Must be a way to structure things to make people use it but want to 7739monkathink

silk fulcrum
#
like | this |
-----+------+
yes  | True |
no   | False|```
vale wing
#

Gigachad

silk fulcrum
#

โ˜„๏ธ

mossy jacinth
#

how can i make it so if the user presses a button it sends a message?

silk fulcrum
#

callback

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
mossy jacinth
#

How can i edit the message above to remove the right button when it was used? And how can i make it that only Admins can use it?

rugged shadow
#

PostgreSQL is free to setup

white perch
#

how to get all permission overrides in a channel

#

channel.permissions? whats it called

upbeat gust
#

!d discord.TextChannel.overwrites

unkempt canyonBOT
#

property overwrites```
Returns all of the channelโ€™s overwrites.

This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").

Changed in version 2.0: Overwrites can now be type-aware [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") in case of cache lookup failure
upbeat gust
mossy jacinth
upbeat gust
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
white perch
#

thx

#

and how to get guild.max_emojis allowed

#

similar to guild.max_members

silk fulcrum
#

not that easy(

white perch
#

oh

silk fulcrum
#

!d discord.Guild.emoji_limit

unkempt canyonBOT
white perch
#

oh thanks

#

And bots can add new stickers to the server? how that works

silk fulcrum
#

!d discord.Guild.create_sticker

unkempt canyonBOT
#

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

Creates a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") for the guild.

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

New in version 2.0.
white perch
#

Thanks

mossy jacinth
#

how can i disable a button after i click on it?

silk fulcrum
unkempt canyonBOT
silk fulcrum
#

get this button in the view, set disabled to True and do message.edit(view=updated_view)

#

you can get the button via view.children for example

robust fulcrum
rugged shadow
slate swan
#

How to get a user?

rugged shadow
slate swan
#

await client.fetch_user(id)?

silk fulcrum
unkempt canyonBOT
rugged shadow
#

^ that

silk fulcrum
slate swan
rugged shadow
rugged shadow
robust fulcrum
slate swan
# silk fulcrum this also

So can I dm them by doing this?

user = await bot.fetch_user(id)

await user.send(โ€œ. . . โ€œ)
```?
whole sparrow
#

Guys, how do I add description to each parameter of my slash commands?

slate swan
#

k ty

whole sparrow
#

disnake but they should be the same

silk fulcrum
#

not really

whole sparrow
rugged shadow
#

slash command implementations differ between forks

silk fulcrum
whole sparrow
#

yh app_commands don exist

#

in disnake

silk fulcrum
#

ig this

mossy jacinth
#

Sorry @silk fulcrum but I'm very confused, because the text I need to edit the buttons from is in another class, i dont know if i didnt understood u but i created another class with the buttons and disabled the one, but now i cant edit the embed... Sorry if its explained poorly

whole sparrow
#

tysm

whole sparrow
robust fulcrum
#

Guys like we can make a comand to run python code in dpy . Is there way to make a comand that can run js code?

silk fulcrum
robust fulcrum
#

Lazy to open ide

silk fulcrum
#

well technically it's possible, you just need js code interpreter and... idk... but it's 1000000 times harder than opening ide

#

it wont be just copy + paste

silk fulcrum
whole sparrow
#
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: InteractionTimedOut: Interaction took more than 3 seconds to be responded to. Please defer it using "interaction.response.defer" on the start of your command. Later you may send a response by editing the deferred message using "interaction.edit_original_message"
Note: This might also be caused by a misconfiguration in the components make sure you do not respond twice in case this is a component.
silk fulcrum
#

that's just... really weird idea

whole sparrow
#

Why is it giving me this error even though im responding within 3 seconds

silk fulcrum
#

just defer it

whole sparrow
#

should i be doing inter.response.send_message?

#

ive been doing inter.send

silk fulcrum
#

idk how disnake works, ig it's okay, just defer it

whole sparrow
#

aight

#

๐Ÿ’€ reason was i was running two bots at the same time

silk fulcrum
#

nice

vale wing
unkempt canyonBOT
#

JavaScript to Python Translator & JavaScript interpreter written in 100% pure Python.

maiden fable
#

So a basic python question here, but how to get the guild with most members?

rugged shadow
lime rampart
#

Hey so in the future is discord making it so that you can only user slash commands?

#

Your bot can't have your old regular message commands and then add on new commands as slash commands?

heavy folio
#

no, that is only for verified bots
unverified bots are not affected

green wraith
#

how do I create a button that when clicked the bot respond?

silk fulcrum
#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
maiden fable
silk fulcrum
green wraith
silk fulcrum
#

it'll help more than this page in docs

green wraith
#

ok

#

thanks again!

vale wing
vale wing
#

Just sharing knowledge

silk fulcrum
#

Just joking

shrewd apex
vale wing
#

What the hell

#

Just use max

shrewd apex
#

yeah max better here

vale wing
#

Sorting is expensive

slate swan
#

hi guys how can i retrieve the date a discord account was created when they join my server

shrewd apex
#

.created_at

#

...

#

what was that

silk fulcrum
unkempt canyonBOT
#

property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.created_at "discord.User.created_at")
slate swan
#

thanks

silk fulcrum
unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

slate swan
#

only needed the top one but appreciate it

silk fulcrum
#

ok

shrewd apex
#

32 flexing ๐Ÿ‘€

silk fulcrum
#

i just was confused by this

#

so provided both dates

slate swan
#

ah so basically just want to check that there account is over 30 days old when joining my server

shrewd apex
slate swan
#

if that makes sense

silk fulcrum
#

Asher is joke

shrewd apex
#

๐Ÿ’€

mossy jacinth
#

I still need help disabling a button after it got used
hope someone can help more than google and stack overflow

silk fulcrum
#

channek

mossy jacinth
silk fulcrum
mossy jacinth
silk fulcrum
shrewd apex
#

also if Google and stack cannot help you that's skill issue from your side :kek:

silk fulcrum
#

isnt that what you want?

mossy jacinth
#

no

silk fulcrum
shrewd apex
mossy jacinth
#

I want to disable the button only after it got pressed

shrewd apex
#

discord does that

#

till the response is processed

#

the buttons infact all other buttons are disabled

#

temporarily

mossy jacinth
#

๐Ÿ’€ I mean i want to make the button unusable after it got used, because now i can press it so often i want

rugged shadow
#

your ticket will be handled by darek 2

slate swan
#

import sys, subprocess, random, json, asyncio, os, time try: import colorama, pyfade, discord except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", 'colorama']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'pyfade']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'discord.py']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'discord']) from colorama import Fore from datetime import datetime from discord.ext import commands def error_msg(): print(pyfade.Fade.Horizontal(pyfade.Colors.purple_to_red, """Bruhhhh\nSeems like you\'re new to Python and/or JSON..\nJoin the Support-Server and lemme help you :)\n""")) time.sleep(10) input(f"{Fore.YELLOW}Press Enter to exit the script") raise SystemExit sys.tracebacklimit = 0 bot = discord.Client() with open("tokens.json", "r") as file: tokens = json.load(file) with open("alrdyusedtokens.json", "r") as file: tokenscheck = json.load(file)

#

AttributeError: module 'discord' has no attribute 'Client'

silk fulcrum
#

bot = Client ๐Ÿ˜ญ

green wraith
rugged shadow
silk fulcrum
rugged shadow
#

something's definitely overwriting discord

rugged shadow
slate swan
#

Yes i have already fixed

silk fulcrum
#

sorry

rugged shadow
#

that seems like a very unlikely situation @silk fulcrum

silk fulcrum
#

I thought you were responding to Iorran

rugged shadow
#

ah ic

rugged shadow
#

To install it, pip install git+https://github.com/Rapptz/discord.py

green wraith
silk fulcrum
#

my brain goes off when I'm eating a pie + making minesweeper command + helping people

green wraith
silk fulcrum
limber bison
#

If i change button lable at High speed will it rate limite ?

green wraith
#

how Do I create a Slash Commands?

slate swan
#

Hello, I'm coding a bot in python, I have a little problem, I'm coding a system that allows me to see if the user is in voice in my server, but it gives me this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'voice'
Can you help me?

green wraith
#

@silk fulcrum

cold sonnet
#

what's a SlashClient

#

oh it's from Ashley's gist

cold sonnet
#

can't delete the embed on my phone

scarlet aurora
#
ctx.voice_clients,``` this was deprecated to what ?
green wraith
limber bison
#

How can I build logic
If x is multiple of 100

#

If x%100 == 0 ?

#

!e
print(200%100)

unkempt canyonBOT
#

@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.

0
gleaming anvil
#

!d discord.ext.commands.Context.voice_client

unkempt canyonBOT
#

property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
maiden fable
slate swan
#

does anyone have cogs with subdirectory?

abstract kindle
#

Yo, is it possible to add a field at a specific row?

#

I don't think so from looking through the docs, but maybe i'm wrong

pulsar solstice
#

I am trying to make a currency bot in discord.py. I made it that it will store add 5 cookies everytime the user messages.

Now how can I make a jar command to check how many cookies does a user have?

#

here is my code

#
import discord
from discord.ext import commands
import json

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

@bot.event
async def on_ready():
    print("Bot is Now Online")


@bot.event
async def on_message(message):
    user_id = str(message.author.id)

    with open("jar.json", "r") as file:
        jar = json.load(file)
        
    if not user_id in jar:
        jar[user_id] = {}
        jar[user_id]["cookies"] = 0
    
    [user_id]["cookies"] += 5

    with open("jar.json", "w") as file:
        json.dump(jar, file)
    await bot.process_commands(message)

@bot.command()
async def jar(ctx):
    user_id = str(ctx.author.id)
    with open("jar.json", "r") as f:
        jar=json.load(f)
    cookie_amt=jar[user_id]["cookies"]
    await ctx.author.send(f"You have {cookie_amt} cookies in your jar.")

    
        

bot.run(token)
#
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 466, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 24, in on_message
    [user_id]["cookies"] += 5
TypeError: list indices must be integers or slices, not str```
green wraith
#

How do I count on how many servers my bot is on?

abstract kindle
#

right now it thinks user_id is just a list

pulsar solstice
limber bison
#

Does

button.label = values interaction.response.edit_message(view=self)

Has rate limit ?

vale wing
green wraith
#

thanks

vale wing
#

And yeah it needs to be awaited

rotund bloom
#

I have the following problem: I installed discord.py v 2 using pip install -U git+https://github.com/Rapptz/discord.py, but the code:

from discord.ext import commands, tasks
import discord
bot = commands.Bot()
@bot.slash_command(guild_ids=[id])
async def test(ctx):
  ctx.send("Test")
bot.run(token)
``` doesnt work... Can anybody help?My traceback is:

Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Snap\Final2\main-slash.py", line 28, in <module>
bot = commands.Bot()
TypeError: init() missing 1 required positional argument: 'command_prefix'

quaint epoch
#

bot = commands.Bot('!')

rotund bloom
# quaint epoch you need to give the bot a command prefix
Traceback (most recent call last):
  File "C:\Users\Admin\PycharmProjects\Snap\Final2\main-slash.py", line 473, in <module>
    @bot.slash_command(guild_ids=[cfg["guild_id"]])
AttributeError: 'Bot' object has no attribute 'slash_command'
quaint epoch
#

dpy smh

#

!d disnake.ext.commands.Bot.slash_command

unkempt canyonBOT
#

@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to the internal command list.
quaint epoch
#

disnake does though

rotund bloom
#

hm okay

vale wing
#

Dpy still has that ๐Ÿง

golden tapir
#

i want to dm a person that i warn but it dms me
how can i do this?

#
@bot.command(pass_context=True)
async def warn(ctx, user: discord.Member, role: discord.Role, why):
    guild = ctx.guild
    channel = guild.get_channel(1008388083508576367)
    await user.add_roles(role)
    await ctx.send(str(user) + " you have been warned for " + str(why))
    await channel.send(str(user) + " has been warned for " + str(why))
    await ctx.author.send("you have been warned for " + str(why))
quaint epoch
#

await user.send('this is a DM message')

golden tapir
#

ok

quaint epoch
#

!d discord.Member.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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

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. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with 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. **Specifying both parameters will lead to an exception**.
quaint epoch
#

also name your user var as member isntead

golden tapir
#

thx it worked

limber bison
#

If i edit button label at rate 100/sec will it able to hendil ?

slate swan
#

Im trying to grab questions from a .txt file everytime the user puts the command ?wyr. I tried using this code but it was not working? Could someone help me please @bot.command() async def wyr(ctx): with open ('wyr.txt'): await ctx.send(random.choice(wyr.txt()))

green wraith
vale wing
quaint epoch
vale wing
#

?

quaint epoch
vale wing
#

Amogus

quaint epoch
limber bison
vale wing
vale wing
clever dune
#

I need help pls

green wraith
#

what is the equal command of seeing the total servers only in the commands?

clever dune
#

Idk how to start the discord bot

#

Startup cmd

vale wing
clever dune
#

@vale wing can u help me?

green wraith
limber bison
vale wing
limber bison
#

Is interaction have more rate limit ?

slate swan
#

WHATTTT

vale wing
#

Most likely it means they have different ratelimit

limber bison
#

What's that, i think they didn't mention ๐Ÿ˜ณ

vale wing
#

Yeah it means that

#

Damn man sent a link and got banned

limber bison
#

Lol

vale wing
slate swan
#
@slash.slash(name="google", description="Search on google")
async def google(ctx, *, search):
    link = f"https:/letmegooglethat.com/?q={search}"
    await ctx.send(link)```
how to put several words ?
vale wing
#

Idk what that thing accepts tho

#

It might be URL encoded

slate swan
#

link = f"https:/letmegooglethat.com/?q={search}" "+".join(search.split())
like this?

sick birch
#

Might want to use urllib to urlencode the data

#

Instead of doing it manually

vale wing
#

!d urllib.parse.quote_plus use this

unkempt canyonBOT
#

urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)```
Like [`quote()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote "urllib.parse.quote"), but also replace spaces with plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in *safe*. It also does not have *safe* default to `'/'`.

Example: `quote_plus('/El Niรฑo/')` yields `'%2FEl+Ni%C3%B1o%2F'`.
slate swan
#

I just want to be able to search from my order

#

How can i make a counter for giveaway system?

limber bison
slate swan
limber bison
#

Which db u use ?

sick birch
limber bison
#

Ohh

#

Lol my mistake

clever dune
sick birch
clever dune
#

Can I invite to repl?

limber bison
#

Is buttons with edit label on every click is good idea ?

slate swan
#

๐Ÿ‘€

limber bison
#

Like count reaction

slate swan
vale wing
#

Then just put choice

vale wing
vale wing
# limber bison Like count reaction

For this case it's better to write count to some variable and periodically update the label, if too many people press it suddenly you are going to get ratelimited

limber bison
vocal snow
#

(interaction based)

limber bison
vale wing
vocal snow
#

Nah that's a different endpoint altogether

vale wing
#

How tho

vocal snow
#

Check in the Interaction responses section, you'll find the UPDATE_MESSAGE type

slate swan
vocal snow
vale wing
#

Ok

#

But still there are per-route ratelimits

limber bison
vale wing
#

for some reason discord doesn't tell what they are exactly

vocal snow
#

Discord will give an interaction for each click

limber bison
#

Conclusion lol ????

slate swan
#

how to get discord api ping?

green wraith
#

how do I create an economy command?

limber bison
vocal snow
slate swan
#

it is for the bot's latency

limber bison
vocal snow
#

If you use the normal Message.edit ep you can get ratelimited

green wraith
vale wing
limber bison
slate swan
vocal snow
#

You can only respond to an interaction once

vocal snow
green wraith
#

As I create a economy command, I've been looking for time and do not think

vocal snow
unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
green wraith
limber bison
green wraith
#

yes

limber bison
#

What ?

#

Economy ?

green wraith
#

I want to create an economy command

#

daily

#

pay

#

atm

limber bison
#

Use cogs @comands.commad with cooldown 24 h

#

@green wraith

cloud dawn
limber bison
#

Or it you want to automate it use task

green wraith
#

It's not that, I want to "create" an "economy" command containing daily, pay and atm

limber bison
#

What's its inputs ?

green wraith
#

it's like Loritta's command

cloud dawn
#

Who is Loritta

green wraith
#

an economy command is a command that when you write "<prefix>daily" you will earn a money, and to see the money earned have to use "<prefix>atm" to see the money. In case I want to pay any user I have to use " <prefix>pay." Did you understand?

green wraith
cloud dawn
slate swan
limber bison
gusty shard
#

how can i make my bot work for the people wo have mod role only

cloud dawn
#

Luc means prepared statements.

gusty shard
#

not like command

slate swan
gusty shard
#

the whole bot

cloud dawn
unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
gusty shard
#

i want to make whole bot unusable

#

isnt it possible?

green wraith
#

think you do not understand, I want to "know" how to create a python economy command, I do not know how to create

cloud dawn
gusty shard
#

..

limber bison
gusty shard
green wraith
gusty shard
#

its not that hard

slate swan
limber bison
gusty shard
#

do you know json?

green wraith
#

yes

cloud dawn
gusty shard
#

why

#

making economy bots with json is easier

limber bison
cloud dawn
gusty shard
#

wdym

green wraith
gusty shard
#

is it another language?

green wraith
gusty shard
green wraith
#

lol

cloud dawn
unkempt canyonBOT
#

bot_check(ctx)```
A special method that registers as a [`Bot.check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") check.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
cloud dawn
#

Works like cog_check

green wraith
#

do you know how to create an economic command?

gusty shard
#

that place is so weird

#

i do

#

but looks like i cant help you here

#

because its not a 'database'

limber bison
cloud dawn
regal pulsar
hot prawn
limber bison
regal pulsar
gusty shard
cloud dawn
#

Ight I'm going to the d.py discord.

slate swan
#

thatst jsut me tho

regal pulsar
limber bison
regal pulsar
unkempt canyonBOT
#

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

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

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

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
hot prawn
cloud dawn
limber bison
gusty shard
#

is there any way to make my bot work with two prefix

limber bison
#

It's db depended

gusty shard
#

and each prefix work for different command

gusty shard
#

for example ! for games and . for mod commands

vale wing
vale wing
scarlet widget
hushed galleon
slate swan
#

But it gives the error that there is no attribute called 'choice'

#

already did

hushed galleon
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
hushed galleon
#

random.choice() is a function provided by the random library, so you need to use it as random.choice(...)

#

... would be the list of lines you've read from the file

slate swan
gusty shard
#

how can i timeout people with my bot?

shrewd apex
unkempt canyonBOT
#

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

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

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
shrewd apex
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
hushed galleon
#

the specific usage of .timeout() depends on the library you're using

gusty shard
#

so what should i do

hushed galleon
#

ctrl+F for timeout( in the API Reference for whichever library you're using

slate swan
shrewd apex
#

pretty sure it all same for discord nextcord pycord and disnake i think๐Ÿ‘€

wise mulch
#

anyway to get message content via a reaction?

hushed galleon
gusty shard
#
@bot.command()
async def timeout(message: commands.Context, member: discord.Member, until: int):
    handshake = await timeout(user_id=member.id, guild_id=message.guild.id, until=until)
    if handshake:
         return await message.send(f"Successfully timed out user for {until} minutes.")
    await message.send("Bunu yapamam.")```
#

it that code ok?

hushed galleon
#

timeout() should be called from the member object

#

e.g. member.timeout(...)

#

its how you use any instance method like what you wrote, message.send()

gusty shard
#

alright

gusty shard
hushed galleon
gusty shard
#

idk

#

how can i see it

hushed galleon
#

run pip list in your terminal and look for a line starting with discord.py

shrewd apex
hushed galleon
#

sure

gusty shard
#

yep

#

its 1.7.3

hushed galleon
#

1.7's using a deprecated version of the discord gateway which doesnt have member timeouts

gusty shard
#

dang

#

but i can mute people with roles

#

cant i

shrewd apex
#

yes

#

tempmute

hushed galleon
#

temp muting someone is a bit more complicated to implement but you could

gusty shard
#

im sure i can make it

hushed galleon
# shrewd apex pretty sure it all same for discord nextcord pycord and disnake i think๐Ÿ‘€

Member.edit()
discord.py 2.0: timed_out_until = Optional[datetime.datetime]
pycord: communication_disabled_until = Optional[datetime.datetime]
disnake: timeout = Optional[Union[float, datetime.timedelta, datetime.datetime]]
nextcord: timeout = Optional[Union[datetime, timedelta] (yes, their doc is missing a closing bracket)

Member.timeout()
discord.py 2.0: timeout(until, /, *, reason=None)
pycord: timeout(until, *, reason=None)
disnake: timeout(*, duration=..., until=..., reason=None)
nextcord: timeout(timeout, *, reason=None)

other methods:
disnake: Guild.timeout(user, *, duration=..., until=..., reason=None)
pycord: Member.timeout_for(duration, *, reason=None)

hot prawn
#

How could I make a discord bot?

#

In python

shrewd apex
hot prawn
shrewd apex
hot prawn
#

UK?

shrewd apex
#

u know classes and async programming?

hot prawn
#

I know it's basics

deep osprey
#
@bot.command()
@commands.is_owner()
async def view(ctx,arg):
    with open(arg+'.txt', "r") as f:
        [await ctx.reply(line) for line in f.readlines()]``` why does this code send each line in a message?
shrewd apex
hot prawn
#

Hmm

hot prawn
#

Which is better Library

#

??

deep osprey
shrewd apex
# hot prawn Which is better Library

hikari for slightly advanced knowledge base for u i recommend dpy or disnake syntax mostly same u can just switch name between those 4 and be fine 99% of the time

shrewd apex
#

ignore capital my keyboard ๐Ÿ—ฟ

pulsar solstice
# green wraith and command count, how is it?

I am trying to make a currency bot in discord.py. I made it that it will store add 5 cookies everytime the user messages.

Now how can I make a jar command to check how many cookies does a user have?
here is my code

import discord
from discord.ext import commands
import json

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

@bot.event
async def on_ready():
    print("Bot is Now Online")


@bot.event
async def on_message(message):
    user_id = str(message.author.id)

    with open("jar.json", "r") as file:
        jar = json.load(file)
        
    if not user_id in jar:
        jar[user_id] = {}
        jar[user_id]["cookies"] = 0
    
    [user_id]["cookies"] += 5

    with open("jar.json", "w") as file:
        json.dump(jar, file)
    await bot.process_commands(message)

@bot.command()
async def jar(ctx):
    user_id = str(ctx.author.id)
    with open("jar.json", "r") as f:
        jar=json.load(f)
    cookie_amt=jar[user_id]["cookies"]
    await ctx.author.send(f"You have {cookie_amt} cookies in your jar.")

    
        

bot.run(token)```
shrewd apex
#

json database ๐Ÿ‘€

pulsar solstice
#

idk for some reason the jar command is not responding

#

no outputs

#

either

deep osprey
shrewd apex
#
@bot.command()
async def jar(CTX: commands.Context, user: discord.Member=None) -> None:
    member = user or CTX.author
    with open("jar.json") as f:
        data = json.load(f)
    await CTX.send(data[member.id]["cookies"])
pulsar solstice
#

ctx capital?

vocal snow
#

๐Ÿ˜ญ

shrewd apex
vocal snow
#

and the annotation is incorrect

shrewd apex
#

my keyboard...

#

autocorrect

hushed galleon
#

the annotation is fine from dpy's perspective

#

but 8ster's code appears to be valid anyway

#

id try adding a print statement on top of on_message to make sure its registering your message at least

shrewd apex
#

check json for cookies

vocal snow
#

it works but it should be Member | None

shrewd apex
#

added or not

pulsar solstice
gusty shard
#
import random
import asyncio
from time import sleep

at0, at1, at2, at3, at4 = 0, 0, 0, 0, 0
atlar = [at0, at1, at2, at3, at4]
while all(at < 5 for at in atlar):
    for i in range(5):
        sayi = random.randint(0,1)
        print("-" * atlar[0] + "๐ŸŽ",",", "-" * atlar[1]  + "๐ŸŽ",",", "-" * atlar[2] + "๐ŸŽ",",", "-" * atlar[3] + "๐ŸŽ",",", "-" * atlar[4]  + "๐ŸŽ")
        atlar[i] += sayi
        asyncio.sleep(delay=0.5)
winner = atlar.index(5)
print("winner is", atlar[winner]) # THAT'S NOT WORKING```
#

how can i make it print the winner at the end

pulsar solstice
pulsar solstice
shrewd apex
#

it was an example

#

jar[user_id]["cookie"] += 5

#

what's a cot?

scarlet widget
#

what does this error mean

shrewd apex
#

did u install

#

!pypi python-dotenv

unkempt canyonBOT
scarlet widget
#
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)
wise mulch
scarlet widget
wise mulch
spring flax
#

Can someone remind me which attribute of command returns the command arguments?

slate swan
#

.signature

shrewd apex
#

get_command_signature

slate swan
#

!d discord.ext.commands.Command.signature

unkempt canyonBOT
slate swan
#

you can also use Context

#

!d discord.ext.commands.Context.args

unkempt canyonBOT
spring flax
#

was looking for the signature, thanks

scarlet widget
#
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to Sparks Place! This bot was programmed by yours truly, Sparkpf#3258'
    )

client.run(TOKEN)

Why does it not send a dm to my alt when I Join?

slate swan
#

!d discord.Member.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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

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. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with 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. **Specifying both parameters will lead to an exception**.
spring flax
#

what's the obvious error here? ```py
for command in bot.commands:
help_text.append(f'{command.name}\n{command.doc}')
print(help_text)

mossy jacinth
#

I want to pin a message but this error came

msg = await interaction.send(embed=embed)

await msg.pin(reason="Handling")
vocal snow
spring flax
#

ah. I thought it would return the function doc

#

but I guess command.brief is for that

vocal snow
#

command.description would return that directly i think

#

would have to check source for that

slate swan
#

command.description searches for the description kwarg else it returns the docstring yes

slate swan
#

nor are responses

mossy jacinth
#

so i cant pin them?

slate swan
#

``@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")

return await ctx.respond(
    f"```Current Nitro Tokens Stock: {len(open('tokens.txt', encoding='utf-8').read().splitlines())}```")``

I want to make from f"```Current Nitro Tokens Stock: {len(open('tokens.txt', encoding='utf-8').read().splitlines())}```") An Embed, can someone help

#

....................................

mossy jacinth
#

shouldnt it be

embed = discord.Embed(title="", description="")
await ctx.send(embed=embed)

idk if im wrong, i use nextcord

limber bison
#

or a fun game ?

slate swan
mossy jacinth
#

maybe its like nextcord?
interaction.send(embed=embed)?

limber bison
#

i have json embed file how can i create embed vai python just puting json in code ?

slate swan
#

@slate swan Can you help

slate swan
#

Can u make that for me

slate swan
#

diy

slate swan
#

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

I have already tryed

#

Can u maybe make it, it will help me alot

silk fulcrum
#

no it wont

#

diy, no spoonfeed

slate swan
#

I dont ask you

silk fulcrum
slate swan
wise mulch
#

u need to add fields after instantiating the embed object

slate swan
#

Please behave properly with other members

#

How

wary shadow
#

Hello.

slate swan
silk fulcrum
#

Hi

slate swan
wary shadow
slate swan
#

stockVar = discord.Embed(title="Test", description="**Test*") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

#

``@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")

return await(
        stockVar = discord.Embed(title="Test", description="**Test*")
           stockVar.set_image(url="Test")
           await ctx.respond(embed=stockVar))``
wise mulch
slate swan
vocal snow
#

the syntax at the end is just wrong

slate swan
#

Lol

vocal snow
#

what are you trying to await there

slate swan
#

Idk

slate swan
#

Removed Await but still the same error

vocal snow
#

you can't just type stuff and expect it to work

slate swan
#

what

#

This discord is for help, and you guys dont help

#

ok nice

#

then stop asking for help here

#

No

#

Bro go away, your an so stupid

wary shadow
#

!shhh

unkempt canyonBOT
#

โœ… silenced current channel for 6 minute(s).

wary shadow
#

If you don't wish to assist someone then you are welcome to remain silent. Negative comments toward others without any offer of help are just not welcome. If someone doesn't know how to ask the question, you're all welcome to guide them but you are not welcome to bash them.

@slate swan Calling people names and telling them to stfu regardless of their actions is not going to fly here. I suggest you stop.

#

!unshush

#

!unhush

unkempt canyonBOT
#

โœ… unsilenced current channel.

wary shadow
#

Darn "s" rooDerp1

wise mulch
# slate swan No
embed=discord.Embed()
embed.add_field(name="undefined", value="undefined", inline=False)
await ctx.send(embed=embed)
slate swan
#

I need to add an field that says the stock

#

You know what i mean?

#

He needs to tell the lines of tokens.txt & count it x2

still swan
#

Hi, how i can fix that?...

slate swan
#

no wait multiple

still swan
slate swan
#

which lib is that

still swan
slate swan
#

re-sync the tree

slate swan
still swan
slate swan
# slate swan <@165958693689491456>

Get this error
File "/home/container/main.py", line 161 embed=discord.Embed() ^^^^^^^^^^^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

still swan
slate swan
slate swan
# still swan how

comment out all the slash commands, then run your code and sync, so that it syncs an empty tree and cleans off all the commands from the discord api corresponding to your bot, then uncomment all the commands and sync again

wise mulch
slate swan
#

Still get this error

wise mulch
limber bison
#

mysql vs postgresql / which is best for new ones ? new to realtional db ?

slate swan
#

``
@bot.slash_command(guild_ids=[settings["guildID"]], name="stock", description="Allows you to see the current stock.")
async def stock(ctx: discord.ApplicationContext):
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")

return(
    stockVar = discord.Embed(title="Test", description="**Test*")
           stockVar.set_image(url="Test")
           
            await ctx.send(embed=stockVar))

`` this is the code @wise mulch

wary shadow
slate swan
# still swan

What you are were actually doing is
return await(embed = discord.Embed() embed.set_image() await ctx.respond())
which simply doesnt make sense since you cannot assign variables while using a return statement and the await never even works outside the parentheses here. You have to create variables outside an await or return statement and only await the send method

slate swift
#
@client.command()
@commands.has_guild_permissions(ban_members=True)
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split("#")

    for ban_entry in banned_users:
        user = ban_entry.user
        
        if(user.name, user.discriminator) == (member.name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f"Successfully unbanned **{user.name}** !")```
slate swan
slate swift
#

can anyone help with that

scarlet widget
#
# bot.py
import os
import random

from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

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

@bot.command(name='rmsg')
async def nine_nine(ctx):
    choice_messages = [
        'You\'ve ran the random message command, this is a random message out of 5! (1/5)',
        'Hi? (2/5)',
        'Who are you? (3/5)',
        'ayo bro (4/5)'
        'I am bored (5/5)'
    ]

    response = random.choice(choice_messages)
    await ctx.send(response)

bot.run(TOKEN)

It says I'm missing intents on line 12, what do I do?

slate swan
#

Lucas ban PepeRain

#

@wise mulch

Now i get this error
if not isWhitelisted(ctx): ^ IndentationError: unindent does not match any outer indentation level

limber bison
#

mysql vs postgresql / which is best for new ones ? new to realtional db ? @silk fulcrum ?

slate swift
limber bison
slate swan
slate swan
slate swan
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

Okimii study Visual Basic for me peepocry

#

heck no, visual basic makes me wanna vomit๐Ÿ˜ญ

#

me too but exam

scarlet widget
# slate swan if you have recently switched to 2.0, then intents are now a required argument t...
# bot.py
import os
import random
import discord

from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

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

bot = commands.Bot(command_prefix='!')
client = discord.Client(intents=intents)

@bot.command(name='rmsg')
async def nine_nine(ctx):
    choice_messages = [
        'You\'ve ran the random message command, this is a random message out of 5! (1/5)',
        'Hi? (2/5)',
        'Who are you? (3/5)',
        'ayo bro (4/5)'
        'I am bored (5/5)'
    ]

    response = random.choice(choice_messages)
    await ctx.send(response)

bot.run(TOKEN)

like this?

slate swan
#

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

@wise mulch

#

I have fixed it, but now i need to make that it counts each line in tokens.txt & it wil send in the embed

wise mulch
silk fulcrum
#

lol degradation

scarlet widget
silk fulcrum
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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

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. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with 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. **Specifying both parameters will lead to an exception**.
silk fulcrum
#

embed kwarg

scarlet widget
#

I still don't get it

silk fulcrum
#

sad

scarlet widget
#

how do I make it send an embed

#

that doesn't explain how to send it

slate swan
#

for line in open("tokens.txt"): count += 1 varstock=discord.Embed(title="Tiqs | Stock") varstock.add_field(name="($count)", value="Count", inline=False)

But now i get in the embed ($count)

#

And not the count

silk fulcrum
#

wth is ($count)

#

PHP?

#

its just name=count

slate swan
#

Ok

#

But how can i get count += 1

#

In my embed

silk fulcrum
#

what

scarlet widget
#

Is there any tutorial that will explain embeds and not just send some code I don't understand

slate swan
# silk fulcrum its just `name=count`

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'count' referenced before assignment

silk fulcrum
slate swan
#

Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 992, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 358, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'count' referenced before assignment

slate swan
# silk fulcrum full exception

``async def stock(ctx: discord.ApplicationContext):
for line in open("tokens.txt"): count += 1
varstock=discord.Embed(title="Tiqs | Stock")
varstock.add_field(name=count, value="Count", inline=False)
if not isWhitelisted(ctx):
return ctx.respond("Only whitelisted users can use this command.")

if isWhitelisted(ctx):
    await ctx.send(embed=varstock)``
silk fulcrum
#

nah, im eating dinner, watching chess video and helping 2 people

whole sparrow
#

How do you error handle @commands.has_role()?

slate swan
whole sparrow
#

nvm

silk fulcrum
#

so just do count = 0 at the sturt of func

slate swan
#

Ok

silk fulcrum
whole sparrow
#

yup

#

I wish there was a way to hide slash commands for specific roles

#

like moderation commands

silk fulcrum
#

if for specific command:

@that_command.error
async def on_that_command_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        do_whatever```
#

if for all commands: the same but creating an event on_command_error

silk fulcrum
#

but i think so

#

idk, im not sure

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

b"py\n\nclass discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)\nRepresents a Discord embed.\n\nlen(x) Returns the total size of the embed. Useful for checking if it\xe2\x80\x99s within the 6000 character limit.\n\nbool(b) Returns whether the embed has any data set.\n\nNew in version 2.0.\n\nx == y Checks if two embeds are equal.\n\nNew in version 2.0..."

silk fulcrum
whole sparrow
silk fulcrum
#

lmao wtf is this

#

embed broke

lone lichen
#

Lmao

lone lichen
#

@silk fulcrum pop up the docs for checks

vocal snow
#

it won't hide the command

slate swan
#

@silk fulcrum How can i get like
varstock.add_field(name=None, value="Tiqs has", value=count, value="Server Boosts", inline=False)

silk fulcrum
silk fulcrum
#

stoooop spamming

slate swan
#

I dont spam lol

lone lichen
silk fulcrum
lone lichen
vocal snow
#

yeah but they wanted to hide it

silk fulcrum
#

but wont hise the command

slate swan
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

wary shadow
silk fulcrum
#

btw i think I saw the absolute similar bug today, but I didnt really realise it was wrong

slate swan
slate swan
#

wut

silk fulcrum
#

im stupid

#

nvm im just complete dumbass

vocal snow
#

tell us something we didn't know

#

๐Ÿ˜

slate swan
vocal snow
#

master did you see my awesome thnig i made

wary shadow
slate swan
#

count = 0 for line in open("tokens.txt"): count += 2 varstock=discord.Embed(title="Tiqs | Stock") varstock.add_field(name=None, value="Tiqs has {count} boosts", inline=False) varstock.set_thumbnail(url="https://cdn.discordapp.com/attachments/937356474210979860/1008267653565140992/925FBE55-A0A6-4105-942E-D26AC99F8CAB.gif")

#

Whats the problem

vocal snow
#

string literal needs to prefixed with f

silk fulcrum
slate swan
#

But how can i get count there?

lone lichen
silk fulcrum
#

you already got it

vocal snow
#

prefix the string literal with f

slate swan
#

OH

#

p_kek Stupid

vocal snow
#

you can achieve this by adding an f to the start (prefix) of the string

slate swan
#

i use uppercase F๐Ÿ˜ณ

silk fulcrum
#

๐Ÿ‡ซ

vocal snow
#

sociopathic qualities

slate swan
quaint epoch
#

i just got here

#

what

wise mulch
#

I'm getting a 403 forbidden error when attempting to add this user to the thread. I have admin perms for the bot. The users reacting to the message also have perms to change threads. The channel the messages are appearing in also allows threads to be created.

Think i fixed it by making the thread public.

@bot.event
async def on_reaction_add(reaction: nextcord.Reaction, user: nextcord.User):
    if reaction.emoji == 'โœ…' and not user.bot:
  await reaction.message.clear_reactions()
        await reaction.message.add_reaction('๐Ÿ‘')
        await reaction.message.edit(content=f'Approved by {user.mention}')
        message_content = reaction.message.content
        print(message_content)
    elif reaction.emoji == 'โŒ' and not user.bot:
        await reaction.message.clear_reactions()
        await reaction.message.add_reaction('โ›”')
        
        create_thread = await reaction.message.create_thread(name=f'Application was denied by {user.name}')
        for field in reaction.message.embeds:
            user_id = int(field.fields[0].value)
            
            user_to_add = reaction.message.guild.get_member(user_id)
            await create_thread.add_user(user_to_add)
            break
limber bison
#

if i put a message with a button (timeout = 1day) and after posting it i delete it , will it take my cpu ?

#

for remaining time ?

#

also for wait_fro ?

#

and how can i stop a button ?

#

on a massage ?