#discord-bots

1 messages · Page 96 of 1

slate swan
#

like this?

meager chasm
#

And if u want to change button then u can just do button.label = whatever and then interaction.response.edit_message(view=self)

#

What

#

Just use if statement

#

Much simpler

slate swan
#

@discord.ui.button(label="Claim", style=discord.ButtonStyle.grey)
async def my_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(view=self, check interaction.user.roles manage_messages=True)

#

its doing an error

meager chasm
#

Ya because that isn't even valid python

#

Do u know how to make if statement

slate swan
#

I dont think so

meager chasm
#

Bruh

slate swan
#

OH

split forge
#

now I have a code called round_id = str(round_id) and I want it to write the round id in this code in my bot how can I do it
example .help
When [round_id] is entered, I want the round id we entered to appear at the bottom of the Embed.

slate swan
#

statement

split forge
#

help

slate swan
#

let me check what thats means

#

@meager chasm yes i do know

marble ocean
#

can anyone halp me?

#

help*

meager chasm
marble ocean
#

I am trying to maske a bot that trade stocks with discord messages but it says me that "discord.ext.commands.errors.CommandNotFound: Command "Buy" is not found"

import alpaca_trade_api as tradeapi
import discord from discord.ext import commands

ALPACA_BASE_URL = "https://paper-api.alpaca.markets";

class bot(commands.Cog) :

def init(self, client):
self.alpaca = tradeapi.REST("<>","<>")
self.client = client

@commands.command()
async def Buy(self, ctx):
await self.alpaca.submit_order("BTC", 1, 'buy', 'market', 'day')
#await bot.wait_for("message")
#msg = ctx.message.content

@commands.command()
async def Sell(self,ctx,msg):
#msg = ctx.message.content
await self.alpaca.submit_order("MSFT", 1, 'sell', 'market', 'day')
def setup(client): client.add_cog(bot(client))

slate swan
#

that's not even valid but ok.

meager chasm
#

And can u use !paste for code

#

So we can see da indentation

marble ocean
#

!I am trying to maske a bot that trade stocks with discord messages but it says me that "discord.ext.commands.errors.CommandNotFound: Command "Buy" is not found"

import alpaca_trade_api as tradeapi
import discord from discord.ext import commands

ALPACA_BASE_URL = "https://paper-api.alpaca.markets";

class bot(commands.Cog) :

def init(self, client):
self.alpaca = tradeapi.REST("<>","<>")
self.client = client

@commands.command()
async def Buy(self, ctx):
await self.alpaca.submit_order("BTC", 1, 'buy', 'market', 'day')
#await bot.wait_for("message")
#msg = ctx.message.content

@commands.command()
async def Sell(self,ctx,msg):
#msg = ctx.message.content
await self.alpaca.submit_order("MSFT", 1, 'sell', 'market', 'day')
def setup(client): client.add_cog(bot(client))

slate swan
#

indentations usually mess up while copy pasting, a screenshot is bettter

#

stop spamming.

marble ocean
#

im not spaming

meager chasm
#

!code

#

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

meager chasm
#

Use this to send ur code

marble ocean
meager chasm
#

Why is _init_ and both commands not in cog class

marble ocean
meager chasm
#

But how r u loading this extension file

hushed galleon
marble ocean
hushed galleon
marble ocean
#

how do i know?

brazen raft
#
from discord import version_info
print(version_info())
hushed galleon
#

depends on how you installed discord.py in the first place

brazen raft
#

Or you can do pip freeze (or py -m pip freeze/python3 -m pip freeze) depending on how you installed it

marble ocean
brazen raft
#

Ye, never mind, just print it

#

Without the parentheses after version_info

slate swan
#

discord.__version__.

brazen raft
rare echo
#

how do you just cancel a slash cmd from timing out

slate swan
hushed galleon
#

discord gives you 3 seconds to initially respond, if you need more time you can use the Interaction.defer(thinking=True) method and then follow up later

rare echo
slate swan
#

it's just an example smh

#

it's just to demonstrate how a method works

#

yeah but it’s unnecessary as the thinking parameter is pretty much a sleep already

#

...?

#

your sleeping the function itself tho lol and no code in the cmd would be executed

keen dust
#

Hi, I tried using hybrid commands and it doesn't seem to work

slate swan
#

yea and you listed as an example so ppl will follow that example.

keen dust
#

heres my code

keen dust
#

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix="$", intents=intents)

    async def setup_hook(self):
        await self.tree.sync()
        print("synced")

    async def on_command_error(self, ctx, error):
        await ctx.reply(error, ephemeral=True)

@bot.hybrid_command(name="meme")
async def meme(ctx):
    
    meme_url = "https://some-random-api.ml/meme"
    async with request("GET", meme_url, headers={}) as response:
        if response.status == 200:
            data = await response.json()
            meme_link = data["image"]
            meme_embed = discord.Embed(title="Meme", color=0x2ecc71)

            if meme_url is not None:
                meme_embed.set_image(url=meme_link)
            
            await ctx.channel.send(embed=meme_embed)
            

        else:
            print("Error")

slate swan
#

while inviting the bot to your server

keen dust
slate swan
keen dust
#

yes

#

its all the same

slate swan
#

can you print self.tree.sync() ?

keen dust
#

sure

#

gimme a sec

slate swan
keen dust
marble ocean
keen dust
#

'Bot.setup_hook' was never awaited

#

I might be printing it out wrong

brazen raft
slate swan
split forge
keen dust
#

ye I'll try it

brazen raft
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.

split forge
#

thanks

#

any one can help me?

faint sapphire
#

is it possible to make a venv on a VPS like vultr
I wanna add 2 bots to a 2.50$ package (10 Gb space and 500Gb bandwith)

faint sapphire
#

yes

shrewd apex
#

yeah all peace then

faint sapphire
#

nice thanks

shrewd apex
#

u can easily make venv and stuff

shrewd apex
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

brazen raft
marble ocean
slate swan
faint sapphire
#

nice thanks

faint sapphire
#

and everything will work

quaint epoch
faint sapphire
marble ocean
faint sapphire
#

😐

marble ocean
marble ocean
rustic onyx
#

Yessir susge

rustic onyx
marble ocean
rustic onyx
#

thats the traceback error

#

I stopped using d.py a while ago, but if I'm not wrong, you should pass the name argument

#

so it would be something like
@commands.command(name = "alpaca_buy")

slate swan
rustic onyx
#

what is his function name is repeated.

#

not the case, but...

#

also, are you calling the setup function, I think if you dont do so, cogs wont be added to your main file

devout cape
#

when we do the discord code formatting like "```py" or ```js to force the syntax highlighting, what are those labels called and is there a way for me to browse what other formats are available.

rustic onyx
#

I load them in a somewhat different way

rustic onyx
devout cape
#

i mean the labels that can be used after the triple backtick

#

like "py" "js" "diff" etc, i wonder what is included in etc

primal token
rustic onyx
#

markdown like in github?

devout cape
#

yes but you can declare which language to use for syntax highlighting, i want to know all the possible declarations

primal token
primal token
rustic onyx
devout cape
#

yes is that list of languages browsable anywhere

#

correct that is my question

rustic onyx
#

I think like all the available file extensions?

devout cape
#

perfect, thank you very much.

primal token
devout cape
#

aw that is very helpful

warm thunder
#

Is it possible to ban a player who was not on the server or left the server using his id, for example, from another server?

rustic onyx
warm thunder
silk fulcrum
#

Guild.ban requires a Snowlake

honest shoal
#

snowlake

silk fulcrum
#

so for example this would work:
await guild.ban(discord.Object(user_who_is_not_on_the_server_id))

silk fulcrum
honest shoal
#

oh

silk fulcrum
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

it was also known as hackban

silk fulcrum
#

@warm thunder

rustic onyx
#

oooh

warm thunder
#

got it

devout cape
#

When the python discord bot replies to people it looks like it uses the markdown Callouts that start with an emoji in a block quote.
I'm looking at the markdown docs at https://rdmd.readme.io/docs/callouts and I'm seeing that you can make your own Callout themes with some custom css and then display those custom Callouts with the emoji designated in the css.

Can you use the css in a discord message or is there an equivalent way that the python bot in this server makes custom Callouts?

#

I might also just be wrong about the python bot using callouts.

sick birch
#

Do @unkempt canyon emojis look different?

devout cape
#

I think maybe I just misunderstood some of the bot replies i remember seeing.

sick birch
#

Do you have an example?

glad cradle
#

I think he means embeds?

sick birch
#

Or do you remember the command?

devout cape
#

I cant find any specific examples, i just remember being impressed with the formatting of the bot replies and I thought that Callouts might be the source of the fancy formatting.

sick birch
#

!src

unkempt canyonBOT
devout cape
#

awesome, this will sort it out, thank you.

sick birch
#

You can check out the source if you want but it’s all just regular markdown

devout cape
#

even if it doesnt answer my question it will answer the question I should have been asking anyway. that was what I needed, thanks.

hushed galleon
#

if this was the immediate cause of your issue you should have seen a RuntimeWarning: coroutine 'load_extension' was never awaited message

slate swan
#

whats the command for reaction roles?

sick birch
#

there is no command for it

#

you'll have to build it using existing ones

slate swan
#

oof

#

okay ty

slate swan
#

Hey!

Im making a bot with slash commands (pycord)

How would i get options like this?

slate swan
steep river
#

Can anyone help me with detecting threads created on a message? I'm trying to delete both the message and the thread (if exists) in my code. I've dug through the documents and the closest thing I can find is the "parent id" for the thread

glad cradle
slate swan
glad cradle
#

disnake / dpy

slate swan
#

how would you do it there

#

ive done a bit of disnake

glad cradle
#

in disnake there's disnake.ext.commands.Param where you can pass a kwarg called choices

slate swan
#

pycord and dpy are very simular

glad cradle
#

!d disnake.ext.commands.Param

unkempt canyonBOT
#
disnake.ext.commands.Param(default=Ellipsis, *, name=None, description=None, choices=None, converter=None, convert_defaults=False, autocomplete=None, channel_types=None, lt=None, ...)```
A special function that creates an instance of [`ParamInfo`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.ParamInfo "disnake.ext.commands.ParamInfo") that contains some information about a slash command option. This instance should be assigned to a parameter of a function representing your slash command.

See [Parameters](https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#param-syntax) for more info.
glad cradle
#

you would use this like

@bot.slash_command()
async def my_sus_cmd(inter, choices: str = commands.Param(...))
steep river
slate swan
mental hollow
#

how can I create and define a aiohttp session in my bot subclass using the recommended way (async)?

slate swan
#

is one way

slate swan
#
  File "C:\Users\Eclipse\Desktop\Discord Bots\Eclipse's Utilities\main.py", line 6, in <module>
    from discord.ext.flags import Intents
ImportError: cannot import name 'Intents' from 'discord.ext.flags' (C:\Users\Eclipse\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\flags\__init__.py)``` I keep getting this error an I dunno how else to import Intents
sick birch
#

Or just don't import it at all

#

Instead use discord.Intents

slate swan
slate swan
primal token
primal token
slate swan
#

idfk thats what worked for me

primal token
#

It doesnt work lol

#

you ment discord.Intents.all() not discord.Intents().all()?

sick birch
# slate swan

You may already have a file/folder called discord, or some other type of shadow/clash

wispy spade
unkempt canyonBOT
#

disnake/flags.py line 923

self = cls.__new__(cls)```
primal token
#

it's disnake but I'm quite sure discord.py has the same abstractions

wispy spade
#

It should still be able to create an instance regardless.

#

and yes dpy does share the same abstraction

primal token
wispy spade
#

it doesn't

>>> import discord
>>> discord.Intents.all()
<Intents value=3276799>
>>> discord.Intents().all()
<Intents value=3276799>
#

maybe your type checker will complain but it should still work

primal token
unkempt canyonBOT
#

discord/flags.py line 661

def all(cls: Type[Intents]) -> Intents:```
torn sail
primal token
unkempt canyonBOT
#

@primal token :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: object.__new__(X): X is not a type object (A)
primal token
#

Am i having confusing myself or?

wispy spade
#

__new__ should receive the class rather than the instance there

torn sail
#

!e

class A:
    @classmethod
    def method(cls):
        cls.__new__(cls)

a = A()
a.method()
unkempt canyonBOT
#

@torn sail :warning: Your 3.11 eval job has completed with return code 0.

[No output]
torn sail
#

staticmethods can also be called from instances i think

primal token
#

yeah

primal token
#

This is confusing me allot

torn sail
#

the class is passed in, not the instance

#

as cls

primal token
torn sail
#

!e

class A:
    @classmethod
    def method(cls):
        print(cls)
        cls.__new__(cls)

a = A()
a.method()
#

!e

class A:
    @classmethod
    def method(cls):
        print(cls, type(cls))
        cls.__new__(cls)

a = A()
a.method()
unkempt canyonBOT
#

@torn sail :white_check_mark: Your 3.11 eval job has completed with return code 0.

<class '__main__.A'> <class 'type'>
primal token
#

That's some odd behavior

#

It converts the instance to the class object

kind trellis
hot cobalt
#

It passes in the class instead of the instance

primal token
hot cobalt
#

What do mean by that?

primal token
#

e.g

foo.bar()

foo would be an instance of Foo it's like doing

Foo.bar(foo)

my point is, the instance given within methods which when passed the local variable would be called self, in a class method when using it on an instance it actually doesnt pass the current instance, but the polymorphic object it came from

#

It's odd to me

hot cobalt
#

Well it does pass the instance

#

Just not to method

#

The instance is passed to the wrapper function returned by the classmethod decorator

#

Which then grabs the class from that, and passes that to the method

#
def my_classmethod(method):
    def wrapper(*args, **kwargs):
        return method(args[0].__class__, *args[1:], **kwargs)
    return wrapper
#

It'd look something along those lines

#

!e

def my_classmethod(method):
    def wrapper(*args, **kwargs):
        return method(args[0].__class__, *args[1:], **kwargs)
    return wrapper

class Test:
    @my_classmethod
    def method(cls, var):
        print(cls)
        print(var)

a = Test()
a.method(10)
unkempt canyonBOT
#

@hot cobalt :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <class '__main__.Test'>
002 | 10
primal token
#

Yep, like i said, it's kinda still odd to see

robust fulcrum
#

Guys is there any way to check that a user has voted my bot on top.gg?
Like an api that sends response fastly and my bot knows?

wary shadow
robust fulcrum
wary shadow
robust fulcrum
wary shadow
#

I didn't completely read the docs.

slate swan
#

how do i run the vsc code?

#

its for a discord bot im making

rare echo
rare echo
slate swan
#

the main file?

rare echo
#

yes

primal token
rare echo
slate swan
primal token
slate swan
#

im staying up all night tonight

primal token
slate swan
#

im better off not going to bed

rare echo
slate swan
#

woops

slate swan
primal token
rare echo
#

not as a whole

slate swan
#

thats the gui

primal token
slate swan
# slate swan

and im finding trouble runnning it, and i dont know how to select the startup file

rare echo
#

i can’t tell if i’m missing something or if you’re a stickler for correct naming

slate swan
#

help

#

please

primal token
rare echo
primal token
#

You mean a run button?

slate swan
#

can someone help me on how atleast use visual studio?

#

on how to run the discord bot

primal token
slate swan
primal token
#

I'm pretty sure VS isnt beginner friendly

slate swan
#

im using

rare echo
slate swan
#

since i have it

rare echo
slate swan
#

can i run the bot easier?

primal token
#

VS is the fully featured version of VSC, if you want a lightweight feel i would use VSC

#

do know VSC isnt that lightweight compared to others like vim or sublime text

primal token
#

nano😏

rare echo
primal token
#

use Microsoft word👀

rare echo
primal token
#

it's lovely

slate swan
#

VSC is a general purpose open-source code editor that you can customize with extensions

#

They are different

ivory wraith
#

First time using discord.py's slash commands, and the sync function doesn't seem to be working for me.
What's the problem here?

@bot.command(name="sync")
async def sync(ctx):
    await discord.app_commands.CommandTree.sync()

Error:

TypeError: CommandTree.sync() missing 1 required positional argument: 'self'
#

(ping when responding!)

slate swan
#

how can i get a discord module

slate swan
unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
slate swan
#

you have to use client.tree.sync()

#

wait hold on i think you have to assign it manually

#

basically, you need an instance of CommandTree to work with

#

uh

#

use python -m pip install discord.py

#

that goes into your terminal

#

not into the python repl

#

man im confused asf

#

its my first time coding

#

ever

#

then starting with discord.py is the wrong thing to do, you kind of need experience with python

#

you can start with learning python basics if you want

#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

im trying to finish the bot, then i might go into python basics

#

that's not how that works

#

🤷‍♂️

#

i can't help you if you don't understand what i'm saying

primal token
#

You also need to learn a few paradigms before using the library

slate swan
#

can i ask why you're building a discord bot?

ivory wraith
slate swan
#

thats why

#

unsolicited but sure

#

i mean again i can't help you because you have no exposure to the terminology we use

#

nvm

#

i did it

slate swan
#

here's an example for how to use the app_commands package. ask away if you have any questions.

primal token
slate swan
#

i mean not really

#

typing into the console and the python repl are two different things

#

knowing that terminology helps

primal token
#

I wasnt personally referring to that, maybe we arent at the same page

slate swan
#

please refer me to your page

primal token
#

I took terminology as in the paradigms used in Discord.py but it wouldnt fit in this context as you were referring to concepts like a terminal

slate swan
#

it's clear who and what i was talking about

#

hi preocts sorry i'll stop the ot discussion

wary shadow
#

@primal token and @slate swan , it seems that you two are frequently having a debate over the pedantic meaning of a statement. Could you tone it down a touch?

primal token
#

sure

slate swan
#

sorry noid, it's really not personal lol

#

i'm pedantic in nature i think

steep river
#

Can anybody help me with closing/deleting/completely removing a thread whenever the message it was tied to is deleted? I'm using discordpy. Am I missing something obvious?

primal token
ivory wraith
# slate swan here's an example for how to use the `app_commands` package. ask away if you hav...

this is included in that example

# In this basic example, we just synchronize the app commands to one guild.
    # Instead of specifying a guild to every command, we copy over our global commands instead.
    # By doing so, we don't have to wait up to an hour until they are shown to the end-user.
    async def setup_hook(self):
        # This copies the global commands over to your guild.
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

do I need to copy the global commands over to a specific guild to use them?

primal token
slate swan
#

it's discord.ext, not .exe

slate swan
slate swan
wary shadow
#

I'm glad you two aren't holding any stronger emotions at each other. To clarify why I step in; there is a vague line between being constructive and battling out smallest nits. One keeps the conversations flowing, the other tends drown out other conversation. :)
((ot would be a fine place to have a strong convo like that though))

slate swan
primal token
slate swan
#

no, you don't have to sync them to be able to use them, it's just way faster.

slate swan
primal token
#

That makes me question why global commands took hours to register before, while now it's instant

#

seems like a implementation that was done rushed or at 3am🐧

slate swan
#

hm is this mentioned in the docs?

#

i haven't read the changelogs in a while lol

primal token
#

thats where i found out personally as no news as i can remember where given

slate swan
#

oh ic

#

interesting, discord devs are still discord devs lol

#

no change whatsoever in their wonky ways

primal token
#

i read that as "monky ways"

#

🙊

slate swan
#

we can't stay on topic for more than a minute lol

#

alr cya 👋

primal token
#

kek, later✌️

pulsar bridge
#

ent

slate swan
#

when someone dcs from the channel check if its empty, create a task to delete in ten mins if nobody is in it still

feral lichen
slate swan
#

how would i check if the channel is vacant

#

or how owuld i check a category

feral lichen
#

or make a event like time.now and annother time event and within those 10 minutes if anyone joins dont delete

feral lichen
slate swan
#

how would i check a category witht he vcs and if a channel is vacant it deletes it

feral lichen
#

ig before?

slate swan
#

?

#

wym

unkempt canyonBOT
#

@little vector, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

little vector
#

oml

feral lichen
#

idk ig u can do like a while loop seeing if theyre in vc whilst the timer is running like ```py

#timer

a = True

you can make a var = true whilst bot timer is not done yet

while a == True:
check

#timer done

a = False

little vector
#

Trying to screenshot then send to a webhook, heres my current code.
`import pyautogui
from discord_webhook import DiscordWebhook
while True:
image = pyautogui.screenshot()

webhook = DiscordWebhook(url='example', username="deflationz")

'''webhook.add_file(file=f.read(), filename='hit.jpg')'''
webhook.add_file(image, filename='hit.jpg')

response = webhook.execute()`
feral lichen
#

no clue

slate swan
feral lichen
#

.

slate swan
#

or how could i make the bot delete all the channels in that category after a day or so

feral lichen
#

probably get the id and see what category its in with checking the properties 🤦

#

id is also equal to channel

#

u can do this to get the properties ```py

channel = bot.get_channel(id)

print(channel)

#

im pretty sure u can do that

slate swan
feral lichen
#

wouldnt know, i havent rlly messed around with vc channels in dpy, and i dont want to mess up your work lol

slate swan
#

lol

slate swan
#

new.set_permissions(publicmembers, view_channel=True, connect=False)

slate swan
feral lichen
#
a = time.now
time.sleep(60*10)
b = time.now

b - a = solution
#

yes

slate swan
#

Can anyone help me with this?
AttributeError: 'VoiceChannel' object has no attribute 'set_permisisons'
new.set_permissions(publicmembers, view_channel=True, connect=False)

#

can you show code?

#

new.set_permissions(publicmembers, view_channel=True, connect=False)

#

now like whole code lol

#

new = await member.guild.create_voice_channel(f"{member.name}'s Channel")
category = discord.utils.get(member.guild.categories, name="Private Voice Channels")
publicmembers = member.guild.get_role(1009119229229924404)
new.set_permisisons(member.guild.default_role, view_channel=False)
new.set_permissions(publicmembers, view_channel=True, connect=False)
new.set_permissions(member, view_channel=True, priority_speak=True, connect=True)

#

weird

#

why not use overwrites tho

slate swan
#

nice catch

#

ty

#
publicmembers = member.guild.get_role(1009119229229924404)
overwrites = {
    member.guild.default_role: discord.PermissionsOverwrite(view_channel=False),
    publicmembers: discord.PermissionsOverwrite(view_channel=True, connect=False),
    member: discord.PermissionsOverwrite(view_channel=True, priority_speak=True, connect=True ) 
}
await member.guild.create_voice_channel(f"{member.name}'s Channel", overwrites=overwrites)

@slate swan

#

it was a type

#

ik im just showing a more efficient way

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1664519442:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

marble ocean
#

Traceback (most recent call last):
File "d:\Data\alpaca trading bot\main.py", line 10, in <module>
cogs[i].setup(client)
AttributeError: module 'bot' has no attribute 'setup'

naive briar
unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
slate swan
#

how would i get my bot to move a member from one vc to another?

naive briar
unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

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

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

Changed in version 1.1: Can now pass `None` to kick a member from voice.
marble ocean
#

like this:
for cog in cogs:
bot.load_extension(cog)

marble ocean
naive briar
marble ocean
marble ocean
split forge
#

How I add slash commands Can some body help me?

marble ocean
naive briar
split forge
unkempt canyonBOT
#

examples/app_commands/basic.py lines 41 to 44

@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')```
marble ocean
shrewd apex
#

yesh

marble ocean
#

but it says "await" allowed only within async function

naive briar
# marble ocean help please

Are you subclassing the bot? If yes, you can put your load function in the new setup_hook like so:

async def setup_hook(self):
    await load()

If not, you'll have to start the bot with some extra code like this:

import asyncio

...

async def main():
    async with bot:

        await load() # Load cogs
        await bot.start('token') # Run the bot manually

asyncio.run(main()) # Run the main function

There might be another way, but these are what I know.

split forge
#

how I can add my bot slash commands?

#

For easy

slate swan
split forge
#

oh

#

lmao

slate swan
#

client = commands.Bot (command_prefix = '/')

tidal hawk
#

I think he meant interactive slash commands xd

tidal hawk
split forge
naive briar
#

Like discord.py or disnake

split forge
#

py

#

@tidal hawk

naive briar
unkempt canyonBOT
#

examples/app_commands/basic.py lines 41 to 44

@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')```
slate swan
tidal hawk
#

? :D

#

And sends interactive, ephemeral messages and etc..?

#

And converts all existing context commands to slash automatically?

#

That's awesome if it does, something new to me

slate swan
#

i mean

#

it can

#

at least i think lol

tidal hawk
#

What library are you using?

slate swan
#

idfk

#

ahahaha

#

hbu

#

what did you pip install

vestal ruin
#

Hi

#

help

#

@client.command()
async def select(ctx):
await ctx.send("list", components=[
Select(
placeholder="Choose",
options=[
SelectOption(
emoji="😋",
label="Emoji",
description="Emoji1",
velue="e1"
),
SelectOption(
emoji="😀",
label="Emoji2",
description="Emoji2",
velue="e2"
)
]
)
])
res = await client.wait_for("select_option")
await res.respond(content="Вы выбрали тест"+str(res.component.emoji))

#

Error:
File "main.py", line 213
res = await client.wait_for("select_option")
^
IndentationError: unexpected indent

tidal hawk
#

Remove a space from line 213

slate swan
#
  @discord.ui.button(
    label="Create Ticket", style=discord.ui.ButtonStyle.green, custom_id="create_ticket:green"
  )
  async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
    await interaction.response.send_message("A Ticket Is Being Created...", ephemeral=True)```
#

why isnt it working

slate swan
unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
vale wing
#

Not discord.ui.ButtonStyle

slate swan
#

Ohhh oopsss

#

thanks lol

#

The error-

#
2022-09-30 13:43:00 ERROR    discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 229, in setup_tickets
    await ctx.send(embed=embed, view=CreateTicket)
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\context.py", line 841, in send
    return await super().send(
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\abc.py", line 1520, in send
    with handle_message_parameters(
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\http.py", line 187, in handle_message_parameters
    payload['components'] = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 180, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'```
#

the code -

#
class CreateTicket(discord.ui.View):
  def __init__(self):
      super().__init__(timeout=None)
  
  @discord.ui.button(
    label="Create Ticket", style=discord.ButtonStyle.green, custom_id="create_ticket:green"
  )
  async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
    await interaction.response.send_message("A Ticket Is Being Created...", ephemeral=True)

class Bot(commands.Bot):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.persistent_views_added = False

  async def on_ready(self):
      if not self.persistent_views_added:
          self.add_view(CreateTicket())
          self.persistent_views_added = True
          print("Persisitent views added")


@bot.command()
@commands.has_permissions(manage_channels=True)
async def setup_tickets(ctx: commands.Context):
    embed = discord.Embed(title="Create A Ticket!", description="Click The Create Ticket Button Below To Create A Ticket")
    await ctx.send(embed=embed, view=CreateTicket())```
#

view=CreateTicket() in last line

#

thank you so much ill try

naive parcel
#

hi
im uploading my id in stripe for discord bot verification
but discord throws back an error stating that the document type is unexpected

slate swan
#

*button wtf

silk fulcrum
slate swan
#

oh thank youuu

slate swan
silk fulcrum
#

dude is sending verification

#

is it done via code?

slate swan
#

nope

naive parcel
#

not at all

slate swan
#

oh wait nvm

#

I read half the thing, my fault

naive parcel
#

its all right, can you contribute anything to the fixation of my issue?

faint sapphire
#

hi, ive got questions ab a code example using postgres as a db
(ive spent a couple hours learning ab classes before asking questions)
https://gist.github.com/jegfish/cfc7b22e72426f5ced6f87caa6920fd6

my questions are:
-is it normal that its possible to refer to the class before defining it, or is it okay in this example bc they call run() after defining it

-I dont understand the idea of calling run() in a runUntilComplete
(ik this is done to make tasks async, but I dont get it here)

-in this example id have to add the functions start() and logout() inside the class right?

-with the structure of this code id have to put all my bots commands inside of that Bot class? or do i make that Bot class use other classes

slate swan
naive parcel
#

jpeg

#

jpeg and jpg are same

pliant gulch
naive parcel
#

thanks a ton

pliant gulch
#

They would probably have more people who could answer you

naive parcel
#

i never knew this existed

slate swan
#

and I dont think this gist was really helpful anyways
all the database things could have been done within the setup_hook

silk fulcrum
#

me late ofc

faint sapphire
#

ok thanks, ill look up what that is

silk fulcrum
unkempt canyonBOT
#

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

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

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

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

Warning

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

nice thanks

silk fulcrum
faint sapphire
#

very helpful, thank you

pliant gulch
#

You will almost always use asyncio.run instead of run_until_complete here

#

Probably one of the biggest thing about that is, run will do additional cleanup when it closes compared to run_until_complete

#

Like, closing async generators

#

Finishing tasks, etc

slate swan
#
class CreateTicket(discord.ui.View):
  def __init__(self):
      super().__init__(timeout=None)
  
  @discord.ui.button(
    label="Create Ticket", style=discord.ButtonStyle.green, custom_id="create_ticket:green"
  )
  async def create_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
      msg = await button.response.send_message(content="A Ticket Is Being Created...", ephemeral=True)
      overwrites = {
        interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
        interaction.guild.get_role(1009471176264917012): discord.PermissionOverwrite(read_messages=True)
      }
      channel = await interaction.guild.create_text_channel(f"{interaction.user.name}-ticket",
      overwrites=overwrites)
      await msg.edit(f"Channel Created Successfully** {channel.mention}")
      embed = discord.Embed(title="Ticket Created", description=f"{interaction.user.mention} Created A Ticket! \n Click One Of The Buttons Below To Alter The Settings.")
      await channel.send(embed=embed, view=TicketSettings)

class TicketSettings(discord.ui.View):
  def __init__(self):
      super().__init__(timeout=None)

  @discord.ui.button(
    label="Close Ticket", style=discord.ButtonStyle.red, custom_id="ticket_settings:red"
  )
  async def close_ticket(self, button: discord.ui.Button, interaction: discord.Interaction):
    await interaction.response.send_message(content="Ticket Is Being Closed..", ephemeral=True)
    await interaction.channel.delete()
    await interaction.user.send(f"Ticket Closed Successfully! {interaction.channel.mention}")
class Bot(commands.Bot):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.persistent_views_added = False

  async def on_ready(self):
      if not self.persistent_views_added:
          self.add_view(CreateTicket())
          self.persistent_views_added = True
          print("Persisitent views added")


@bot.command()
@commands.has_permissions(manage_channels=True)
async def setup_tickets(ctx: commands.Context):
    embed = discord.Embed(title="Create A Ticket!", description="Click The Create Ticket Button Below To Create A Ticket")
    await ctx.send(embed=embed, view=CreateTicket())```
#

swap button and interaction order again @slate swan

#

im noob

#

thanks

#

@slate swan wait i cant find where

slate swan
slate swan
#

like that?

#

yes

#

thank you i will try

#

install the library

pliant gulch
slate swan
#

its py-cord, not pycord

#

and thats not how you mention versions

slate swan
#

py-cord==2.0.1

#
class CreateTicket(discord.ui.View):
  def __init__(self):
      super().__init__(timeout=None)
  
  @discord.ui.button(
    label="Create Ticket", style=discord.ButtonStyle.green, custom_id="create_ticket:green"
  )
  async def create_ticket(self,  interaction: discord.Interaction, button: discord.ui.Button):
      msg = await interaction.response.send_message(content="A Ticket Is Being Created...", ephemeral=True)
      overwrites = {
        interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
        interaction.guild.get_role(1009471176264917012): discord.PermissionOverwrite(read_messages=True)
      }
      channel = await interaction.guild.create_text_channel(f"{interaction.user.name}-ticket",
      overwrites=overwrites)
      await interaction.response.edit_message(f"Channel Created Successfully** {channel.mention}")
      embed = discord.Embed(title="Ticket Created", description=f"{interaction.user.mention} Created A Ticket! \n Click One Of The Buttons Below To Alter The Settings.")
      await channel.send(embed=embed, view=TicketSettings)

class TicketSettings(discord.ui.View):
  def __init__(self):
      super().__init__(timeout=None)

  @discord.ui.button(
    label="Close Ticket", style=discord.ButtonStyle.red, custom_id="ticket_settings:red"
  )
  async def close_ticket(self,  interaction: discord.Interaction, button: discord.ui.Button):
    await interaction.response.send_message(content="Ticket Is Being Closed..", ephemeral=True)
    await interaction.channel.delete()
    await interaction.user.send(f"Ticket Closed Successfully! {interaction.channel.mention}")

class Bot(commands.Bot):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.persistent_views_added = False

  async def on_ready(self):
      if not self.persistent_views_added:
          self.add_view(CreateTicket())
          self.persistent_views_added = True
          print("Persisitent views added")


@bot.command()
@commands.has_permissions(manage_channels=True)
async def setup_tickets(ctx: commands.Context):
    embed = discord.Embed(title="Create A Ticket!", description="Click The Create Ticket Button Below To Create A Ticket")
    await ctx.send(embed=embed, view=CreateTicket())```
#

yes

#

but i didnt understand how to fix it

faint sapphire
#

u need to add something in the params

slate swan
#

OH

#

I UNDERSTOOD

#

show ur requirements.txt file

#

how do you install reqs then

#

wait i didnt

vale wing
#

!pypi functools

unkempt canyonBOT
vale wing
#

There's probably a mistake in some package's requirements

#

What command did you execute

#

Ok

slate swan
#

how anyone know how i can make my bot send another button once someone clicks a button cause no vids on it or anything

faint sapphire
vale wing
slate swan
faint sapphire
#

oh i thought u wanted that on the same message

slate swan
#

!status

thorny frost
#

someone please help

slate swan
#
@commands.command()
    async def wanted(self, ctx, member: discord.Member = None):
        member = member or ctx.author

        wanted = Image.open("wanted.jpg")

        asset = ctx.author.avatar.url(size=128)

        data = BytesIO(await asset.read())
        pfp = Image.open(data)

        pfp = pfp.resize((177,177))

        wanted.paste(pfp, (120,212))

        wanted.save("profile.jpg")

        await ctx.send(file = discord.File("profile.jpg"))
``` no errors in terminal but i get no command named "wanted'" found
i have error handler for commandnotfound
slate swan
# thorny frost

use pip install discord.py in terminal you haven't done yet

slate swan
#

hmmm

thorny frost
#

visual studio is some sketchy stuff

#

i used to do make bots using replit

slate swan
#

maybe not

thorny frost
#

pls fix

slate swan
thorny frost
slate swan
#

codecamp tutorial?

thorny frost
#

i'm testing the bot

slate swan
#

mhm

thorny frost
#

so i can move further

#

but the stupid module says it's not installed

zealous jay
#

@thorny frost do you have various python versions installed?

thorny frost
slate swan
slate swan
# slate swan yup

could you try printing bot.commands and see if wanted is in the list

#

i have "all cogs are loaded" printed after
await client.load_extension("cogs.cogs.image")

zealous jay
#

was pip list a thing?

slate swan
#

yes it lists all installed libs

#

a command for some reason

slate swan
zealous jay
#

Veseluxe do pip list and see if discord is there

slate swan
#

!paste

thorny frost
#

@zealous jay

zealous jay
#

uh

thorny frost
#

btw can we make bots using visual basic?

slate swan
slate swan
thorny frost
thorny frost
zealous jay
#

idk 🛌

thorny frost
#

so in short replit is the best option if ur making discord bots ||jk||

slate swan
#

unless you get hacker plan

thorny frost
zealous jay
#

Check if visual studio is using the correct interpreter

slate swan
zealous jay
#

bottom right you can see which python version is using

thorny frost
slate swan
#

._.

thorny frost
#

cant find?

zealous jay
#

ú

thorny frost
zealous jay
#

what

thorny frost
#

i have an update tho

zealous jay
#

try to find which python version vs studio is running

thorny frost
#

i have this pyhton installed too

slate swan
# slate swan it is printed

hmm try using the name kwarg in @command decorator
also make sure you saved the file and then rerun the bot

slate swan
#

preferably let 3.19 stay.

#

*3.10

slate swan
zealous jay
#

I think you can change interpreter with Ctrl + Shift + P

slate swan
#

btw @slate swan yk how i can send a message like
shard id 1 is ready in a channel when a shard is ready

slate swan
zealous jay
#

oh

slate swan
slate swan
#

!d discord.on_shard_ready

unkempt canyonBOT
#

discord.on_shard_ready(shard_id)```
Similar to [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") except used by [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient") to denote when a particular shard ID has become ready.
slate swan
#

yeah thats it

#

thats only for AutoSharded(Bot/Client) tho

slate swan
slate swan
#

it wont send both buttons anyone know why
im using nextcord

slate swan
#

no

naive briar
slate swan
#

try changing name

#

of what

#

second button

naive briar
slate swan
#

yuh

#

oh yeah

slate swan
naive briar
slate swan
#

for now i got this

class axn(commands.Bot):
    def __init__(self):
      intents = discord.Intents.all()
      intents.message_content = True

      super().__init__(command_prefix = 'a?', intents=intents)

      async def setup_hook(self) -> None:
        self.add_view(PersistentView())

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')
naive briar
slate swan
#

then where should it be?

naive briar
#

In the same level as on_ready

slate swan
#

got it

slate swan
#

@naive briar

naive briar
# slate swan wb this?

It's pretty much the same thing as commands.Bot but just added sharding to it. You can just subclass it like commands.Bot, although using it while your bot is still very small is not recommended

slate swan
naive briar
slate swan
cloud dawn
#

It will not even shard

slate swan
#

^

#

Each shard can only support a maximum of 2500 guilds, and apps that are in 2500+ guilds must enable sharding.

#

so the instance would work ig

cloud dawn
#

But to be fair idk why they didn't just include it in bot.

slate swan
#

lmao

#

it's too ideal. dpy.

brazen raft
slate swan
cloud dawn
brazen raft
#

Well shard 0 is a shard

cloud dawn
#

Well then the first instance isn't a shard

brazen raft
#

Anyway the point is there is no overhead

#

Unless you need sophisticated sharding

cloud dawn
#

I guess it would be possible to shard across vms

#

To distribute the load iirc thats what mee6 does

limber bison
#

if i type !hello in reply of some message how can i get the orignal message author member object ?

dull terrace
robust fulcrum
#

Guys is there any library to use top.gg webhook in dpy?

brazen raft
#

They have an asynchronous API for Python

slate swan
# limber bison if i type !hello in reply of some message how can i get the orignal message auth...

!d discord.Message.reference returns a MessageReference object which has a cached_message attribute which may or may not be available. So, you'll have to check if cached_message is not None, and if it is not None, you can access the author of that message using the author attribute. Whereas if cached_message is None, you'll have to use the channel_id and message_id attributes of the MessageReference object to fetch the message. (Note that the message_id attribute can also be None)

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

slate swan
#

you can simply check if message_id is None in the first place and if it is None, the cached_message will also be None

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
#

oh

thorny frost
slate swan
#

thats weird

thorny frost
slate swan
#

my code is working

#

'just not that command

thorny frost
#

look

faint sapphire
#

ure using a tutorial thats like 4+ years old

thorny frost
#

tell me how to fix it

faint sapphire
thorny frost
slate swan
#

@faint sapphire

naive briar
unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

Oh

naive briar
#

At least that's what I see in the error

slate swan
#

i wiil try now wait

vale wing
#

@slate swan you parse unexpected string as first argument of superclass init for no reason

#

Wtf

slate swan
#

OOP

#

Exception has occurred: TypeError
expected token to be a str, received <class 'NoneType'> instead
File "C:\Users###\Desktop#################\Bot.py", line 36, in <module>
client.run(token)

vale wing
slate swan
faint sapphire
#

happened to me

slate swan
naive briar
unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
vale wing
#

You parse key not the value

#

Why would you need to parse a value to get a value itself

slate swan
vale wing
#

Enable logic

slate swan
#

i dont need them?

naive briar
#

Yes

slate swan
#

oh okay

#

i will delete

#

ill try now

faint sapphire
#

u still have 8 errors/warnings tho

slate swan
slate swan
slate swan
#

oops

rare echo
#

min_lengh go hard

thorny frost
#

me beginner of py, i use vb mostly

slate swan
#

lengh 😳

rare echo
slate swan
rare echo
slate swan
slate swan
slate swan
rare echo
thorny frost
vale wing
#

We need a bot that would lock "i am py beginner" ppl out of this channel and only let them back when they "know oop"

slate swan
slate swan
thorny frost
rare echo
slate swan
#

what do i change

vale wing
#

Just saying

faint sapphire
#

oop is just to do with classes yh

honest shoal
rare echo
vale wing
#

Basic oop is just classes and objects, advanced one would be like inheritance, polymorphism and other OOP principles

faint sapphire
#

i see

slate swan
#

2022-09-30 171141 ERROR discord.ui.view Ignoring exception in view <TicketSettings timeout=None children=3> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Add User' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 291, in add_user
await interaction.response.send_modal(AddUser(interaction.channel))
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\interactions.py", line 851, in send_modal
params = interaction_response_params(InteractionResponseType.modal.value, modal.to_dict())
AttributeError: 'AddUser' object has no attribute 'to_dict'

faint sapphire
#

inheritance is still classes from what ive seen

slate swan
# thorny frost how?

it's really hard. so you gotta cope, right

  1. Make sure that the IDE is open
  2. Look at the top-right corner
  3. You'll see a button that resembles X
  4. Locate your cursor
  5. Move your cursor to the top right corner to where the button X is "situated"
  6. The X symbol turns red
  7. Left Click.
vale wing
#

Why the hell is there instagram emoji

slate swan
#

and you can always use that link AKG sent.

slate swan
slate swan
faint sapphire
#

actually yh weird, zuck prob payed for this

slate swan
#

but please can soeone help me w that code

rare echo
slate swan
#

okay thanks

thorny frost
honest shoal
#

reminds me of

slate swan
#

,

rare echo
honest shoal
faint sapphire
#

lmfao

rare echo
slate swan
#

Collecting keepalive
Using cached keepalive-0.5.zip (10 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [1 lines of output]
error in keepalive setup command: use_2to3 is invalid.
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

C:\Users###>

slate swan
unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

._.

robust fulcrum
#

Guys how we can loop list items in a discord embed description?

slate swan
robust fulcrum
robust fulcrum
tidal hawk
slate swan
#
embed = discord.Embed(..., description="")
for element in your_list:
  embed.description += element
#

that?

robust fulcrum
#

Ye!

#

Thanks a lot!

slate swan
#

that's literally string con-........nvm

cloud dawn
slate swan
#

contractions

cloud dawn
slate swan
#

does any one know how to make a command that can be runned only twice by user?

cloud dawn
#

Needs more context

slate swan
cloud dawn
#

Like never run again?

slate swan
#

yea

cloud dawn
#

Use a database.

slate swan
#

if he calls it again then the bot says out of attempts

slate swan
cloud dawn
#

It depends on what you want to do.

#

I mean out of attempts does that mean it can get reset?

slate swan
#

by another command yeah

cloud dawn
#

Then you don't need to use a database.

slate swan
#

how so?

cloud dawn
#

Did you make the command in a class?

slate swan
#

nope every command is separate

cloud dawn
#

Well I'd recommend to use a class for this.

#

Cogs

slate swan
#

im not well used to cogs

cloud dawn
#

I highly recommend getting started with it.

slate swan
#

ill look into it

cloud dawn
#

Read the error.

#

What does the last line say?

slate swan
glad cradle
#

you can't have the same custom_id for two components, reflect about it, it doesn't make sense to have the same custom_id

slate swan
#

tried a bunch of things still wont work so came here

#

okay whats a custom id lets start off with that

glad cradle
#

you need to change the custom_id kwarg value of the second button

slate swan
#

o

#

smh how didnt i see that ty guys first bot project im making so yeah

glad cradle
#
Components, aside from Action Rows, must have a custom_id field. This field is defined by the developer when sending the component payload, and is returned in the interaction payload sent when a user interacts with the component. For example, if you set custom_id: click_me on a button, you'll receive an interaction containing custom_id: click_me when a user clicks that button.

custom_id must be unique per component; multiple buttons on the same message must not share the same custom_id. This field is a string of max 100 characters, and can be used flexibly to maintain state or pass through other important data.

https://discord.com/developers/docs/interactions/message-components#custom-id

slate swan
whole hull
slate swan
whole hull
#

guys what can i do now

slate swan
cloud dawn
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

thorny frost
#

my discord bot sending dms but not responding in channels

#

wtf?

whole hull
naive briar
slate swan
naive briar
#

And also make sure to select some intents for it, or just use Intents.default() for default intents

slate swan
#

anyone know how i can make my bot send another button after i click on 1 of the buttons heres my code so far

whole hull
#

do you know what is that ?

slate swan
glad cradle
naive briar
glad cradle
whole hull
#

alright

#

wait

slate swan
whole hull
#

yeahhh good thanks :D

#

do you guys know whats the best way to learn discord py

glad cradle
# slate swan nextcord

so in your button callback you should create a button object

new_button = nextcord.ui.Button(...)
# add the button to the view with
self.add_item(new_button)
# edit the message with the new view
await inter.edit_original_message(view=self)
glad cradle
#

remember that you should reset the view every time the init function is called

#

send your code

glad cradle
slate swan
#

i have a dynamic embed that can keeps bringing up errors because its too big discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In embeds.0.fields.0.value: Must be 1024 or fewer in length. is there a way to add an embed and put the stuff that is making it go over the limit onto that

slate swan
cloud dawn
slate swan
#

is it the same thing for just normal messages? @glad cradle cause i also want my bot to send normal messages after the button is clicked if that makes sense

#

@obsidian canopy

#

2 secs ill show a example

glad cradle
slate swan
#

!tags

unkempt canyonBOT
#
Available tags

» defaultdict
» dict-get
» dictcomps
» docstring
» dotenv
» dunder-methods
» empty-json
» enumerate
» environments
» except
» exit()
» f-string
» f-strings
» faq
» floats

robust fulcrum
#

Guys why i am getting syntax error in it?

            for i in counter_items:
                embed.description += name=f"{self.emo.get(i)}**{i}** - {counter_items.get(i)}x\n"
cloud dawn
#

I don't recommend sending error embeds tough... just fix it.

slate swan
slate swan
#

it can vary from person to person

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
slate swan
robust fulcrum
slate swan
#

@glad cradle where do i put it so it sends a normal message new message after the button click
heres the code

glad cradle
# slate swan what is a paginator lmao

it's an embed that has multiple page, you control the pages with some buttons, paginators allow you to send a single message with "multiples embeds" (though you're not really sending all the embeds in the same moments, you're just editing the original message with the corrispondent embed) you can see it as a book

slate swan
#

will make more sense then

glad cradle
#

if it can help you yes

slate swan
#

alright ill msg u the invite

whole hull
#

it doesnt even print

#

anyone knows why pls

sick birch
whole hull
#

yes

#

but not "."

sick birch
#

Oh, you probably need message content intents then

#

make sure you enable it in your dashboard and in your code by using intents.message_content = True

whole hull
#

oh there

#

im gonna enable all intents toggles

slate swan
# whole hull oh there

it's better to only enable the ones you require. otherwise it would be a waste of resources

whole hull
#

but i don't know what i need

#

and i everytime need to enable one of them

sick birch
#

turn off the rest of them to minimize computing power

#

computing power doesn't grow on trees!!

whole hull
slate swan
#

nor do computers. that's not even hypothetical, Robin

cloud dawn
slate swan
#

yes, pandas grow it

whole hull
#

still doesnt print

sick birch
slate swan
whole hull
#

not run

slate swan
#

it did

whole hull
#

oh nvm

#

wait where

#

it didn't print

slate swan
cloud dawn
whole hull
#

still locked there

brazen raft
#

It printed the dot on the previous line

#

Or is it the end of the last log's sentence

slate swan
whole hull
slate swan
#

^

whole hull
#

ill check

#

...

cloud dawn
#

Intents.all()

slate swan
#

can someone help me with reaction roles? i dont understand how to do that

brazen raft
#

Make sure you enable the intent in your code as Ashley has said

quaint epoch
brazen raft
#

Now you may want to refresh your bot token

whole hull
sick birch
#

Also, any tracebacks?

slate swan
#

and there's also an example to reaction roles in the dpy repo. you could refer to that if you haven't started and just need a basic idea ig